Using scanner to recognize both integers and strings, and stopping user input if a certain string is inputted [duplicate] - java

This question already has answers here:
How to type a string to end a integer Scanning process in Java
(3 answers)
Closed 2 years ago.
Trying to use scanner to recognize both integers and strings, and stopping user input if a certain string is inputted.
Scanner myObj = new Scanner(System.in);
System.out.println("Enter number of students");
int numberof = myObj.nextInt();
Need to make it so if the user types "end", the scanner no longer takes user input. I can't put the line int numberof = myObj.nextInt(); in a loop or something and limit the variable scope, as i'm using that value of numberof throughout the rest of my code.

You can use Scanner#next and then parse integers if needed. I wouldn't recommend just directly using Scanner#nextInt.
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter number of students");
String next = sc.next();
if (next.equals("end")) break;
else {
try {
int num = Integer.parseInt(next);
} catch (NumberFormatException e) {
System.out.println("Please enter a valid input");
}
}
} while (true);

Related

How to validate input type(java) [duplicate]

This question already has answers here:
How to verify that input is a positive integer in Java [closed]
(3 answers)
Closed 15 hours ago.
I have the following snippet of code and I don't know how to make sure that the user is entering a positive int. What can I do so that the code makes sure the input type is valid.
public static void main(String[] args)
{
//creates a scanner
Scanner output = new Scanner(System.in);
//declare all the variables
int fours;
//ask the user how many fours they have
System.out.println("How many 4's do you have");
fours = output.nextInt();
}
I tried using a do while loop like shown below, but it only makes sure that the input is greater than or equal to zero, but does not make sure it is an int.
do
{
System.out.println("How many 4's do you have");
fours = output.nextInt();
}
while(fours <= 0 );
You can check Scanner#hasNextInt:
Scanner sc = new Scanner(System.in);
System.out.println("How many 4's do you have");
while (!sc.hasNextInt()) {
sc.next(); // skip the invalid input
System.out.println("Please enter an integer");
}
int fours = sc.nextInt();

Ensuring user input is a single integer while using Scanner [duplicate]

This question already has answers here:
How do I ensure that Scanner hasNextInt() asks for new input?
(2 answers)
Closed 6 years ago.
Desired outcome:
Accepts user input
Makes sure user inputs only 1 integer value at a time
Stores that integer in a variable
I tried to achieve this by doing the following:
Store user input in variable
Count number of tokens in variable
If there's not one token, reject the input
If the input is not of data type int, reject the input
Code:
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer:");
String myString = scan.nextLine();
int tokens = new StringTokenizer(myString, " ").countTokens();
while (tokens != 1 && !scan.hasNextInt()) {
System.out.println("Enter a single integer");
myString = scanner.nextLine();
tokens = new StringTokenizer(myString, " ").countTokens();
}
int number = scanner.nextInt();
System.out.println(number);
This code is full of holes. The output is inconsistent and undesired. It typically ends by throwing a java.util.InputMismatchException error, indicating the value it's trying to store isn't an int. I've experienced this error occur after one loop and after multiple loops, even with the same type and quantity of input (e.g. 2 strings).
Should I keep going with this code, or should I try to approach this problem from a different angle?
I've modified your program a little bit. My approach was to accept a single line of input. If the input contains more than one token, ask the user to re-enter input. If there is only one input, check if the input is an integer, if not, as the user to again provide input.
Seems to work for me:
Scanner scanner = new Scanner(System.in);
String myString;
int tokens;
int number;
do {
System.out.println("Enter a single integer");
myString = scanner.nextLine();
tokens = new StringTokenizer(myString, " ").countTokens();
try {
number = Integer.parseInt(myString);
} catch(NumberFormatException e) {
tokens = 0;
number = -1;
}
}while (tokens != 1);
scanner.close();
System.out.println(number);
Update: Alternate approach without using StringTokenizer
Scanner scanner = new Scanner(System.in);
String myString;
boolean validInput;
int number;
do {
System.out.println("Enter a single integer");
myString = scanner.nextLine();
try {
number = Integer.parseInt(myString);
validInput = true;
} catch(NumberFormatException e) {
validInput = false;
number = -1;
}
}while (validInput == false);
scanner.close();
System.out.println(number);
Update 2: Another approach using regular expressions to validate input before accepting it.
The Scanner allows us to use a regular expression to match the input. If the input matches the pattern, you can use it to accept the input. Otherwise, discard it and ask user to provide input again.
Here's the code:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a single integer");
String integerPattern = "[+-]?\\d+$"; // positive or negative and digits only
while(scanner.hasNext(integerPattern) == false) {
String x = scanner.nextLine();// capture and discard input.
System.out.println("Enter a single integer. '" + x + "' is an invalid input.");
}
int number = scanner.nextInt(); // capture input only if it matches pattern.
scanner.close();
System.out.println("number: " + number);
Hope this helps!

The code runs again no matter what. [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I don't know why, but the below code makes the user run the code again, whether they choose to or not. I've tried many things, but it doesn't work correctly.
Thanks!
public static void main (String [ ] args)
{
boolean a = true;
while (a)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: ");
int x = scan.nextInt();
System.out.print("\n\nEnter a second integer: ");
int z = scan.nextInt();
System.out.println();
System.out.println();
binaryConvert1(x, z);
System.out.println("\n\nWould you like to run this code again? Enter \"Y\" or \"N\".");
System.out.print("Enter your response here: ");
String RUN = scan.nextLine();
String run = RUN.toLowerCase();
if (run.equals("n"))
{
a = false;
}
System.out.println();
System.out.println();
}
System.out.println("Goodbye.");
}
Scanner.nextInt() doesn't consume the line ending characters from the buffer, which is why when you read the value of the "yes/no" question with scan.nextLine(), you'll receive an empty string instead of the value the user entered.
A simple way to fix this is to explicitly parse the integer from raw lines using Integer.parseInt():
System.out.print("Enter an integer: ");
int x = Integer.parseInt(scan.nextLine());
System.out.print("\n\nEnter a second integer: ");
int z = Integer.parseInt(scan.nextLine());

How to read integers entered on a single line using .nextInt .hasNextInt or .hasNext without cause blockage?

I'm trying to read integers entered one after another on a single line separated by a space.
There will be some way for this code to work without using .nextLine, without converting the input to a string and then do the conversion to integer?
The challenge is "not use .nextLine", do not use string or conversions. Reading pure integers and exit from while loop.
public static void scannerInts (){
int[] list = new int[100];
int n=0;
System.out.print("Input data into one line, [ENTER] to finish: ");
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
if (input.hasNextInt()) {
list[n++]= input.nextInt();
} else {
input.next();
}
}
for (int i=0;i<n;i++)
System.out.print(list[i] + " ");
}
PD: I've tried many of the responses from Stack OverFlow and nothing seems to work.
The problem is that System.in is an infinite stream. Calling hasNextXXX will cause System.in to prompt if the Scanner doesn't find a token in what has already been read. The user needs to enter some non-integer to terminate the list.
You may, however, use a second Scanner since Scanner can scan a String e.g.:
Scanner in = new Scanner(System.in);
System.out.print("Enter a list of integers: ");
List<Integer> list = new ArrayList<>();
Scanner line = new Scanner(in.nextLine());
// optional
line.useDelimiter("\\D+");
while(line.hasNextInt()) {
list.add(line.nextInt());
}
System.out.println("You entered " + list);
Using a single Scanner you could also use findInLine:
for(String token; (token = in.findInLine("-?[1-9]\\d*")) != null;) {
list.add(Integer.valueOf(token));
}

Using while loop as input validation [duplicate]

This question already has answers here:
Determine if a String is an Integer in Java [duplicate]
(9 answers)
user input check int only
(4 answers)
Closed 9 years ago.
I'm trying to use while loop to ask the user to reenter if the input is not an integer
for eg. input being any float or string
int input;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the number of miles: ");
input = scan.nextInt();
while (input == int) // This is where the problem is
{
System.out.print("Invalid input. Please reenter: ");
input = scan.nextInt();
}
I can't think of a way to do this. I've just been introduced to java
The issue here is that scan.nextInt() will actually throw an InputMismatchException if the input cannot be parsed as an int.
Consider this as an alternative:
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of miles: ");
int input;
while (true) {
try {
input = scan.nextInt();
break;
}
catch (InputMismatchException e) {
System.out.print("Invalid input. Please reenter: ");
scan.nextLine();
}
}
System.out.println("you entered: " + input);
The javadocs say that the method throws a InputMismatchException if the input doesn;t match the Integer regex. Perhaps this is what you need?
So...
int input = -1;
while(input < 0) {
try {
input = scan.nextInt();
} catch(InputMismatchException e) {
System.out.print("Invalid input. Please reenter: ");
}
}
as an example.

Categories

Resources