Home > Mobile >  How can I find out which (wrong) data type the user inputted instead of an int?
How can I find out which (wrong) data type the user inputted instead of an int?

Time:12-31

So I'm completely new to Java and programming in general and I'm doing my first little program where I ask the user's age and determine whether they're an adult. I wanted to add an error message which tells the user they inputted the wrong data type and not an integer. However, when I write a string as input, it displays the error message, but it only says Integer and not String.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        //create scanner object
        Scanner sc = new Scanner(System.in);

        System.out.println("What is your age?"); //ask for input
        int age = 0;
        try { //record input and check value
            age = sc.nextInt();
            if (age >= 18) {
                System.out.println("You are an adult.");
            } else {
                System.out.println("You are not an adult.");
            }
        } catch (Exception e) { //find out which wrong type the user inputted and tell it to them
            System.out.println("Error: you did not input a full number, instead you wrote a " ((Object) age).getClass().getSimpleName());
        }

    }
}

As I said, I expect it to say that I wrote a string and not an integer, but for some reason it still says it's an Integer. How can I fix that?

So here is the input window:

What is your age? test Error: you did not input a full number, instead you wrote a Integer

Process finished with exit code 0

CodePudding user response:

You can get values from scanner as Strings by it self and then convert it to the int type:

Scanner sc = new Scanner(System.in);

    System.out.println("What is your age?"); //ask for input
    Object age = 0;
    try { //record input and check value
        age = sc.next();
        int intAge = Integer.parseInt((String) age);
        if (intAge >= 18) {
            System.out.println("You are an adult.");
        } else {
            System.out.println("You are not an adult.");
        }
    } catch (NumberFormatException e) { //find out which wrong type the user inputted and tell it to them
        System.out.println("Error: you did not input a full number, instead you wrote a "  age.getClass().getSimpleName());
    }

I recommend you to use correct exception types when you are handling exceptions, thanks

CodePudding user response:

This is expected behavior because you have declared age is int. It wont consider the datatype you gave as input but in which the variable is declared.

  • Related