我創建了一個程序來檢查整型變量「paycategory」的輸入範圍,但是當我想檢查inputmismatch錯誤時也是如此。我試過但它不工作......我不想將數據類型更改爲字符串,因爲paycategory應該是整數。請幫助如何解決這個問題?InputMismatch異常不起作用
import java.util.Scanner;
import java.util.*;
import java.text.*;
import java.lang.Object.*;
public class TestEmployeePayRoll {
public static void main(String Args[])
{
String EmployeeID = null, FirstName = null, LastName = null, result;
double HoursWorked;
int PayCategory = 0, counter = 0;
do
{
Scanner input = new Scanner(System.in);
try
{
int flag = 1;
String input1 ;
System.out.println("Enter your Employee ID number: ");
while(flag==1){
EmployeeID = input.nextLine();
if(EmployeeID.trim().length()>=5){
flag = 0;
System.out.println("Enter the First Name: ");
FirstName = input.nextLine();
System.out.println("Enter Last Name: "+ " ");
LastName = input.nextLine();
}else
System.out.print("EmployeeID must be exactly 5 digits long: \n Enter the Employee ID again: ");
}
}
catch(Exception e)
{
System.out.println("Exception ");
}
try{
do{
System.out.println("Enter the Pay Category: "+ " ");
PayCategory = input.nextInt();
if(!(PayCategory >0 || PayCategory <5))throw new InputMismatchException();
{
System.out.println("Pay Category must be between 1 and 4");
}
}
while(PayCategory < 1 || PayCategory > 4);
}
catch(InputMismatchException e)
{
System.out.println("PayCategory must be integers");
}
do
{
System.out.println("Enter the number of hours worked: ");
HoursWorked = input.nextDouble();
Double hours = new Double(HoursWorked);
if(hours.isNaN())
{
System.out.println("---Enter a valid hours value---");
}
else if(!(HoursWorked >1 || HoursWorked <80))
{
System.out.println("---Enter value between 1 and 80---");
}
}
while(HoursWorked < 1 || HoursWorked > 80);
EmployeePayRoll obj1 = new EmployeePayRoll(FirstName, LastName, EmployeeID, HoursWorked, PayCategory);
DecimalFormat fmt = new DecimalFormat("###,##0.00");
System.out.println("\n-----------------------------------------------------");
System.out.println("\n The pay details for:" + obj1.getName() + "\t\t\t" + "ID:" + EmployeeID);
System.out.println("\n-----------------------------------------------------");
System.out.println("Pay Category: \t\t\t" + obj1.getPayCategory());
System.out.println("Hours Worked: \t\t\t" + obj1.getHoursWorked());
System.out.println("Pay Rate: \t\t\t" + obj1.getPayRate());
System.out.println("Gross Pay: \t\t\t" + "$"+fmt.format(obj1.getGrossPay()));
System.out.println("Tax Payable: \t\t\t" + "$"+fmt.format(obj1.getTaxPayable()));
System.out.println("\t\t\t\t---------");
System.out.println("Net Pay: \t\t\t" + "$" + fmt.format(obj1.getNetPay()));
System.out.println("\n------------------------------------------------------");
System.out.println();
System.out.println("\n Process another employee? (Y/N)");
result = input.next();
}
while (result.equals("Y")||result.equals("y"));
}
}
感謝
什麼叫「它不工作」是什麼意思?它在做什麼?它應該做什麼? – Mat
它沒有做任何事情....這就是爲什麼我沒有把任何細節... – user804437