繁体   English   中英

Java扫描仪异常问题

[英]Java scanner exception issue

我正在做中期项目,现在或多或少已经完成了。 我唯一的问题是,当我运行该程序并要求我输入员工的全名时,编译器向我抛出了有关扫描仪的异常。 我从Scanner输入转到了“ scanner user_input”,但仍无法正确编译。 任何暗示问题的提示将不胜感激。

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("-----------------------------------------");
    }
}

错误在这里:

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

next()读取所有内容,直到下一个分隔符为止,默认情况下为空白。 因此,如果有人输入名字和姓氏(用空格分隔),则该名称只会读取名字。 因此,当您稍后调用user_input.nextDouble() ,仍有部分名称要读取,并且程序崩溃了,因为下一个标记(在本例中为姓氏)无法解析为double

由于这听起来像是一个学校项目,所以我不会确切说明如何解决它。

尝试使用:

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

不要使用user_input.next();

而是尝试以下方法: user_input.nextLine();

挺直截了当的! 这是使用扫描仪类接受键盘输入的方法:

    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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM