0

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.

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

That one gave me the following error: code error: cannot find symbol int age = Integer.valueof(console.readLine("Enter your age: ")); ^ symbol: method valueof(String) location: class Integer 1 error code
Not sure what error you are getting. But console.readline() returns a String which you will need to changed to an int. Perhaps this question will help you further: stackoverflow.com/questions/5585779/…
2

You can use

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

1 Comment

do not forget to consume the <enter>
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.