With the Scanner
Scanner scan = new Scanner(System.in);
and the methods ( read API for detail)
next()
- would read next characters until it found space ( or the delimiter used. by default space) and return String.
nextInt()
- would read next characters until it found space ( or the delimiter used. by default space) and convert it into int and return.
Note** if you give input as 'xyz' you will get exception and your program would terminate.
if you give 5 7 for answer (Strength (1-10):)
as per your program it would read 5 as strength and 7 as health. and will ask for luck.
nextLine()
would read all characters until the end of line found ( while you enter in keyboard).
So the ideal implementation to avoid issues .
You can use nextLine and convert into int if not say as error and ask to enter correct value.
System.out.println("Strength (1-10):");
String str=scan.nextLine();
while (!isNumeric(str)){
System.out.println("Enter Valid Number Strength (1-10):");
str=scan.nextLine();
}
strength = Integer.parseInt(str);
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
For example , when you call luck=scan.nextInt();
users enters 6 and enter key . 6 will capture by nextInt()
and the enter key would capture by input=scan.nextLine();
.
So in order to get next input you have to ask scan.nextLIne()
again like
luck=scan.nextInt();
scan.nextLIne();