2013-01-10 44 views
2

所以,我一直在尋找一種有效的方法,使用Java的標準包來讀取輸入整數...例如,我碰到類「掃描儀」,但我發現了兩個主要困難:Java:如何讀取輸入int

  1. 如果我不插入int,我實際上不能解決異常;
  2. 該類適用於令牌,但我的目標是加載字符串的全長。

這就是我想實現執行的例子:

Integer: eight 
Input error - Invalid value for an int. 
Reinsert: 8 secondtoken 
Input error - Invalid value for an int. 
Reinsert: 8 
8 + 7 = 15 

這是(不正確)的代碼,我試圖執行:

import java.util.Scanner; 
import java.util.InputMismatchException; 

class ReadInt{ 
    public static void main(String[] args){ 
     Scanner in = new Scanner(System.in); 
     boolean check; 
     int i = 0; 
     System.out.print("Integer: "); 
     do{ 
      check = true; 
      try{ 
       i = in.nextInt(); 
      } catch (InputMismatchException e){ 
       System.err.println("Input error - Invalid value for an int."); 
       System.out.print("Reinsert: "); 
       check = false; 
      } 
     } while (!check); 
     System.out.print(i + " + 7 = " + (i+7)); 
    } 
} 
+0

請你詳細說明你是什麼意思,如果我不插入int,我實際上不能解決異常'? –

回答

1

使用BufferedReader。檢查NumberFormatException。否則非常相似,你有什麼。像這樣...

import java.io.*; 

public class ReadInt{ 
    public static void main(String[] args) throws Exception { 
     BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
     boolean check; 
     int i = 0; 
     System.out.print("Integer: "); 
     do{ 
      check = true; 
      try{ 
       i = Integer.parseInt(in.readLine()); 
      } catch (NumberFormatException e){ 
       System.err.println("Input error - Invalid value for an int."); 
       System.out.print("Reinsert: "); 
       check = false; 
      } 
     } while (!check); 
     System.out.print(i + " + 7 = " + (i+7)); 
    } 
} 
import java.io.*; 

public class ReadInt{ 
    public static void main(String[] args) throws Exception { 
     BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
     boolean check; 
     int i = 0; 
     System.out.print("Integer: "); 
     do{ 
      check = true; 
      try{ 
       i = Integer.parseInt(in.readLine()); 
      } catch (NumberFormatException e){ 
       System.err.println("Input error - Invalid value for an int."); 
       System.out.print("Reinsert: "); 
       check = false; 
      } 
     } while (!check); 
     System.out.print(i + " + 7 = " + (i+7)); 
    } 
} 
+0

謝謝,它解決了我所有的問題 – Marco

0

要使用令牌使用:

int i = Integer.parseInt(in.next()); 

然後你可以這樣做:

int i; 
while (true) { 
    System.out.print("Enter a number: "); 
    try { 
     i = Integer.parseInt(in.next()); 
     break; 
    } catch (NumberFormatException e) { 
     System.out.println("Not a valid number"); 
    } 
} 
//do stuff with i 

上述代碼適用於令牌。

+0

它工作正常,但我不想考慮令牌....例如,如果我設置爲輸入「你好8 testtest」我不想有我= 8,而是一個錯誤,因爲整個輸入在這種情況下是字符串 – Marco