ddonche
ddonche

Reputation: 1065

Asking user input for an integer in java

I'm doing a basic java tutorial that is basically a mad libs program. The idea came up in the tutorial to try making sure a user is at least 13, but the example hard coded the age into the program. I wanted to try getting the age from the user, but at this point, my code gives me an error because a "string cannot be converted to an integer." Looking at my code, I don't see why it's giving me this error. Here is what I used:

int age = console.readLine("Enter your age:  ");
  if (age < 13) {
    //enter exit code
    console.printf("Sorry but you must be at least 13 to use this program.\n");
    System.exit(0);
  }

I have looked for other answers, but I didn't see any that I could discern from the specific problems they were trying to fix.

Upvotes: 0

Views: 12971

Answers (3)

user3575886
user3575886

Reputation:

You can use

Scanner input = new Scanner(System.in);
 int Age = input.nextInt();
  input.nextLine();

Upvotes: 2

ddonche
ddonche

Reputation: 1065

Okay, I'm not sure if it's cool to answer your own question. I managed to get this to work, so in case someone else encounters the same problem. Here is the code that I used:

 String ageAsString = console.readLine("Enter your age:  ");
  int age = Integer.parseInt(ageAsString);
  if (age < 13) {
    //enter exit code
    console.printf("Sorry but you must be at least 13 to use this program.\n");
    System.exit(0);
  }

Upvotes: 0

jnd
jnd

Reputation: 754

You should use

try{
    int age = Integer.parseInt(console.readLine("Enter your age:  "));
    // do stuff
} catch (NumberFormatException e) {
    // User did not enter a number
}

Java doesn't cast between the two automatically. The above method however will throw an exception when you don't enter a number which you will have to handle

Upvotes: 3

Related Questions