int Java中String的异常

时间:2013-08-02 23:31:29

标签: java string int

好的,所以我一直在研究这个项目,我必须首先使用异常它会问类似的东西 你叫什么名字 “Joe Bloggs” 所以我有这个工作,如果数字包含一个数字,它将启动一个错误,并要求你重新输入名称。

对于我遇到困难的相反方式

    System.out.println("How many shifts did  " + employee1 +  " achieve? ");
    int Attendance1 = input.nextInt();



    while (Attendance1 >85 )
    {   
    System.out.println("Invalid only 85 Days in Attendance");System.out.println("How many shifts did  " + employee1 +  " achieve? ");
    Attendance1 = input.nextInt();
    }


    double PercentAttendance1 = ((double) Attendance1)/85 * 100 ;

    input.nextLine();

所以香港专业教育学院尝试使用InputMismatchException尝试捕获,但它引发了一个错误我不知道如果我使用case语句做了这个错误或者我需要导入一些东西吗?

第二次尝试

    System.out.println("How many shifts did  " + employee1 +  " achieve? ");
    try {
    int Attendance1 = input.nextInt();



    while (Attendance1 >85 )
    {   
    System.out.println("Invalid only 85 Days in Attendance");

   System.out.println("How many shifts did  " + employee1 +  " achieve? ");
    input.nextLine();
    Attendance1 = input.nextInt();
    }
    } catch (InputMismatchException e) {
        System.out.println("Wrong Data please enter");
        Attendance1 = input.nextInt();
}

这仍在启动

Joe Bloggs实现了多少次出席? SDA       线程“main”java.util.InputMismatchException中的异常     at java.util.Scanner.throwFor(Scanner.java:909)     在java.util.Scanner.next(Scanner.java:1530)     在java.util.Scanner.nextInt(Scanner.java:2160)     在java.util.Scanner.nextInt(Scanner.java:2119)     在programmingone.ProgrammingOne.main(ProgrammingOne.java:50)

2 个答案:

答案 0 :(得分:0)

在这一行

int Attendance1 = input.nextInt();

input.nextInt();不会使用以下换行符。在while循环中,您可以调用

Attendance1 = input.nextInt();

并获得InputMismatchException因为扫描程序会消耗换行符,并且无法将其转换为数字。因此,在致电Attendance1 = input.nextInt();之前,您需要致电input.nextLine();

您的代码将是

while (Attendance1 > 85) {   
    System.out.println("Invalid only 85 Days in Attendance");
    System.out.println("How many shifts did  " + employee1 +  " achieve? ");
    input.nextLine(); // insert this line!
    Attendance1 = input.nextInt();
}

此外,您应该遵守Java命名约定并让变量名以小写字母开头,以提高代码的可读性。

答案 1 :(得分:0)

这种情况正在发生,因为您的扫描仪需要int,并且可能会收到String。你能做的是:

String sentence = scanner.nextLine();

然后使用Integer.parseInt(sentence);

解析整数

OR:

    int Attendance1;
    try {
        Attendance1 = input.nextInt();
    } catch (InputMismatchException e) {
        //do something
    }

修改

这是一种保持程序无效输入的方法:

boolean validInput = false;
int Attendance1 = 0;

while (!validInput) {
    System.out.println("How many shifts did  " + employee1 +  " achieve? ");

    if (input.hasNextInt()) {
        Attendance1 = input.nextInt();
        validInput = true;
    }
    else {
        System.out.println("Invalid input. How many shifts did  " + employee1 +  " achieve? ");
        if (input.hasNext()) {
            input.next();
        }
    }
}
    //The rest of your code