Java Scanner not accepting String after hitting enter [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 6 years ago.
In this snippet what I am doing taking three different types of variables and adding them and then printing then down.
public static void main(String[] args) {
int i = 4;
double d = 4.0;
String s = "HackerRank ";
Scanner scan = new Scanner(System.in);
int firstVariable = 0;
double secondVariable = 0.0;
String theString = "";
firstVariable = scan.nextInt();
secondVariable = scan.nextDouble();
theString = scan.nextLine();
System.out.println(firstVariable+i);
System.out.println(secondVariable+d);
System.out.println(s+""+theString);
}
I am providing input for firstVariable hitting enter and then providing the input for secondVariable and now as soon as I hit enter theString is capturing that value(I know it should capture it).
EDIT: in this case how should I provide the input to theString without as well as with space ?
I did try something like this,
while(scan.hasNext())
theString = scan.nextLine();
But it didn't work either.

Simply check scan.nextLine() is empty if so call scan.nextLine() again as next:
secondVariable = scan.nextDouble();
theString = scan.nextLine().trim();
if (theString.isEmpty()) {
theString = scan.nextLine();
}
Another approach with a pattern:
firstVariable = scan.nextInt();
secondVariable = scan.nextDouble();
theString = scan.next("\\w+");

There are two ways to solve your problem:
The first one is to use
nextLine()
each time you read from the user like this:
int firstVariable = scan.nextInt();
scan.nextLine();
double secondVariable = scan.nextDouble();
scan.nextLine();
String theString = scan.nextLine();
The second one is to parse the integer and double value from nextLine() like this:
int firstVariable = Integer.parseInt(scan.nextLine());
Double secondVariable = Double.parseDouble(scan.nextLine());
String theString = scan.nextLine();

You need to add an extra scan.nextLine(); before your String theString, to capture the Enter after the double. Like this:
firstVariable = scan.nextInt();
secondVariable = scan.nextDouble();
scan.nextLine();
theString = scan.nextLine();
Just as an advice to reduce your code, there's no need to add these:
int firstVariable = 0;
double secondVariable = 0.0;
String theString = "";
Just add the type to the variables to capture the scan:
int firstVariable = scan.nextInt();
double secondVariable = scan.nextDouble();
scan.nextLine();
String theString = scan.nextLine();

Related

writing multiple words to one CSV cell

I'm currently trying to create a little program which creates Recipes as csv files. That worked fine till the point where I want to add an Ingredient with spaces in between for example: 'real big bananas'. Whenever I write something like this or with underscores or with minus it enters null instead of the word I wrote.
I have a class Ingredients(double amount, String unit, String ingredient, String tags) with getter and setters for all of the variables.
My Code for creating a csv
public static ArrayList<Ingredients> createIngredientList() {
Scanner scan = new Scanner(System.in);
ArrayList<Ingredients> list = new ArrayList<Ingredients>();
char quit = 'Y';
String unit, ingredient, tags;
double amount;
while(quit == 'Y') {
System.out.print("Please use underscores instead of spaces e.g. real_big_boats.\n");
System.out.print("Amount: ");
amount = scan.nextDouble();
System.out.print("Unit: ");
unit = scan.next();
System.out.print("Ingredient: ");
ingredient = scan.nextLine();
System.out.print("Tags (e.g. tag;tag;tag): ");
tags = scan.nextLine();
list.add(new Ingredients(amount, unit, ingredient, tags));
System.out.print("More Ingredients? (Y/N) ");
String s = scan.next();
s = s.toUpperCase();
quit = s.charAt(0);
}
return list;
}
You can find the whole class in my pastebin below.
https://pastebin.com/vi09kGqi
while (quit == 'Y') {
System.out.print("Please use underscores instead of spaces e.g. real_big_boats.\n");
System.out.print("Amount: ");
amount = scan.nextDouble();
scan.nextLine() ;
System.out.print("Unit: ");
unit = scan.next();
scan.nextLine() ;
System.out.print("Ingredient: ");
ingredient = scan.findInLine("(\\s|\\S)*");
scan.nextLine() ;
System.out.print("Tags (e.g. tag;tag;tag): ");
tags = scan.next();
scan.nextLine() ;
list.add(new Ingredients(amount, unit, ingredient, tags));
System.out.print("More Ingredients? (Y/N) ");
String s = scan.next();
scan.nextLine() ;
s = s.toUpperCase();
quit = s.charAt(0);
}
This is due to a known problem with Scanner in java. Check the link here: Scanner is skipping nextLine() after using next() or nextFoo()?
You can use a blank scanner.nextLine() after every scanner.nextDouble() or scanner.next() to overcome this.
public static ArrayList<Ingredients> createIngredientList() {
Scanner scan = new Scanner(System.in);
ArrayList<Ingredients> list = new ArrayList<Ingredients>();
char quit = 'Y';
String unit, ingredient, tags;
double amount;
while(quit == 'Y') {
System.out.print("Please use underscores instead of spaces e.g. real_big_boats.\n");
System.out.print("Amount: ");
amount = scan.nextDouble();
scan.nextLine();
System.out.print("Unit: ");
unit = scan.next();
scan.nextLine();
System.out.print("Ingredient: ");
ingredient = scan.nextLine();
System.out.print("Tags (e.g. tag;tag;tag): ");
tags = scan.nextLine();
list.add(new Ingredients(amount, unit, ingredient, tags));
System.out.print("More Ingredients? (Y/N) ");
String s = scan.next();
s = s.toUpperCase();
quit = s.charAt(0);
}
return list;
}
Output:
Please use underscores instead of spaces e.g. real_big_boats.
Amount: 111
Unit: 111
Ingredient: a b c
Tags (e.g. tag;tag;tag): a b c
More Ingredients? (Y/N) N
Ingredients [amount=111.0, unit=111, ingredient=a b c, tags=a b c]
Another solution would be to accept every input as String by using scanner.nextLine() and then parsing it to the desired type.

How to scan a string in java and then concate it with other string? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
The code is not scanning the second string form user. It just prints 'Hello' second string is not printed.
package online_questions;
import java.util.Scanner;
public class Add {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int i = 4;
double d = 4.0;
String s = "Hello ";
int a = scan.nextInt();
double b = scan.nextDouble();
String c = scan.nextLine();
System.out.println(i+a);
System.out.println(d+b);
System.out.println(s + c);
}
}
after
double b = scan.nextDouble();
add
scan.nextLine();
The methods nextInt nextDouble etc doens't move to the next line automatically. So you need to call them explicitely.
After reading double b there will be a newline character in the buffer. nexLine() will read upto new line character '\0 so that's why your getting empty string simply addscan.nextLine();after reading your double
You need to call nextLine after nextDouble.
double b = scan.nextDouble();
scan.nextLine();
String c = scan.nextLine();

Scanner not asking input of string

In the below code:
secondI = scan.nextInt();
System.out.println("double");
secondD = scan.nextDouble();
System.out.println("string");
secondS = scan.nextLine();
After entering the double value, it is skipping the string entry part. How can I fix this?
secondI = scan.nextInt();
System.out.println("double");
secondD = scan.nextDouble();
scan.nextLine();
System.out.println("string");
secondS = scan.nextLine();
You need to have this extra nextline statement which consumes the remaining section of that line which you entered for the double value.
Use
secondS = scan.next();
instead of
secondS = scan.nextLine();
Please see the documentation for Scanner.nextLine().
Advances this scanner past the current line and returns the input that was skipped.
Try using other methods of the Scanner class such as Scanner.next()

Getting issues while reading series of lines using scanner

I'm trying to read the input which is in the following format.
2
asdf
asdf
3
asd
df
2
Following is the code:
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
System.out.println(t);
while(t>0){
String a = scanner.next();
String b = scanner.next();
int K = scanner.nextInt();
}
But when I'm scanning, I'm getting empty t=2 , a="" , b=asdf, K=asdf
Can't figure out the issue. There is no space/new line between 2 and asdf.
I have tried using scanner.nextLine() instead of scanner.next() but no change
nextInt() doesn't cosume the newline token, so the following read will get it. You could introduce a nextLine after the nextInt to skip it:
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
scanner.nextLine(); // Skip the newline character
System.out.println(t);
while(t > 0) {
String a = scanner.next();
String b = scanner.next();
int K = scanner.nextInt();
scanner.nextLine(); // Skip the newline character
}
Another approach I prefer:
Scanner scanner = new Scanner(System.in);
int t = Integer.parseInt(scanner.nextLine());
System.out.println(t);
while(t>0){
String a = scanner.nextLine();
String b = scanner.nextLine();
int K = Integer.parseInt(scanner.nextLine());
}
But note it will throw NumberFormatException when input is incorrect.

Do-while loop inside a method [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
Everything is working fine in this code sample that i did, but everytime it calls the do-while loop on the output screen, it skips the "First name" input, and goes straight to "How old are you?" input. why is that happening and how can i fix it? I want to be able to repeat the whole thing without skipping "First name" when i pick 'y' to perform the loop.
public class WeightGoalTest
{
public static void main(String[]args)
{
doWhile person = new doWhile();
person.userInput();
}
}
import java.util.*;
public class doWhile
{
Scanner keyboard = new Scanner(System.in);
private String inputFn = "";
private int inputAge = 0;
private int inputHeight = 0;
private double inputWeight = 0.0;
private int inputCalculation = 0;
private int inputGender = 0;
private char loop;
public void userInput()
{
do
{
System.out.println("First Name: ");
inputFn = keyboard.nextLine();
System.out.println("How old are you?");
inputAge = keyboard.nextInt();
System.out.println("Gender 1 - Male: ");
System.out.println(" 2 - Female: ");
inputGender = keyboard.nextInt();
System.out.println("What is your Height in inches? ");
inputHeight = keyboard.nextInt();
System.out.println("Current Weight in pounds: ");
inputWeight = keyboard.nextDouble();
System.out.println("\nDo you want to use the calculator again? (y/n)");
loop = keyboard.next().charAt(0);
}while(loop == 'y');
}
}
Please note:
String java.util.Scanner.next() - Returns:the next token
String java.util.Scanner.nextLine() - Returns:the line that was skipped
Change your code [do while initial lines] as below:
System.out.println("First Name: ");
inputFn = keyboard.next();
use keyboard.next() instead of .nextLine(). For further informations have a look in the Java API concerning the Scanner class. nextLine() will
Advance this scanner past the current line and return the input that was skipped."

Categories

Resources