2016-04-19 44 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.nextDouble(Unknown Source) 
    at Main.main(Main.java:14) 

這是代碼:

import java.util.Scanner; 

public class Main { 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     double salary = 0;  // Salary excluded tax 
     int tax = 0;   // % of tax 
     double taxTot = 0;  // amount of tax 
     double totSalary = 0; // Salary with tax 

     System.out.println("Salary, please : "); //Input salary 
     salary = input.nextDouble();  

     if (salary <= 15000) {       // <=15000 
      tax = 10; 
     } else if (salary>= 40000 && salary < 60000){  // >=40000 
      tax = 20; 
     } else {           // over > 60000 
      tax = 30; 
     } 

     taxTot = salary/100*tax; 
     totSalary = salary - taxTot; 
     System.out.println("Your tax is : " + taxTot + " Your salary : " + totSalary); 
    } 
} 
+1

之間我編譯和運行程序的不同,你可能會得到錯誤。當我輸入一個數字時我沒有錯誤。然而,當輸入一封信時,我得到了和你一樣的錯誤,這並不奇怪。你的意見是什麼? – Gendarme

+0

我似乎無法複製您的問題。複製和粘貼,併爲我工作得很好。 –

+0

當您運行此應用程序時,您提供了什麼樣的輸入? – LearningPhase

回答

1

java.util.InputMismatchException可如果下拋出輸入Scanner與您嘗試獲取的類型不匹配。這裏有一個例子:

Scanner input = new Scanner("hello"); 
double salary = input.nextDouble(); 

所以,問題最有可能從salary = input.nextDouble();線始於在你的代碼, 和原因是你沒有輸入有效的double

爲了測試你的程序的行爲,你可以像上面我之前寫的那樣在Scanner構造函數中寫入輸入。 例如,您可以通過編寫此測試:

Scanner input = new Scanner("9000"); 

這樣salary將是9000,所以自salary <= 15000tax將被設置爲10.更改值別的東西來獲得不同的結果,對於例如:

Scanner input = new Scanner("41000"); 

當你熟悉了Scanner工作,你可以改變固定字符串參數回new Scanner(System.in)和運行完整的程序。

+0

我按照你所說的嘗試過,但當我嘗試輸入一個十進制數字時,我得到錯誤,我的意思是如果我輸入13.548我得到錯誤,程序停止運行。但是,當我輸入整數,程序完美地工作。 – woft

0

如果您通過本有一個讀它告訴你關於InputMismatchException

基本上,在程序中輸入不匹配的掃描儀類型。所以,因爲你的投入不是雙

1

嘗試例如

Scanner scanner = new Scanner(System.in).useLocale(Locale.US); 

有5,0和5.0

+0

非常感謝。我現在明白問題在哪裏。 – woft