两个带有不同变量的if语句

时间:2016-10-14 05:34:22

标签: java if-statement

好的,所以我试着这样做,如果这个人不想进入他们的年龄,程序将打印出不同的答案。但是,当我这样做时,它给了我一个错误的字符串。我使用//来制作它所以int答案没有被播放然后它起作用了。我究竟是如何做到这一点所以他们都为同一个问题工作?我搜索了一个答案,但我似乎无法找到它,所以如果有这个链接,请链接我。谢谢!

   System.out.println("So how old are you?");

   TimeUnit.SECONDS.sleep(2);

   System.out.println("If you dont want to answer you dont have to.   ");

   Scanner scan4 = new Scanner (System.in);
   String user_imput_string1 = scan.nextLine();

   if (user_imput_string1.equals("I dont know")) {
       System.out.println("Ah thats cool. You look great regardless of your age anyway");
   } else {
       System.out.println("Ah thats cool. You look great regardless of your age anyway");
   }

3 个答案:

答案 0 :(得分:1)

您需要将String转换为int才能将值与30进行比较。但是,查看代码时,您似乎已经有两个不同的变量user_imput_string1user_imput_int,后者仍然是一个字符串。

以下是您可以使用的示例代码,以便从String正确转换为int:

int result = Integer.parseInt(user_imput_int);
if (result > 30){
// do whatever
}

另外,作为旁注,您拼写输入错误。

答案 1 :(得分:0)

您可以通过捕获异常

来实现此目的
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("So how old are you? ");
    String age = scanner.next(); //Read string by default
    try{
       int actualAge = Integer.parseInt(age);
       //do your stuff with age
    }catch(Exception e){ //Raises NumberFormatException if it's not a number
       //e.printStackTrace();
       System.out.println("Ah thats cool. You look great regardless of your age anyway");
    }
  }

答案 2 :(得分:0)

代码如下,我希望它可以帮到你。

        System.out.println("So how old are you?");
        TimeUnit.SECONDS.sleep(2);
        System.out.println("If you dont want to answer you dont have to.   ");
        Scanner scan = new Scanner(System.in);
        String user_imput_int = scan.next();
        if ("I dont know".equals(user_imput_int)) {
            System.out.println("Ah thats cool. You look great regardless of your age anyway");
        } else {
            try {
                int age = Integer.parseInt(user_imput_int);
                if(age > 30)
                {
                    System.out.println("Oh wow you look so good");
                }
                else {
                    System.out.println("Oh thats ok. You look great regardless");
                }
            } catch (Exception e) {
                System.out.println("your input is either 'I dont know' or int number");
            }
        }