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);
}
}}
我正在尝试使用前面的代码从用户那里获取一系列输入,如果他们输入 quit,我将结束程序。但是条件永远不会满足,while循环永远不会结束,我不明白为什么
while(!input.equals("quit")) { //makes sure its not equal to quit
//System.out.println(input);
inputList.add(input);
input = scan.nextLine();
}
应使用equals
如上所示的方法来比较字符串。Java 提供了 equals 方法来比较两个字符串的内容。 ==
和!=
运算符用于比较对象相等性。
a == b
返回 true,当且仅当 a 指向与 b 相同的对象
应使用 equals
方法,因为 String 类实现了它,以便如果 a 包含与 b 相同的字符,它将返回 true。
while (!input.equals("quit")) { ... }