初学者在这里。如前所述,我的问题是:当输入是字符串而不是int时,如何输出错误?我试图创建一个输出工人加薪的程序,我想实现一个函数,当用户输入工资以外的其他数字时会显示错误。这是我的代码:
package calculating.salary;
import java.util.Scanner;
public class CalculatingSalary {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please input yearly salary:");
int salary = in.nextInt();
//this is where I would implement the error message
System.out.println("Please input how many years worked:");
boolean running = true;
while (running){
String years = in.nextLine();
if (years.equals ("1")|| years.equals("one")){
System.out.println("Your salary is now $"+(salary + salary*0.02));
break;
}
if (years.equals("2")||years.equals("two")){
System.out.println("Your salary is now $"+(salary + salary*0.03));
break;
}
if (years.equals("3")||years.equals("three")){
System.out.println("Your salary is now $"+(salary + salary*0.04));
break;
}
if (years.equals("4")||years.equals("four")){
System.out.println("Your salary is now $"+(salary + salary*0.05));
break;
}
if (years.equals("5")||years.equals("five")){
System.out.println("Your salary is now $"+(salary + salary*0.06));
break;
}
else {
System.out.println("Please type in a number from 1 through 5");
}
}
}
}
答案 0 :(得分:1)
String salary = in.nextLine();
int salaryValue;
try {
salaryValue = Integer.parseInt(salary);
} catch (NumberFormatException e) {
System.out.println("You didn't enter a valid integer.");
}
这会将用户的输入存储在String
而不是int
中,然后单独管理转换。如果转换失败,则抛出异常,从而导致打印消息。