java couldn't take 2 continuous String input from user - java

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.

Related

Scanner not reading Next() or NextLine() immediately

I have the following code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter A name");
String aString = keyboard.nextLine();
System.out.print(aString);
System.out.print("Enter A message");
String bString = keyboard.nextLine();
System.out.print(bString);
Every time I execute this I enter the name then hit enter, nothing happens I enter the name again, nothing happens as well and I enter the name the third time and here we go it prints it. The same thing happens with the second string
I don't understand what could be wrong.
Have you defined keyboard? have a look here

The nextLine method is giving me an incorrect implementation

Why nextLine() method doesn't work? I mean, I can not enter any sentence after the second scan call because the program runs to the end and exits.
Input: era era food food correct correct sss sss exit
Should I use another Scanner object?
import java.util.*;
public class Today{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str="";
String exit="exit";
System.out.println("Please enter some words : ");
while(true){
str=scan.next();
if(str.equalsIgnoreCase(exit)) break;
System.out.println(str);
}
System.out.println("Please enter a sentnce : ");
String sentence1 = scan.nextLine();
System.out.println("the word you entered is : " + sentence1);
}
}
What Scanner#nextLine does is to
Advance this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end.
Since your input is era era food food correct correct sss sss exit you read inside the while every word with Scanner#next, so when Scanner#nextLine is called it returns "" (empty string) because there is nothing left of that line. That's why you see the word you entered is : (at the begging of the text is the empty string).
If you would have used this input: era era food food correct correct sss sss exit lastWord you would have seen the word you entered is : lastWord
The only thing you need to do in order to fix this is to call scan.nextLine(); first to move to the next line for the new input the user is going to provide and then get the new word with Scanner#nextLine() like this:
Scanner scan = new Scanner(System.in);
String str="";
String exit="exit";
System.out.println("Please enter some words : ");
while(true){
str=scan.next();
if(str.equalsIgnoreCase(exit)) break;
System.out.println(str);
}
scan.nextLine(); // consume rest of the string after exit word
System.out.println("Please enter a sentnce : ");
String sentence1 = scan.nextLine(); // get sentence
System.out.println("the word you entered is : " + sentence1);
Demo: https://ideone.com/GbwBds

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

Why cant I read whole line along with double using Scanner(System.in)?

What actually happens here ?
Why can't I store a String with spaces in between as name ?
I tried the delimiter thing, but didn't worked. Is there a way that will produce the desired output ?
I know .next() works but we might need to store a string with space. Just curious ...
Scanner input=new Scanner(System.in);
System.out.print("Enter number of Students:");
double [] scores = new double[input.nextInt()];
String [] names=new String[scores.length];
for(int i=0;i<names.length;i++){
System.out.println("Enter the students name: ");
names[i] = input.nextLine();
System.out.println("Enter the student scores : ");
scores[i]=input.nextDouble();
}
when you call input.nextInt(), it doesn't consume the new line character on that line, so the following call to input.nextLine(); will consume the newline, and return the empty string. nextDouble() will function properly.
one way to fix this is to call input.nextLine(); immediately before the for loop to consume the extra new line character
Edit:
String [] names=new String[scores.length];
input.nextLine(); //literally add the call right here
for(int i=0;i<names.length;i++){
According to the Javadoc:
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
What if you replace the default delimiter with "\n" like this:
Scanner s = new Scanner(input).useDelimiter("\\\\n");
This is how it works ! Thanks for concern guys! :)
for(int i=0;i<names.length;i++){
if(input.nextLine().equals("")){
System.out.println("Enter students name : ");
names[i] = input.nextLine();
}
System.out.println("Enter the student scores : ");
scores[i]=input.nextDouble();
}

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