2013-10-19 315 views
0

我正在做一个简单的媒人作为JAVA的学习项目。我的计划到目前为止只是提出几个问题,但我想要做具体的性别问题,所以我问他们的性别(男或女),然后试图添加一条消息,只有当性别为m时才显示。对话应该说“做得好,你是男性!”。否则它重新启动方法。每次,无论我输入什么,它都会重新启动程序。如果语句被忽略

这里是我的代码:

import javax.swing.JOptionPane; 

public class Main { 

    public static void main(String[] args){ 
     setVars(); 
    } 

    public static void setVars(){ 
     String name = JOptionPane.showInputDialog(null, "What is your name?"); 
     String sAge = JOptionPane.showInputDialog(null, "What is your age?"); 
     String sex = JOptionPane.showInputDialog(null, "What is your sex?\n(Enter m or f)"); 

     if (sex == "m"){ 
      JOptionPane.showMessageDialog(null, "Well done, you are male.\nKeep Going!"); 
     } 
     int age = Integer.parseInt(sAge); 
     String chars = JOptionPane.showInputDialog(null, "Name three charectaristics"); 
    } 
} 
+0

字符串总是比较使用'equals()'方法编辑。 –

+0

即使“sex”的值是“m”,“m”也不会与“sex”相同。字符串比较应该使用'equals()'(如上所述)来完成,比较平等而不是身份。 – thriqon

回答

1

尝试

if ("m".equalIgnoreCase(sex)) 

你应该使用等于为检查其引用

比较字符串值和==
1

你的代码应该是:

if ("m".equals(sex)) { 
    // 
} 

==比较对象的地址/引用
.equals比较对象的值

+1

它应该是'“m”.equals(sex)'因为'sex'可能是'null' –

1

在Java中,你不”随着==比较字符串,你必须将它们与Stringequals()方法进行比较。字符串有这种方法的两种变体:区分大小写的equals()和区分大小写的equalsIgnoreCase()。在下面的例子中,你可以使用任何一个。

试试这个:

if(sex.equalsIgnoreCase("m") { 
    ... 
} 

还是要谨防空...

if("m".equalsIgnoreCase(sex)) { 
    ... 
} 
0

因为String是一个对象,并不像int数据类型,当涉及到比较两个字符串是做通过.equals()方法:

package example; 

import javax.swing.JOptionPane; 
public class Main { 
    public static void main(String[] args){ 
     setVars(); 
    } 
    public static void setVars(){ 
     String name = JOptionPane.showInputDialog(null, "What is your name?"); 
     String sAge = JOptionPane.showInputDialog(null, "What is your age?"); 
     String sex = JOptionPane.showInputDialog(null, "What is your sex?\n(Enter m or f)"); 
     if (sex.equals("m")){ 
      JOptionPane.showMessageDialog(null, "Well done, you are male.\nKeep Going!"); 
     } 
     int age = Integer.parseInt(sAge); 
     String chars = JOptionPane.showInputDialog(null, "Name three charectaristics"); 
    } 
}