Skip to content
Advertisement

How do I get the Scanner in java to read a string? [closed]

How would I get my program to quit when the user enters q? Is there something wrong with the scanner?


My code

JavaScript

Advertisement

Answer

I can see mainly two problems in your code:

  1. It lacks a loop to repeat asking for age again. There can be many ways (for, while, do-while) to write a loop but I find do-while most appropriate for such a case as it always executes the statements within the do block at least once.
  2. age is of type, int and therefore it can not be compared with a string e.g. your code, age.equals("q") is not correct. A good way to handle such a situation is to get the input into a variable of type, String and check the value if it should allow/disallow processing it (e.g. trying to parse it into an int).

Note that when you try to parse a string which can not be parsed into an int (e.g. "a"), you get a NumberFormatException which you need to handle (e.g. show an error message, change some state etc.).

JavaScript

A sample run:

JavaScript
Advertisement