我正在努力实现 System.exit(0);
在java中,当在控制台输入 "exit "一词时,终止我的程序。我写了下面的方法。
public static void exit(){
Scanner input = new Scanner(System.in);
Str1 = input.next(String);
if (str1 = "exit"){
System.exit(0);
}
else if (str1 = "clear"){
System.out.println("0.0");
}
}
但似乎并不奏效。 有人有什么建议吗?
ThanksP.S "clear "只是应该在向控制台输入 "clear "时返回0.0,如果你还看不出来的话。
比较字符串与 equals()
不与 ==
.
原因是 ==
只是比较对象引用基元,而String的 .equals()
方法检查平等。
if (str1.equals("exit")){
}
并且还
else if (str1.equals("clear")){
}
if(str.equals("exit"))
或
if(str.equalsIgnoreCase("exit"))
或
if(str == "exit")
而不是
if (str1 = "exit"){
随着 if (str1 = "exit")
你可以用分配而不是比较。equals()
方法。
使用 String.equals(String other)
函数来比较字符串,而不是用 ==
操作符。
该函数检查字符串的实际内容,即 ==
操作符检查对象的引用是否相等。 请注意,字符串常量通常是 "内定 "的,因此,两个具有相同值的常量实际上可以通过比较 ==
但最好不要依赖它。
所以使用。
if ("exit".equals(str1)){
}
除了... equals()
జజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజ input.next(String pattern);
需不需要 String
数据类型
将你的代码改为。
public static void exit(){
Scanner input = new Scanner(System.in);
str1 = input.next(); //assumed str1 is global variable
if (str1.equals("exit")){
System.exit(0);
}
else if (str1.equals("clear")){
System.out.println("0.0");
}
}
注释 : http:/www.tutorialspoint.comjavautilscanner_next_string.htm