用于存储用户输入的Java Arraylist

嗨,我是arraylists和java的新手,我想知道是否有人可以帮助我或指导我如何创建一个程序,允许用户从键盘重复输入目录条目并将它们存储在arraylist中。

enter name: enter telephone number: 

然后询问用户是否想要输入另一个

 enter another: Y/N 

谢谢

您仍然可以使用两个ArrayLists,或者创建一个具有name和phone属性的类,然后创建该类对象的一个​​ArrayList。

这里显示的第一种方法

 import java.util.ArrayList; import java.util.Scanner; public class AAA { public static void main(String[] args) { ArrayList name = new ArrayList(); ArrayList phone = new ArrayList(); Scanner sc = new Scanner(System.in); while (true) { System.out.println("Please enter your name: "); name.add(sc.next()); System.out.println("Please enter your number: "); phone.add(sc.nextInt()); } } } 
 import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Tester { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub List directoryNames= new ArrayList(); String input=getDirectoryName(); String directoryPath=""; String userChoice=""; String[] inputTokens=input.split(" "); if(inputTokens.length>1) { directoryPath=inputTokens[0]; userChoice=inputTokens[1]; } else { directoryPath=inputTokens[0]; } while(!"q".equalsIgnoreCase(userChoice)) { directoryNames.add(directoryPath); input=getDirectoryName(); inputTokens=input.split(" "); if(inputTokens.length>1) { directoryPath=inputTokens[0]; userChoice=inputTokens[1]; } else { directoryPath=inputTokens[0]; } } } public static String getDirectoryName() { String input=""; System.out.println("Please Enter Directory name . If you want to quit press q or Q at the end of directory name \n "); System.out.println("\n Example  q"); Scanner in = new Scanner(System.in); input=in.nextLine().trim(); return input; } } 

您似乎想要使用Map而不是数组列表。 您想使用.put(k,v)方法来存储输入。

 Map newMap= new Map(); newmap.put(inputName,inputNum); 

链接到Map API

 import java.util.*; class simple { public static void main(String args[]) { ArrayList al=new ArrayList(); ArrayList al1=new ArrayList(); Scanner ac=new Scanner(System.in); al.add(ac.next()); al1.add(ac.nextInt()); Iterator itr=al.iterator(); Iterator itr1=al1.iterator(); while(itr.hasNext()&& itr1.hasNext()) { System.out.println(itr.next()); System.out.println(itr1.next()); } } }