使用扫描仪的循环永远不会满足条件

时间:2017-10-10 01:43:37

标签: java while-loop java.util.scanner

public class ex1 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Please enter a series of strings each followed by the enter key. When you'd like to end thr program simply type 'quit': \n");
    Scanner scan = new Scanner(System.in);

    ArrayList<String> inputList = new ArrayList<String>(); // creates a list to store user input

    String input = scan.nextLine(); //takes the scanner input
    while(input != "quit") { //makes sure its not equal to quit
        //System.out.println(input);
        inputList.add(input);
        input = scan.nextLine();
    }
    scan.close();       
    System.out.println("The number of strings enetered was: " + inputList.size());
    System.out.println("The strings you entered were as follows");
    for (String i: inputList) {
        System.out.println(i);

    }

} }

我尝试使用前面的代码使用enter键从用户那里获取一系列输入,如果他们进入quit,我就会结束程序。然而,条件永远不会满足,而while循环永远不会结束,我无法理解为什么

2 个答案:

答案 0 :(得分:0)

 while(!input.equals("quit")) { //makes sure its not equal to quit
        //System.out.println(input);
        inputList.add(input);
        input = scan.nextLine();
    }

您应该使用上面显示的equals方法来比较字符串。 Java提供了equals方法来比较两个字符串的内容。 ==!=运算符用于比较对象的相等性。

答案 1 :(得分:0)

a == b返回true,当且仅当 a 指向与 b

相同的对象时

应该使用equals方法,因为String类实现它,因此,如果 a 包含与 b 相同的字符,它将返回true

while (!input.equals("quit")) { ... }
相关问题