我希望每次用户输入新字符串时,用户输入都是添加到我的数组列表中的字符串。我认为我在正确的轨道上,但我不完全确定,因为我无法输出我的阵列。这是我的代码。
System.out.println("input your word list");
Scanner scanner = new Scanner(System.in);
String phrase;
//not sure if phrase =""; is necessary but eclipse suggested it at one point
phrase = "";
ArrayList<String[]> wordlist = new ArrayList<String[]>();
for(int i=0; i<phrase.length();i++){
phrase = scanner.nextLine();
wordlist.add(new String[] {phrase});
}
System.out.println(phrase);
System.out.println(Arrays.toString(wordlist));
答案 0 :(得分:1)
编辑: - 这里你把所有输入都带到数组列表,直到用户输入quit并显示所有输入: -
public static void main(String[] args)
{
System.out.println("input your word list");
Scanner scanner = new Scanner(System.in);
ArrayList<String> wordlist = new ArrayList<String>();
String input = "";
while(!input.toLowerCase().equals("quit"))
{
input = scanner.nextLine();
if(!input.toLowerCase().equals("quit"))
wordlist.add(input);
}
for(int i = 0; i < wordlist.size(); i++)
{
System.out.println(wordlist.get(i));
}
}
答案 1 :(得分:1)
使用ArrayList<String>
代替ArrayList<String[]>
是否可能成为解决方案?在这种情况下,你可以这样做:
Scanner scan = new Scanner(System.in);
ArrayList<String> wordList = new ArrayList<String>();
for (int i=0; i<3; i++){ //not sure what you're doing with your loop
//so will just get 3 inputs
wordList.add(scan.next());
}
然后每次打印出来,你会这样做:
for (int i=0; i<wordList.size(); i++){
System.out.println(wordList.get(i));
}
或者,如果你更喜欢 - 每个:
for (String word : wordList){
System.out.println(word);
}