2016-10-14 93 views
-1

好吧,我試圖做到這一點,如果這個人不想進入他們的年齡,程序會打印出不同的答案。但是,當我這樣做,它給了我一個錯誤的字符串。我使用//來創建它,所以int的答案不會被播放,它的工作。我究竟如何做到這一點,所以他們都爲同一個問題工作?我搜索了一個答案,但我似乎無法找到它,所以如果有這個鏈接,請鏈接我。謝謝!兩個if語句有不同的變量

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

@KevinEsche與您的評論有點混淆。你是說我不能同時擁有一個字符串和一個int有一個問題的單獨變量? –

+0

對不起,在第二部分中使用'String'的時候會錯過它。 [檢查這個問題,它應該是相關的](http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – SomeJavaGuy

+0

@NateCraft嘿內特,它似乎就像刪除了具有'user_imput_int'的代碼的第二部分。 – kbunarjo

回答

1

您將需要字符串轉換成int類型,以價值比較30.然而,看着你的代碼,你似乎已經兩個不同的變量,user_imput_string1user_imput_int,後者仍然是一個字符串。

下面是示例代碼,你可以使用以便正確地從一個字符串轉換爲int:

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

此外,作爲一個側面說明,你在拼寫輸入錯誤。

+0

謝謝一個男人。還有我太笑了一下,我無法拼寫輸入 –

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

謝謝你。在我的課程中還沒有完全掌握整數.parseInt,所以它很好理解=) –