2014-06-13 77 views
-2
import java.util.Scanner; 

public class test { 

/** 
* @param args 
*/ 
public static void main(String[] args) 
{ 
    Scanner input = new Scanner (System.in); 
    boolean US1 = false; 
    boolean game; 
    int score = 1; 
    int wage = 0; 
    int fin_score = 0; 
    String ans; 

    if (US1 == false) { 
     game = false; 
     System.out.println (score); 
     System.out.println("Enter a wager"); 
     wage = input.nextInt(); 
    } 

    if (wage < score) { 
     System.out.println ("What is the capital of Liberia?"); 
     ans = input.next(); 

     if (ans.equalsIgnoreCase("Monrovia")) { 
      System.out.println ("You got it right!"); 
      System.out.println ("Final score " + fin_score); 
     } 
    } 
} 
} 

我發現了一堆用InputMismatchException時的解決方案,並嘗試{}趕上{}但是當他們在我的代碼來實現他們從來沒有工作。有沒有辦法在這裏實現這些?我試圖做一個循環迭代,直到輸入的工資是一個整數確定是否輸入的號碼是一個int

+0

當然這種方法(與try/catch)的作品。因此(未示出)的實現必須是錯誤的。 – user2864740

+0

你有什麼嘗試?在這種情況下,使用在線解決方案將起作用,我保證。 – nook

回答

0

你可以在你的代碼中有多個catch異常來檢查錯誤的輸入。例如

try{ 

    wage = input.nextInt(); 

catch (InputMismatchException e){ 
    System.out.print(e.getMessage()); 
    //handle mismatch input exception 
} 

catch (NumberFormatException e) { 
    System.out.print(e.getMessage()); 
    //handle NFE 
} 

catch (Exception e) { 
    System.out.print(e.getMessage()); 
    //last ditch case 
} 

任何這些將工作的優良掃描儀的錯誤,但InputMismatchException是最好的使用。如果你在try-catch塊中包含非工作代碼,這將有助於你的案例。

+1

不回答這個問題......「我正在嘗試創建一個迭代循環,直到輸入的工資爲整數」。此外,nextInt對於stdin不利,它不會查看整行以確定它是否有效,並且會留下任何其他單詞/整數。 – Runemoro

0

首先,你應該使用Scanner.nextLine,因爲Scanner.nextInt使用空格和換行符作爲分隔符,這可能不是你想要的(任何東西在掃描儀上留下空間,打破下一次讀取)。

試試這個:

boolean valid = false; 
System.out.print("Enter a wager: "); //Looks nicer when the input is put right next to the label 
while(!valid) 
    try { 
     wage = Integer.valueOf(input.nextLine()); 
     valid = true; 
    } catch (NumberFormatException e) { 
     System.out.print("That's not a valid number! Enter a wager: "); 
    } 
} 
+0

我究竟在哪裏將它放在我的代碼中?它可以工作,但是當我輸入一個整數時,它崩潰 – user3734973

+0

@ user3734973:用我給你的東西替換System.out.println(「輸入一個賭注」);'和'wage = input.nextInt();'。另外,如果你的程序讓java ** crash **,那麼我建議你重新安裝它。如果它只是給你一個例外,然後粘貼你的異常! – Runemoro

0

是的!有一個很好的方法可以做到這一點:

Scanner input = new Scanner(System.in); 
    boolean gotAnInt = false; 
    while(!gotAnInt){ 
     System.out.println("Enter int: "); 
     if(input.hasNextInt()){ 
      int theInt = input.nextInt(); 
      gotAnInt = true; 
     }else{ 
      input.next(); 
     } 

    } 
相關問題