扫描仪要求我输入两次,只为一次注册



在过去的几个小时里,我一直在做大量的研究,但运气不佳。我很确定这是.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();
}
}

代码的问题是您要执行console.next()两次。如果条件和在添加到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();
}
}

在代码中,您要求插入两个单词。只需移除其中一个即可。

这样使用:

String choice = console.next();
if (choince.equals('done')) break;
strings.add(choice);

最新更新