2016-01-11 66 views
0

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

回答

1

在你的代码中,你要求插入两个单词。只要删除其中的一个。

使用这种方式:

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

没错@Titus,只是编辑。 :) – slackmart

2

问题与您的代码是,你正在做console.next()两次。 1st如果条件和 第二次添加到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(); 
} 
}