2013-10-12 93 views
0

我正在處理我的中期項目,並且我已經完成了大部分工作。我遇到的唯一問題是,當我運行該程序並要求輸入完整的員工姓名時,編譯器會向我發出有關掃描器的例外情況。我從Scanner輸入到「scanner user_input」,但它仍然無法正確編譯。任何暗示什麼問題是值得讚賞的。Java掃描程序異常問題

package midterm; 

import java.util.Scanner; 

public class Midterm { 

    public static void main(String[] args) { 
     Scanner user_input = new Scanner(System.in); 

     System.out.print("If you wish to enter another's employee's inforamtion" 
         + " please press 1, else to exit enter 0."); 
     int choice = user_input.nextInt(); 

     if (choice == 1) { 
      System.out.print("What is the employee's full name. "); 
      String empName = user_input.next(); 
      System.out.printf("Please enter the number of hours that the employee has worked. "); 
      double hoursWorked = user_input.nextDouble(); 
      System.out.printf("Please enter the employee's hourly pay rate. "); 
      double payRate = user_input.nextDouble(); 

      displayPay(empName, calculatePay(hoursWorked, payRate)); 
     } 
     else if (choice == 0) { 
      System.exit(0); 
     } 
    } 

    public static double calculatePay(double hours, double pay) { 
     double wages = 0; 

     if (hours <= 40) { 
      wages = hours * pay; 
     } 

     if (hours > 40) { 
      double regPay = hours * pay; 
      double overTime = (hours - 40) * pay * 1.5; 
      wages = regPay + overTime; 
     } 

     return wages; 
    } 

    public static void displayPay(String name, double empWage) { 
     System.out.print("-----------------------------------------"); 
     System.out.print("Employee Name: " + name); 
     System.out.print("Pay Check Amount: $" + empWage); 
     System.out.print("-----------------------------------------"); 
    } 
} 
+0

顯示什麼錯誤?它是編譯器錯誤還是運行時異常? – hexafraction

回答

0

漂亮的直線前進! 這是如何使用掃描儀類接受來自鍵盤的輸入:

String str; 
    Scanner in = new Scanner(System.in); 

    System.out.println("Enter any string :-"); 
    str = in.nextLine(); 
    System.out.println(str); // will print the string that you entered. 
+0

謝謝你完美解決。 –

1

的錯誤是在這裏:

System.out.print ("What is the employee's full name. "); 
String empName = user_input.next(); 

next()讀取一切直到下一個分隔符,默認情況下是空白。因此,如果有人輸入名字和姓氏(用空格分隔),則只會讀取第一個名字。因此,稍後您調用user_input.nextDouble()時,仍然會有部分名稱被讀取,並且該程序因爲下一個標記(在本例中爲姓氏)而無法解析爲double

由於這聽起來像一個學校項目,我不會說如何解決它。

0

嘗試使用:

System.out.print ("What is the employee's full name. "); 
String empName = user_input.nextLine(); 
0

不要使用user_input.next();

的而不是,試試這個:user_input.nextLine();