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循环永远不会结束,我无法理解为什么
答案 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")) { ... }