how to capture enter key when asking for integer input [duplicate] - java

This question already has an answer here:
hasNextInt() keeps waiting for input when pressing Enter
(1 answer)
Closed 11 months ago.
How do you capture the enter key when using hasNextInt()? I have the following code and am trying to exit gracefully if the user just enters the return key. In the example below I was expecting to get back -9, but the program just hangs on the hasNextInt() line
import java.util.Scanner;
public class InputInt{
public static void main(String[] args){
InputInt x = new InputInt();
System.out.println(x.enterInt());
}
public int enterInt(){
int myInt = -9;
boolean isValid = false;
String lf = "";
Scanner kb = new Scanner(System.in);
while(!isValid){
System.out.print("please enter an integer: ");
if(kb.hasNextInt()){
myInt = kb.nextInt();
isValid = true;
}else{
lf = kb.nextLine();
if (lf.length() == 0)isValid = true;
}
}
return myInt;
}
}

When asking for user input, always use nextLine(), which clears the input buffer (including the trailing newline), then check/parse the input for correctness:
while (true) {
System.out.print("Please enter an integer: ");
String input = kb.nextLine();
if (input.matches("\\d{1,8}")) {
myInt = Integer.parseInt(input);
isValid = true;
break;
} else if (input.ieEmpty()) {
break;
} else {
System.out.print("1 to 8 digits only please, or blank to exit.");
}
The final else is optional, but a nice touch.
The limiting of input to up to 8 digits means you'll never get a error on parsing. To allow every valid integer using regex, see this answer (it's ugly, so viewer discretion is advised).
Note also the more succinct and conventional while (true) with break combination, which obviates the need for overloading the isValid variable, which now means the user entered a valid integer.
To also allow negative numbers, use instead:
if (input.matches("-?\\d{1,8}"))

Related

Repeatedly check whether integer input has leading zeroes

I need the user to enter an integer input, check whether it starts by 0 and tell the user to enter another integer if that is the case
I tried parsing the integer input to a string, that works but only once. The string cannot be edited when program loops
I think the solution should not at all involve strings because i need the program to loop and check over and over until the input is valid (ie has no leading zeroes)
Splitting each digit of the int into an array does not work also because the ways i found pass by string.
public static void main(String[] args){
Scanner key = new Scanner(System.in);
int in= 0;
boolean looper=true;
while (looper == true) {
System.out.println("Enter an integer");
in = key.nextInt();
/* check whether in has any leading zeroes, example of
wrong input: 09999, 0099*/
if (/*in has no leading zeroes*/)
looper = false;
}
key.close();
}
Maybe another answer would be to have a method that creates a brand new string every time the program loops, so maybe like a recursion that automatically creates strings, not sure if that's even a thing though.
You can make it cleaner by using a do-while loop instead of while(true). Note that an integer starting with 0 is an octal number e.g.
public class Main {
public static void main(String[] args) {
int x = 06;
System.out.println(x);
// x = 09; // Compilation error - out of range
}
}
Thus, 06 is a valid integer. For your requirement, you can input to a String variable and prompt the user to again if it starts with a zero. If the input does not start with a zero, try parsing it to an int and process it if it succeeds; otherwise, loopback e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
String input = "";
int in = 0;
boolean valid = true;
do {
System.out.print("Enter an integer: ");
input = key.nextLine();
if (input.startsWith("0")) {
System.out.println("Invalid input");
valid = false;
} else {
try {
in = Integer.parseInt(input);
System.out.println("You entered " + in);
// ... process it
valid = true;
} catch (NumberFormatException e) {
System.out.println("Invalid input");
valid = false;
}
}
} while (!valid);
}
}
A sample run:
Enter an integer: 09999
Invalid input
Enter an integer: xyz
Invalid input
Enter an integer: 123
You entered 123
As an aside, never close a Scanner(System.in) because it also closes System.in and there is no way to open it without rebooting the JVM.

How to loop wrong data type inputs? [duplicate]

This question already has an answer here:
While loop to determine if entered value is a double
(1 answer)
Closed 1 year ago.
I know there are lots of questions similar to this but I can't understand most of it, also I can't see any similar questions related to java language.
So can you guys help me how to loop this question if the input is not a double data type?
The code:
System.out.println("Enter first number");
num1 = input.nextDouble();
System.out.println("Enter second number");
num2 = input.nextDouble();
I really appreciate anyone who tries to answer, tia!!
This is a solution (without exception handling). It loops until two Doubles have been entered. So it is possible to enter this:
3
4.2
or also:
www
3
abc
4.2
Both will give the same result
3
4.2
Note that the code is locale sensitive in regard of the numbers you enter at the command prompt (meaning that the decimal sign depends on your computer settings – in Germany for example it is the comma and not the dot, so you would enter 4,2):
Scanner scanner = new Scanner(System.in);
Double part1 = null;
Double part2 = null;
while (true) {
if (scanner.hasNextDouble()) {
if (part1 == null ) {
part1 = scanner.nextDouble();
} else {
part2 = scanner.nextDouble();
break;
}
} else {
scanner.next(); // The input is not a Double, so just drop it
}
}
scanner.close();
System.out.println(part1);
System.out.println(part2);
If you add the line scanner.useLocale(Locale.ROOT) after creating the scanner:
Scanner scanner = new Scanner(System.in);
scanner.useLocale(Locale.ROOT);
the decimal sign will be the dot '.' like in 4.2 independent of the settings of your computer.
I like to create a separate method to validate input. If the value is invalid, then I have the method return -1. Then I'll have a while loop that checks if the input is -1, if so, than it'll ask the for a new input value till it's correct. There are many ways to go about it. But the gist is something like this.
public static void main(String[] Args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter first number");
double num1 = validateDouble(input);
while (num1 == -1) {
num1 = validateDouble(input);
}
System.out.println(num1);
}
private static double validateDouble(Scanner scanner) {
String input = scanner.nextLine();
try {
double i = Double.parseDouble(input);;
return i;
}catch (InputMismatchException | NumberFormatException e) {
if (input.equals("q")) {
System.exit(0);
}
System.out.println("Please try again.");
return -1;
}
}

What does .next(); do in this case?

This is the code which expects the integer input. If the input is integer the loop ends else the input is asked again. But if I do not include sc.next(); it will go into infinite loop when non integer value is given. Here is the main function:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean status = false;
while (!status) {
status = sc.hasNextInt();
if (status){
System.out.println("Number of people recorded");
} else {
System.out.println("Enter a valid integer number.");
}
sc.next();
}
}
You don't need status as a separate variable. You merely need to consume the token that isn't an int while you wait for an int. Like,
Scanner sc = new Scanner(System.in);
while (true) {
if (sc.hasNextInt()) {
System.out.println("Number of people recorded " + sc.nextInt());
break; // <-- end the loop
} else {
System.out.println("Enter a valid integer number.");
sc.next(); // <-- it's not an int, but consume whatever it is
}
}
sc.hasNextInt() tells you if the input is an integer or not. If it is, then the loop exits. If it isn't, then the loop continues. It continues infinitely because you never read what the input actually was, since sc.hasNextInt() is false. Including a sc.next() will actually get the input, pausing, and therefore not infinitely continuing the loop.

How to check nextInt from Scanner without consuming the int itself

What I am attempting to do is verify user input of an integer between 0-136, while also making sure that the input IS in fact an integer. I can't figure out a good way to do so, as using nextInt in the conditional consumes the int, and you can't compare hasNextInt to integers. Any help would be greatly appreciated!
Here is my code:
public static int retrieveYearsBack() {
Scanner input = new Scanner(System.in);
//Retrieve yearsBack
System.out.println("How many years back would you like to search? (Enter only positive whole numbers less than 136)");
while (!input.hasNextInt([0-136]) {
System.out.println("Invalid entry. Please enter a positive whole number less than 136 only.");
input.next();
}
return input.nextInt();
}
I have also tried:
int myYears = -1;
int tempValue = 0;
while (!input.hasNextInt() || (myYears < 0 || myYears > 136)) {
if (input.hasNextInt())
tempValue = input.nextInt();
if (tempValue > 0 && tempValue < 136)
myYears = tempValue;
else {
System.out.println("Invalid entry. Please enter a positive whole number less than 136 only.");
input.next();
}
}
This try gets stuck in an infinite loop.
I believe that you do need the input.next() call despite what Vivin says. If you can't read an integer from the next line of stdin then you will end up in an infinite loop. Furthermore, you should handle the case where you run out of lines of stdin to process, which can happen where your application's input is from a pipe instead of an interactive session.
In a more verbose style, this might look something like:
public static int retrieveYearsBack() throws Exception
{
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
if (input.hasNextInt()) {
int years = input.nextInt();
if (0 <= years && years <= 136) {
return years;
}
} else {
input.next();
}
System.out.println("Invalid entry. Please enter a positive whole number less than 136.");
}
throw new Exception("Standard in was closed whilst awaiting a valid input from the user.");
}

How to limit user to only put in octal number in Java or loop until they do?

So I am trying to make the user give me an octal number or loop until they do. I cannot figure it out. Please help! Thanks!
Scanner keyboard = new Scanner (System.in);
boolean valid = false;
while (!valid) //first loop unitl uers inputs correct value
{ // starts the main loop
System.out.print("\n \nInput an octal number: ");
String octatl = keyboard.next();
if((ocatal.contains("8") || ocatal.contains("9"))) // invalid input tester
{// starts second loop for user to input correct value
System.out.print("Incorrect octal input...re-enter number.");
System.out.print("\nInput an octal number: ");
String octatl = keyboard.next();
}// ends loop
valid = true; // end user input loop
}
You might simplify your logic by doing the following (pseudo-code):
boolean isValid = false;
System.out.Println("describe what the input should be like")
String line;
while (!isValid) {
line = keyboard.next();
if (line only contains 012345678) { valid = true;}
else {System.out.println("reenter");}
}
work with line
By the way you want to make sure that only the numbers 0-7 are entered .. you don't want to accept a line like octal which does not contain an 8 or 9
Try the following ... Try it and let me know.
Scanner keyboard = new Scanner (System.in);
boolean valid = false;
String octatl = "";
System.out.print("\n \nInput an octal number: ");
while ((octatl = keyboard.next())!=null) //first loop unitl uers inputs correct value
{ // starts the main loop
if((octatl.contains("8") || octatl.contains("9"))) // invalid input tester
{// starts second loop for user to input correct value
System.out.print("Incorrect octal input...re-enter number.");
System.out.print("\nInput an octal number: ");
continue;
}// ends loop
break;
}

Categories