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.

ddonche
  • 1,065
  • 2
  • 11
  • 24

3 Answers3

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

jnd
  • 754
  • 9
  • 20
  • 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` – ddonche Jan 30 '15 at 04:57
  • 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: http://stackoverflow.com/questions/5585779/converting-string-to-int-in-java – jnd Jan 30 '15 at 05:03
2

You can use

Scanner input = new Scanner(System.in);
 int Age = input.nextInt();
  input.nextLine();
Abdi
  • 1,298
  • 1
  • 9
  • 10
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);
  }
ddonche
  • 1,065
  • 2
  • 11
  • 24