如何在Message Dialog中正确使用命令“if”?

时间:2013-08-24 08:39:22

标签: java string swing conditional

我是Java新手。我想问一下如何在消息对话框中使用 if

If "age" under 15, add message to new line of Message Dialog-

“你真是太宝贝了”

我写了这些代码,但这是错误的。请帮助。

import javax.swing.JOptionPane;

 public class Isim {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    String name, age, baby;
    name = JOptionPane.showInputDialog(null, "Enter Your name");
    age = JOptionPane.showInputDialog(null, "Enter Your Age");

    int i = new Integer(age).intValue();
    baby = "You`re so baby";

    JOptionPane.showMessageDialog(null, "Your Name is: "+name+"\n"+"Your Age is: "+age+"\n"+if (i < 15){baby});
 }
}

5 个答案:

答案 0 :(得分:4)

使用Conditional operator

JOptionPane.showMessageDialog(null, "Your Name is: "+name+"\n"+"Your Age is: "+age+"\n" + 
                                    (i < 15 ? baby : ""));

您还可以使用String.format方法来避免这些连接:

JOptionPane.showMessageDialog(null, String.format("Your Name is: %s\n. Your Age is: %d\n. %s", name, age, (i < 15? baby: ""));

答案 1 :(得分:3)

对于你的和其他启发,​​这就是解决问题的方法:

public static final String babyMessage = " You`re so baby";
public static final int notABabyAge = 15;

public static String generateMessage(String name, int age) {
  StringBuilder sb = new StringBuilder("Your name is: ");
  sb.append(name);
  sb.append(".  Your age is: ");
  sb.append(age);
  sb.append(".");
  if(age < notABabyAge) sb.append(babyMessage);
  return sb.toString();
}



public static void main(String args[]) {
    String name, age, message;
    name = JOptionPane.showInputDialog(null, "Enter Your name");
    age = JOptionPane.showInputDialog(null, "Enter Your Age");

    //Possible NumberFormatException here, enter aaa in the dialog, and boom.
    int i = new Integer(age).intValue();  
    message = generateMessage(name,age);

    JOptionPane.showMessageDialog(message);
}

这种问题经常出现问题。通常在与应用程序中的数据库交互时。通常,我们最终使用变量和硬编码字符串的组合构造SQL语句。

对于硬编码字符串,它们通常最好是静态的和最终的。对于诸如notABabyAge之类的变量,这些类型应该被编码,以便它们可以通过在应用程序外部发生的配置进行更改。

捕获NumberFormatException很重要,因为人们总是试图破坏你的代码。

答案 2 :(得分:2)

您也可以这样做,以获得更易读的代码:

String age = JOptionPane.showInputDialog(null, "Enter your age");
int ageInt = new Integer(age).getValue();

String babe = "";
if(ageInt < 14){
    babe = "You're so baby";
}

JOptionPane.showMessageDialog(null,"Your Name is: "+name+"\n"+"Your Age is: "+age+"\n"+baby);

答案 3 :(得分:1)

使用"Your Name is: "+ name + "\n" + "Your Age is: " + age + "\n" + (i < 15 ? "baby" : "")

有关详细信息,请参阅this链接。

答案 4 :(得分:1)

试试这个:

JOptionPane.showMessageDialog(null, "Your Name is: "+name+"\n"+"Your Age is: "+age+"\n"+ (i < 15) ? baby : String.Empty);

它评估条件,在这种情况下为i < 15,如果它的计算结果为true,那么它将返回在?之后的内容,在这种情况下为baby,否则后面的内容为:,一个空字符串(String.Empty)。