2017-10-20 91 views
1

我需要用一個while循環來詢問用戶一個介於1-100之間的數字,並告訴用戶輸入了錯誤的號碼數字是負數或超過100.這是我迄今爲止所擁有的。每當我運行它時,它都會詢問用戶的輸入。當輸入爲負數或大於100時,表示無效號碼,但當用戶輸入爲45時,表示無效號碼,當0-100之間的數字有效時。我不認爲它讀取代碼的最後部分。怎麼辦請問用戶輸入正確的號碼

import java.util.*; 

public class PlayOffs { 
    public static Scanner scan = new Scanner(System.in); 

    public static void main(String[] args) { 

     System.out.print("What is the % chance Team 1 will win (1-99)?: "); 
     int team1input = scan.nextInt(); 
     do { 
      while (team1input >= -1 || team1input >= 101) { 
       System.out.println("That's not between 1-99"); 
       scan.next(); // this is important! 
      } 
      team1input = scan.nextInt(); 
     } while (team1input >= 0 && team1input <= 100); 
     System.out.println("Thank you! Got " + team1input); 
    } 
} 
+2

我真的不明白爲什麼你需要2個循環 –

+1

此外,你的一些比較是不正確的 – theGleep

+0

@FrankUnderwood內環可能處理案件提供像'富酒吧123'數據時。它會處理'foo'和'bar',然後接受'123'作爲有效的號碼。代碼最有可能基於:[使用java.util.Scanner驗證輸入](https://stackoverflow.com/q/3059333) – Pshemo

回答

0

你的問題是在你的while循環的這個條件:

while (team1input >= -1 || team1input >= 101) 

45> = -1? => true,這就是爲什麼它打印無效。

其實你不需要2個循環。在do-while循環就足以讓你期望的結果:

import java.util.*; 

public class PlayOffs { 
    public static Scanner scan = new Scanner(System.in); 

    public static void main(String[] args) { 

     System.out.print("What is the % chance Team 1 will win (0-100)?: "); 
     boolean validNumber; 
     int team1input; 
     do { 
      team1input = scan.nextInt(); 
      validNumber = team1input >= 0 && team1input <= 100; 

      if (!validNumber) { 
       System.out.println("That's not between 0-100"); 
      } 

     } while (!validNumber); 
     System.out.println("Thank you! Got " + team1input); 
    } 
} 

運行輸出:

什麼%的機率1隊會贏得(0-100)?: -1
這是不是 0-100 那不是0-100 那就是 不在0-100之間謝謝!得到45

+0

爲什麼它是(!v​​alidNumber)而不是while(validNumber)? –

+0

你想保持循環,而數字是**不**有效。這是'while(!validNumber)'的作用。當你得到一個有效的號碼,那麼你可以退出循環。 –

+0

@LuisValdez請閱讀:[當某人回答我的問題時該怎麼辦?](https://stackoverflow.com/help/someone-answers) –

1

您的比較存在問題。
你不需要兩個循環。
此代碼可能適合。

import java.util.Random; 
import java.util.*; 

    public class PlayOffs { 
     public static Scanner scan = new Scanner(System.in); 

     public static void main(String[] args) { 

      System.out.print("What is the % chance Team 1 will win (1-99)?: "); 
      int team1input = scan.nextInt(); 
      do { 
       if(!(team1input >= 0 && team1input <= 100)) { 
        System.out.println("That's not between 1-99"); 
        scan.next(); // this is important! 
        team1input = scan.nextInt(); 
       } 

      } while (!(team1input > -1 && team1input <101)); 
      System.out.println("Thank you! Got " + team1input); 
     } 
    } 
+0

當您輸入45時,將打印出不是有效的數字。檢查條件在你的if語句中。 –

+0

U R右 我很想編輯它。 –