过去几个小时我一直在做这方面的大量研究,没有运气。我很确定这是.next()或.nextLine()的问题(根据我的搜索)。但是,没有什么能帮助我解决我的问题。
当我运行下面的代码时,我必须输入两次输入,然后只有一个输入被添加到arrayList中(当你打印arrayList的内容时可以看到它。)
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester{
public static void main(String[] args) {
AddStrings();
}
public static void AddStrings() {
Scanner console = new Scanner(System.in);
ArrayList<String> strings = new ArrayList<String>(); //this arraylist will hold the inputs the user types in in the while loop below
while(true) {
System.out.println("Input file name (no spaces) (type done to finish): ");
if(console.next().equals("done")) break;
//console.nextLine(); /*according to my observations, with every use of .next() or .nextLine(), I am required to type in the same input one more time
//* however, all my google/stackoverflow/ reddit searches said to include
//* a .nextLine() */
//String inputs = console.next(); //.next makes me type input twice, .nextLine only makes me do it once, but doesn't add anything to arrayList
strings.add(console.next());
}
System.out.println(strings); //for testing purposes
console.close();
}
}
答案 0 :(得分:2)
您的代码问题在于您正在执行两次console.next()。 1st inside if if condition and 添加到 ArrayList 时的第二个。 正确的代码:
public class TestClass{
public static void main(String[] args) {
AddStrings();
}
public static void AddStrings() {
Scanner console = new Scanner(System.in);
ArrayList<String> strings = new ArrayList<String>(); //this arraylist will hold the inputs the user types in in the while loop below
while(true) {
System.out.println("Input file name (no spaces) (type done to finish): ");
String input = console.next();
if(input.equals("done")) break;
strings.add(input);
System.out.println(strings);
}
System.out.println(strings); //for testing purposes
console.close();
}
}
答案 1 :(得分:1)
在您的代码中,您要求插入两个单词。只需删除其中一个。
以这种方式使用:
String choice = console.next();
if (choince.equals('done')) break;
strings.add(choice);