gpt4 book ai didi

Java扫描仪异常问题

转载 作者:行者123 更新时间:2023-12-01 14:01:25 26 4
gpt4 key购买 nike

我正在做我的中期项目,我已经或多或少完成了。我遇到的唯一问题是,当我运行该程序并要求我输入完整员工姓名时,编译器会向我抛出有关扫描仪的异常。我从 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

由于这听起来像是一个学校项目,因此我不会具体说明如何解决它。

关于Java扫描仪异常问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19329006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com