2012-09-23 46 views
1

我需要int num只接受數字。如果我輸入字母,則會出現錯誤。有沒有辦法立即標誌字母,或者我必須採取num作爲字符串並運行循環?輸入編譯錯誤Java

import java.util.Scanner; 

public class Test 
{   
    public static void main(String[] args) 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.println("Input a number."); 
     int num = input.nextInt(); 
    } 
} 
+0

沒有聲明變量(即聲明爲'Scanner',我想象的是你想要的,並實例化)名爲'input'的變量。 – Makoto

+0

@Makoto檢查導入語句。他可能沒有在這裏複製整個代碼 – vikiiii

+0

那時候'input'將會是一個靜態變量,並且可能會被副本抓取。但你可能是對的... – Makoto

回答

0

你可能想要做這樣的事情:

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

public class Test { 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     System.out.println("Input an integer."); 
     int num = 0; // or any other default value 
     try { 
      num = input.nextInt(); 
     } catch (InputMismatchException e) { 
      System.out.println("You should've entered an integer like I told you. Fool."); 
     } finally { 
      input.close(); 
     } 
    } 
} 

如果用戶輸入的東西是不是一個整數,則catch塊中的代碼會被執行。

+0

好的,所以我嘗試了這一點,但現在我的代碼中沒有看到我的num變量。我如何解決這個問題? – Tooilia

+0

查看上面的修改。如果用戶給你提供無效輸入,你可以將'num'初始設置爲想要的默認值。 – arshajii

+0

通過編輯,它可以看到num,但它的值保持爲0. – Tooilia

1

您必須使用Scanner.hasNextInt():

它如果此掃描器輸入信息的下一個標記可以解釋爲使用nextInt()方法默認基數中的一個int值,則返回true。掃描儀不會超過任何輸入。

public static void main(String[] args) 
{ 
System.out.println("Input a number."); 
Scanner sc = new Scanner(System.in); 
System.out.print("Enter number 1: "); 
while (!sc.hasNextInt()) sc.next(); 
int num = sc.nextInt(); 

System.out.println(num); 

} 
+0

感謝小費! – Tooilia

+0

如果此功能適用於您,請將答案標記爲已接受。 – vikiiii