Cwarren
Cwarren

Reputation: 15

Error handling in JAVA - Check correct input type

Not sure where i'm going wrong, please help. Trying to check if the user has only entered an integer. Error showing strInpit cannot be resolved to a variable.

import java.util.Scanner;

public class Salary{ 
  public static void main(String[] args){
    int num = 0;
    String strIntput;
    boolean valid = false;
    

    // setup scanner
    Scanner in = new Scanner(System.in);
    // loop to check for valid input
    while(valid == false){
      //prompt user to enter
      System.out.println("Enter your salary per year");
      // grab input from keyboard
      strInput = in.nextLine();
      // try to convert String to int
      try{
        num = Integer.parseInt(strInput);
        valid = true;
      }
      catch(NumberFormatException e){
        System.out.println("Error - enter an integer value.");
      }
    }
    System.out.println("your salary is " + num);
  }
}

Upvotes: 1

Views: 49

Answers (2)

Дима Шуть
Дима Шуть

Reputation: 31

There is another method which you can use: #Scaner.nextInt(); It will get Integer value from console or, in another case, will throw an exception

Upvotes: 0

Daksh Rawal
Daksh Rawal

Reputation: 451

you have named the variable as String strIntput;

while declaring it..but you are using strInput everywhere else

so change String strIntput; TO String strInput;

Upvotes: 1

Related Questions