2013-10-11 66 views
1

我试图在java中实现System.exit(0);来终止我的程序,当单词“exit”输入到控制台。我写了下面的方法:这段代码为什么不终止我的程序? Java

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"); 
    }  
} 

它似乎并没有工作。有没有人有什么建议?

谢谢 P.S“清除”只是应该返回0.0当“清除”进入控制台,如果你不能告诉。

+0

如果你想用Google如何比较你会得到字符串你的答案。 :) – NewUser

+0

btw除了等于(),我认为你的代码有一些小错误。 Str1和str1是不同的。 – gjman2

+1

你有没有放过它?无论如何都调用System.exit(0)? – JulianG

回答

5

将字符串与equals()比较而不是与==比较。

原因是==只比较对象引用/基元,其中as String的.equals()方法检查相等性。

if (str1.equals("exit")){ 

} 

并且还

else if (str1.equals("clear")){ 

} 

强权有用:What are the benefits of "String".equals(otherString)

+0

更好 - ''退出“.equals(str1)' – sanbhat

+1

@sanbhat补充说。Thankyou :) –

1
if(str.equals("exit")) 

if(str.equalsIgnoreCase("exit")) 

if(str == "exit") 

代替

if (str1 = "exit"){ 
1

使用String.equals(String other)功能比较字符串,而不是==操作。

函数检查字符串的实际内容,==运算符检查对象的引用是否相等。请注意,字符串常量通常是“interned”的,这样两个具有相同值的常量实际上可以与==进行比较,但最好不要依赖它。

所以使用:

if ("exit".equals(str1)){ 

} 
+0

这些都非常有帮助,谢谢。但是,我实现了这些更改,并且控制台仍在抛出异常而不是终止程序。 –

+0

投掷什么异常? @CharlieTidmarsh – gjman2

+0

@CharlieTidmarsh你能告诉我你的例外吗? –

1

随着if (str1 = "exit")您使用,而不是一个比较的分配。 您可以使用equals()方法进行比较。

0

此外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.com/java/util/scanner_next_string.htm

+2

将'str1 = input.next();'改为'String str1 = input.next();',除非'str1'是一个全局变量 – JulianG

+0

@JulianG注意。谢谢 – gjman2