Nighthawk Nighthawk - 1 month ago 12
Java Question

how to make an error message when input is a string instead of an int

beginner here. As mentioned before my question is: how do you output an error when the input is a string instead of an int? I'm trying to created a program that outputs a workers raise in salary, and I wanted to implement a function that displays an error when the user entered something other than a number for their salary. here's my code:

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

Answer
String salary = in.nextLine();
int salaryValue;
try {
    salaryValue = Integer.parseInt(salary);
} catch (NumberFormatException e) {
    System.out.println("You didn't enter a valid integer.");
}

This will store the user's input in a String instead of an int, then manage the conversion separately. If the conversion fails, an exception is thrown, which causes the message to be printed.