2016-06-28 52 views
1

我正在做一個程序,要求你的年齡,但它不工作。 首先它會詢問掃描儀模塊的年齡,並將您的年齡放入變量中。我想在結束你的年齡輸出,但它需要一個整型,所以如果你把一個字符串或其他什麼東西它給出了一個錯誤:我該如何讓一個程序在循環中獲得一個變量? (java)

Exception in thread "main" java.util.InputMismatchException 
at java.util.Scanner.throwFor(Unknown Source) 
at java.util.Scanner.next(Unknown Source) 
at java.util.Scanner.nextInt(Unknown Source) 
at java.util.Scanner.nextInt(Unknown Source) 
at org.asking.age.main(asking.java:18) 

我不想讓他這麼一說,而不是錯誤):請只輸入一個介於1和100之間的數字,如果輸入其他數字,則輸入1-100之間的數字。如果你輸入了錯誤的號碼,它必須「重新啓動」,如果它是一個好號碼,它必須結束。

我嘗試一個循環:

(I =年齡從掃描儀)

while(i>100 || i>0) 
     { 
      if (a < 100 || a > 0) { 

       System.out.println("please only enter a number between 1 and 100"); 
       System.out.println("how old are you?"); 
       Scanner s = new Scanner(System.in); 
       int a = s.nextInt(); 

     { 
System.out.println("you are " + a + "years old") 
    }}}}} 

,但在開始時的 '如果' 斜面到達的變量。是否存在其他/任何方式來做到這一點?

感謝您的幫助,而我的英語不好:)

感謝對不起@TheLostMind現在幫助我得到這個代碼:

,但我不知道如何使用if(> 0 & & < 100,比賽不工作

public static void main(String[] args) { 
    System.out.println("how old are you?"); 

    Scanner h = new Scanner(System.in); 
    String a= h.nextLine(); 

    String str = a; 

    String matches=("\\d+"); 

    Integer.parseInt(a); 



    { 
do { 


    System.out.println("please only enter a number between 1 and 100"); 
    System.out.println("how old are you?"); 
    h.nextLine(); 

} while(a>0 && a<100); } 
} 
} 
+0

在while循環外定義您的掃描儀 –

+3

對循環外的'Scanner'和'int a'進行Decalre。 – TheLostMind

+0

您的問題是由於您從掃描儀讀取整數而創建的,而您輸入的不是數字值。我的建議是使用行,然後檢查它是一個有效的數字或別的東西報告錯誤或繼續進行,小方評論,'i> 100 || i> 0'可以被重寫爲'x> 0', – user902383

回答

1

First of all, start by decalring both Scanner and int a outside the loop.

Next, use scanner#nextLine() to read an entire line of input into a String.

Then use String#matches("\\d+") and Integer.parseInt(inputString) to parse the int as a number.

Then use if(>0 && <100) check.

裏有方法類(hasNextInt())等待int,但這不是你正在尋找。

1

你需要做這樣的事情:

Declare Scanner and other Variable 

do { 
    System.out.println("please only enter a number between 1 and 100"); 
    System.out.println("how old are you?"); 

    read variable value from Scanner 
} while(check your condition on variable); 

希望這有助於。

1

是System.out.print中和掃描儀的問題,應該是外循環。 檢查while循環,它表示> 100而不是< 100.

相關問題