if语句有问题

时间:2014-11-14 23:53:01

标签: java

System.out.println("Aside from that how old are, because I'm 15.");
String age = input.nextLine();
  

下一行有问题,但不知道netbeans上的原因。我认为它必须与二十几岁做点什么。

if(age > 20){
System.out.println("Were not really the same age.");
}

3 个答案:

答案 0 :(得分:2)

您正在将String对象与整数进行比较。 首先将String转换为整数,然后比较整数。 为此,请使用Integer.parseInt(age)。这将返回一个相等的整数 用字符串写的数字。

String age = input.nextLine();
int ageInteger = Integer.parseInt(age);
if (ageInteger > 20) {
    System.out.println("...");
}

答案 1 :(得分:0)

你可以做2种方式

  1. 您可以将字符串转换为整数:
  2.         
      System.out.println("Aside from that how old are, because I'm 15.");
      String age = input.nextLine();
      int ageInInt = Integer.parseInt(age);
      if(ageInInt > 20){
          System.out.println("Were not really the same age.");
      }
    

    或2.您可以从输入中读取输入内容:

    System.out.println("Aside from that how old are, because I'm 15.");
    int ageInInt = input.nextInt();
    if(ageInInt > 20){
        System.out.println("Were not really the same age.");
    }
    

答案 2 :(得分:-1)

变化:

String age = input.nextLine();

为:

int age = input.nextInt();