Getting accurate int and String input - java

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);

Related

java couldn't take 2 continuous String input from user

This code in java
boknam [variable] refers to bookname & bokauthor[variable] referes to bookAuthor just not to get confused [ this is not that point here]
Code
String boknam;
String bokauthor;
System.out.print("Enter bookNAme: ");
boknam = scan.nextLine();
System.out.println("");
System.out.print("Enter bookAuthor: ");
bokauthor = scan.nextLine();
Here I want user to give input bookname & bookauthor but the output is
I
IT skips to take the input as bookNAme, it is only taking input as bookAuthor,
please help will be aprreciated
System.out.print("Enter bookNAme: ");
boknam = scan.nextLine();
System.out.println("");
System.out.print("Enter bookAuthor: ");
bokauthor = scan.nextLine();
boknam = scan.nextLine();
This line here is not working, not asking for input
NOTE:- THE VARIABLE IS ALREADY ASSIGNED TO DON'T SAY YOU DIDNT INITIALIZED A STRING boknam
Sometimes, we have to clear the buffer after getting integer input. Here, after getting your Choice input, we have to clear the buffer so just add an extra line scan.nextLine() before boknam = scan.nextLine(); and that should work just fine.

Reusing Java Scanner

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();

Strange output when I read from scanner

I'm trying to create a videoStore with the basic CRUD operation. For creating each movie I need to read the title, the year and the gender as below:
System.out.print("name: ");
name = in.nextLine();
System.out.print("year: ");
year = in.nextInt();
in.nextLine();
System.out.print("gender: ");
gender = in.next();
When I enter the addMovie option, I get this print on the console
(name: year:)
Can someone explain to me why it happens as above?
Here is the rest of the method:
static ArrayList<Movie> movies = new ArrayList<Movie>();
static Scanner in = new Scanner(System.in);
public static void InserirFilme() {
String name;
int year;
String gender;
boolean existe = false;
System.out.print("name: ");
name = in.nextLine();
System.out.print("year: ");
year = in.nextInt();
in.nextLine();
System.out.print("gender: ");
gender = in.next();
Movie movie = new Movie(name, year, gender);
for(Movie m: movies)
{
if(movie == m)
{
existe = true;
}
}
if(!existe)
{
movies.add(movie);
}
else
{
System.out.println("the movie already exists in the videoStore");
}
}
Calling next does not remove the line break, which means the next time you call InserirFilme the call to read the name can complete immediately. Use nextLine.
System.out.print("gender: ");
gender = in.nextLine();
(You probably mean "genre" instead of "gender" though)
Also, as mentioned in the comments, this check will never succeed:
if(movie == f)
You run this method in loop (right?)
The first call reads input correctly, but it leaves the linebreak in System.in after the last in.next().
On next call the name: is printed, then scanner reads an empty string from System.in because the linebreak already exists here.
And after thet the year: is printed on the same line because no new linebreaks are entered.
So you just have to insert another in.nextLine() after reading gender (or genre :) )
Or use nextLine() for read genre instead of next(), because genre might have more than one word.
But there are some disadvantages with using fake nextLine() to 'eat' linebreak - there might be another text which you doesn't process. It's a bad practice - to loose the data user entered.
It is better to read all the data from line, then validate/parse it, check isn't there some extra data, and if the data is invalid show notification and let him try to enter the right value.
Here are some examples how to deal with user input manually - https://stackoverflow.com/a/3059367/1916536. This is helpful to teach yourself.
Try to generalize user input operations:
name = validatedReader.readPhrase("name: ");
year = validatedReader.readNumber("year: ");
genre = validatedReader.readWord("genre: ");
where ValidatedReader is a custom wrapper for Scanner which could use your own validation rules, and could gently re-ask user after a wrong input.
It could also validate dates, phone numbers, emails, url's or so
For production purposes, it is better to use validation frameworks with configurable validation rules. There are a lot of validation frameworks for different purposes - Web, UI, REST etc...
when i enter the addMovie option, i get this print on the console (name: year:) can someone explain me why it happens i already searched a lot and i cant understand why :S
The way i understood your question is that you are getting the output (name: year: ) in a line and want it in seperate lines? In that case you simply can use System.out.println(String); instead of System.out.print(String). On the other hand you can also use "\n" whenever you want a linebreak within a String. Hope i could help you :).
Edit: If this was not an answer to your question, feel free to tell me and clarify your question :)
For String name you are using in.nextLine(); i.e the data entered on the entire line will be added to name string.
After "name: " is displayed, enter some text and press enter key, so that the year and gender fields will get correct values.
The code written is correct but you are not giving appropriate input through the scanner.
I recommend to use
String name = in.next();//instead of String name = in.nextLine();
You may instantiate Scanner Class differently for String and Integer type input. It works for me :)
Example:
static Scanner in1 = new Scanner(System.in);
static Scanner in2 = new Scanner(System.in);
Please use nextLine() for 'name' and 'gender'. It may contain more than one word. Let me know if it works.
Example:
System.out.print("name: ");
name = in1.nextLine();
System.out.print("year: ");
year = in2.nextInt();
System.out.print("gender: ");
gender = in1.nextLine();

scanner java validation and multiple instances

I am new to java and doing an assignment.
I have to request 3 inputs from the user and I have validation.
If I do it with only one instance of the scanner I get all messed up.
If I use three instances with a bit of workaround my code works.
Only I guess this is not best practice.
I have been reading a bit the manual regarding the scanner, but cannot understand the problem
Thanks
enter code here
Scanner input=new Scanner(System.in);
Scanner input2=new Scanner(System.in);
int input_integer=0;
double input_double=0.0;
String input_string="";
double value=0;
System.out.print("\n Please enter a number: ");
while(!input.hasNextInt()){
System.out.println("***** Error: the char inserted is not a number! *****");
String input_wrong=input.next();
System.out.print("\n Please enter a number: ");
}
input_integer=input.nextInt();
System.out.print("\n Please enter a double: ");
while(!input.hasNextDouble()){
System.out.println("***** Error: the char inserted is not a double! *****");
String input_wrong=input.next();
System.out.print("\n Please enter an double: ");
}
input_double=input.nextDouble();
System.out.print("\nPlease enter a string: ");
input_string=input.nextLine();
So I had two create 3 scanner instances and also to use a string to assign the wrong input in the while cycle to the able to prompt again.
Any suggestion?
I am sure there is a better way but I would try to understand..
Thanks!
I'm not exactly sure I understand what problem you're having, but scanner has some strange behaviors which are not immediately obvious. For instance, if you type "1234bubble" then press enter, then nextInt() will return 1234 and the next nextLine() will say "bubble". That is usually not desired behavior for inputs like this because "1234bubble" is not an integer and should have failed when the user pressed enter.
For that reason, I typically only use the function nextLine(). Then, I just process the data manually using functions like Integer.parseInt(..). That way, I can guarantee that I'm processing the whole line in a clear and obvious manner, unlike other techniques which create confusing code.
Here's how I would have written your program:
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Main
{
static Random rand = new Random();
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(System.in);
int input_integer = 0;
double input_double = 0.0;
String input_string = "";
double value = 0;
while (true)
{
System.out.print("Please enter an integer: ");
// Get the entire next line of text
String text = input.nextLine();
try
{
// Try to turn the line into an integer
input_integer = Integer.parseInt(text);
// Turning it into an int succeeded!
// Leave the while loop
break;
} catch (NumberFormatException e)
{
// Turning it into an int failed.
System.out.println("***** Error: the text inserted is not an integer! *****");
}
}
while (true)
{
System.out.print("Please enter a double: ");
// Get the entire next line of text
String text = input.nextLine();
try
{
// Try to turn the line into a double
input_double = Double.parseDouble(text);
// Turning it into an double succeeded!
// Leave the while loop
break;
} catch (NumberFormatException e)
{
// Turning it into an double failed.
System.out.println("***** Error: the text inserted is not a double! *****");
}
}
System.out.print("Please enter a string: ");
input_string = input.nextLine();
// This is done automatically when the program stops, but it's
// a good habit to get into for longer running programs.
input.close();
}
}

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();
}
}

Categories