Reusing Java Scanner - java

Ive written a small Java code to calculate the product of two integers input by the user using Scanner. The user is forced to input integer values. The code is shown below.
import java.util.Scanner;
public class Principal {
public static void main(String[] args) {
int x=0,y=0;
Scanner sc=new Scanner(System.in);
//Asks for the first number until the user inputs an integer
System.out.println("First number:");
while(!sc.hasNextInt()){
System.out.println("Not valid. First number:");
sc.nextLine();
}
x=sc.nextInt();
//Asks for the second number until the user inputs an integer
System.out.println("Second number:");
while(!sc.hasNextInt()){
System.out.println("Not valid. Second number:");
sc.nextLine();
}
y=sc.nextInt();
//Show result
System.out.println(x+"*"+y+"="+x*y);
}
}
The loop for the first number works fine. But, the second doesn't: if the user inputs something that is not an integer value, the message "Not valid. Second number:" is shown twice!
First number:
g
Not valid. First number:
2
Second number:
f
Not valid. Second number:
Not valid. Second number:
4
2*4=8
What is the reason for this behaviour? I guess I'm doing something wrong.
I've tried to use two different Scanners (one for each number) and the problem dissapears, but I don't think that creating lots of instances is the correct path.
Can anybody help?
Thanks.

Because even after accepting the first int value there is still the newline character to consume,
so change to
x=sc.nextInt();
sc.nextLine();

Related

Using while loop to check input but it runs twice from the second time

I use the while loop to check if the input is an integer or not, the first time encounter a wrong type, it works fine, execute the statements in the loop once. But from the second time, it runs the statements in the loop twice. I already use sc.nextLine() to clear the previous input, still....
Pls ignore it is a date that i need to get in this case, I understand there are other methods to get a date, assume it is an integer the program need later.
What I want to know is what is causing the loop to run twice from the second time before taking a new input? And how to avoid this?
Thanks
I can copy the whole program if needed, but it seems a bit long...
It is the getInput() method with the problem:
import java.util.Scanner;
public class DayOfWeek {
static Scanner sc = new Scanner(System.in);
static int day, month, year;
public static void main(String[] args) {
System.out.println("");
System.out.print("Please enter the DAY in numeric form: ");
day = getInput();
System.out.print("Please enter the MONTH in numeric form: ");
month = getInput();
System.out.print("Please enter the YEAR in numeric form: ");
year = getInput();
}
public static int getInput() {
while (!sc.hasNextInt()) {
sc.nextLine();
System.out.print("Please enter integer only. Try again: ");
}
return sc.nextInt();
}
}
this is the result on the console :
Please enter the DAY in numeric form: a
Please enter integer only. Try again: 1
Please enter the MONTH in numeric form: b
Please enter integer only. Try again: Please enter integer only. Try again: 1
Please enter the YEAR in numeric form: c
Please enter integer only. Try again: Please enter integer only. Try again:
Because after it reads the integer value, it will leave the [ENTER] from System.in. And when you start the next getInput(), [ENTER] is tested by sc.hasNextInt() and return false. So it will loop twice for the second and third round of input.
Try modify your method as below. It will discard anything user input after the 1st integer for each round of input.
public static int getInput() {
while (!sc.hasNextInt())
{
sc.nextLine();
System.out.print("Please enter integer only. Try again: ");
}
int result = sc.nextInt();
sc.nextLine();
return result;
}

How do I add a blank line after the scanner object?

I am very new to Java and I am having some issues making my code do what I want it to.
So this is my code:
System.out.println("Please enter an integer: ");
int another_int_value = Integer.parseInt(input.nextLine());
This outputs the message Please enter an integer: and then a blank line where the user can type an integer let's say the user inputs the integer 3.
The following line starts right after the 3, but I want it to skip one, how do I make this happen?
I tried adding the line input.nextLine() but then the user has to press ENTER, twice and I don't want that. Any suggestions?
Alternatively you could have it to where the user inputs code after the semicolon by removing the .println and just using .print. No extra code needed after.
System.out.print("Please enter an integer: ");
int another_int_value = Integer.parseInt(input.nextLine());
This should work
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer: ");
System.out.println();
int another_int_value = Integer.parseInt(input.nextLine());
System.out.println();
}
}

Java: Trouble taking user input

and while trying to make this simple program, im having trouble getting user input in terms of the string. When entering the integer, im having no problems, but when my program asks the user to enter another a character, the cursur will blink waiting for me to type in something, but it wont let me. If i comment out all of the integer stuff, i am then allowed to enter a string. Is there a reason i cant input both? thank you
import java.util.Scanner;
public class math {
public static void main(String args[]){
int int1,int2,int3;
String operator;
Scanner ahmad=new Scanner(System.in);
System.out.print("Enter three integers: ");
int1=ahmad.nextInt();
int2=ahmad.nextInt();
int3=ahmad.nextInt();
System.out.print("Enter a (for average), s (for sum) or p (for product):");
operator=ahmad.nextLine();
System.out.println("Thank you");
}
}
nextInt() only consumes the integer, it doesn't consume the whitespace characters (EOL in this case). Use two nextLine(), one to consume the EOL character, one to prompt you for input.
System.out.print("Enter a (for average), s (for sum) or p (for product):");
operator=ahmad.nextLine();
operator=ahmad.nextLine();
System.out.println("Thank you");

How to insist that a users input is an int?

Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.
I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
And continue on with my program, and everything works fine.
Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).
How can I make the code more robust, where it would verify that only an int was entered?
These are the results I'm hoping for:
Lets say the input was:
23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc
Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.
In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
scan.next();
}
int input = scan.nextInt();
Here's a simple example with prompts and comments.
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: "); // Initial prompt for input
// Repeat until next item is an integer
while (!scan.hasNextInt())
{
scan.next(); // Read and discard offending non-int input
System.out.print("Please enter an integer: "); // Re-prompt
}
// At this point in the code, the user has entered an integer
int input = scan.nextInt(); // Get the integer
// And now you can use the input variable.
Use scan.hasNextInt() to make sure the next input is an int.
I have written an example that ensures that the program will continue only if a number and not an invalid value is entered. Do not worry, I added the desired explanation.
The program asks the user to input a number. A loop ensures that the processing will not go on until a valid number is entered. Before that I have defined a variable "inputAccepted" that has false as default value. If he enters a number, the variable "inputAccepted" is set to true and the program leaves the loop. But if he enters something else than a number, an exception is thrown right in this moment, and the line that sets the variable "inputAccepted" to true will not be executed. Instead a message will be printed out that tells the user that his input is not valid. Since "inputAccepted" could not be set to true, the loop will do the same stuff again until the string can be converted to a number.
You can test the program here.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean inputAccepted = false;
while (!inputAccepted) {
try {
System.out.print("Please enter a number: ");
Integer.valueOf(input.nextLine());
inputAccepted = true;
} catch (NumberFormatException e) {
System.out.println("Not a valid number.");
}
}
System.out.println("Thank you!");
}
}
Just get "anything" and parse it:
Scanner scan = new Scanner(System.in);
Integer number = null;
while (number == null) {
try {
number = Integer.parseInt(scan.next());
} catch (NumberParseException e) {
System.out.println("bad input: " + input);
}
}
Without any code and just in English, I'd say there's two things you have to test or look out for. First that the input is an int, second that the int is within the correct range.
In terms of pseudocode, the first thing to do is make sure it's an int. Declaring an int named "input", I would put a try / catch block, where you try to scan in the user input as an int, with parseInt(). If the try part fails, you know it's not an int and can return an error message.
Then, now that you know that "input" is an int, you can test whether it is less than 1 or more than 150, and return an error message if so!
public class Sample {
/**
* author CLRZ
*/
public static void main(String[] args) {
int a; // variable
Scanner in = new Scanner(System.in); // scans your input
System.out.println("Enter your number's choice:");
int sem1 = in.nextInt(); // reads next integer
if (sem1 == 1) // conditioned if your choice number is equal to 1
System.out.println("Hello World1"); // output wil be Hello World
int b;
System.out.println("Enter your number's choice:");
int sem2 = in.nextInt();
if (sem2 == 2)
System.out.println("Hello World2");
int c;
System.out.println("Enter your number's choice:");
int sem3 = in.nextInt();
if (sem3 == 3)
System.out.println("Hello World3");
}
}

Getting accurate int and String input

I am having trouble reading in strings from the user after reading in an int. Essentially I have to get an int from the user and then several strings. I can successfully get the user's int. However, when I begin asking for strings (author, subject, etc...), my scanner "skips" over the first string input.
For example, my output looks like this:
Enter your choice:
2
Enter author:
Enter subject:
subject
As you can see, the user is never able to enter the author, and my scanner stores null into the author string.
Here is the code that produces the above output:
String author;
String subject;
int choice;
Scanner input = new Scanner(System.in);
System.out.println("Enter choice:");
choice = input.nextInt();
System.out.println("Enter author:");
author = input.nextLine();
System.out.println("Enter subject:");
subject = input.nextLine();
Any help would be greatly appreciated. Thank you!
-Preston Donovan
The problem is that when you use readLine it reads from the last read token to the end of the current line containing that token. It does not automatically move to the next line and then read the entire line.
Either use readLine consistently and parse the strings to integers where appropriate, or add an extra call to readLine:
System.out.println("Enter choice:");
choice = input.nextInt();
input.nextLine(); // Discard the rest of the line.
System.out.println("Enter author:");
author = input.nextLine();
This works perfectly.
Although while making previous programs like the one below it was not required. Can anyone explain this?
import java.util.Scanner;
public class Average Marks {
public static void main(String[] args) {
Scanner s = new Scanner ( System.in);
System.out.print("Enter your name: ");
String name=s.next();
System.out.print("Enter marks in three subjects: ");
int marks1=s.nextInt();
int marks2=s.nextInt();
int marks3=s.nextInt();
double average = ( marks1+marks2+marks3)/3.0;
System.out.println("\nName: "+name);
System.out.println("Average: "+average);

Categories