Failure trying to read String using Scanner.nextLine() [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 27 days ago.
I am trying to read a String and output it to the terminal, as well as a few primitives, but it does not seem to work. The code is below:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
String s = scan.nextLine();
scan.close();
System.out.println("String: " + s + "\n");
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
I have tried to find other ways to parse the string in the Scanner class, but none of them seemed to work. What I except is for the String to be properly read and outputed to the terminal, along with the few other values.
Thanks in advance.

The problem is that when you press enter (when you digit the number) you are inserting a \n character inside the buffer, so when you will call nextLine() you will read the \n (because nextLine reads the input until the \n) and you will not be able to write anything because the function returns when found the \n.
You can clean it calling scanner.nextLine() one more time
int i = scan.nextInt();
double d = scan.nextDouble();
// Remove \n from buffer
scan.nextLine();
String s = scan.nextLine();

Related

Scanner next methods in Java [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm new to Java and still confused on how the scanner next methods actually work. I have an example program right here:
import java.util.Scanner;
public class HelloJava{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int varInt;
String varString;
String varStringTwo;
System.out.print("Insert int value: ");
varInt = sc.nextInt();
System.out.print("Insert string value: ");
varString = sc.nextLine();
System.out.print("Insert another string value: ");
varStringTwo = sc.nextLine();
sc.close();
}
}
When i executed the program and entered an integer on the first prompt, the terminal looked like this:
Insert int value: 15
Insert string value: Insert another string value: // i can input any value here //
// ^ but the program doesn't allow me to input anything here
I know that one of the solution is to put "sc.nextLine();" between varInt = "sc.nextInt();" and "System.out.print("Insert a string value: ");", but I don't understand why or how.
When you scan a String values with spaces the scanner.next() method will get you the string up to space.
For example,
your input is This is a String
so when the first time you run scanner.next() it will return the value This. If you run it a second time it will return you is and so on.

Trying to scan for an integer and then a string [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
Im writing code to read an integer value, maybe a float, a double, and then finally read a string. What happens is that I enter the int, press enter after which the execution should stop until I enter a string. However, as soon as I press the enter to go to a newline, I get the outout which is only the number, because execution doesnt pause for me to enter the string. Whats going on
Tried inputting number and then string, that works. Tried inputting number followed by number,that works, tried inputting several strings, that works, but i couldnt get the program to read a number and then a string.
package test;
import java.util.Scanner;
public class Trying {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d=scan.nextDouble();
String s=scan.nextLine();
scan.close();
System.out.println("String: \'" + s+"\'");
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
I dont get an output for the string
Your problem is with using Scanner.nextLine() and Scanner.nextDouble() / Scanner.nextInt() together. You should be careful when using these together, as they might result in unexpected behavior. You can read the JavaDocs of the Scanner class for more detailed information. Instead of int i = scanner.nextInt(); double d = scanner.nextDouble(), try using double d = Double.parseDouble(scanner.nextLine()) to read in a String and convert it to a double.
You need to clear buffer in scanner before accepting a string input so just write
scan.nextLine();
before
String s=scan.nextLine();
and it shall work

Difficulty in displaying the input string in java [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I was solving a problem on Hackerrank in which I have to input an integer , a double and a string and print the result using stdout.
Input
42
3.1415
Welcome to HackerRank's Java tutorials!
Output
String: Welcome to HackerRank's Java tutorials!
Double: 3.1415
Int: 42
I wrote the following code and i'm not able to pass my test cases:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String ss = s.nextLine();
int i = s.nextInt();
double d = s.nextDouble();
System.out.println("String: "+ss);
System.out.println("Double: "+d);
System.out.println("Int: "+i);
}
}
is there anything wrong in the code?
The question also states that :-
Note: If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
Following was my output:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Solution.main(Solution.java:8)
Can anyone please explain this ?
the trick is to add s.nextLine(); before getting the String because it will reads the remainder of the line with the number on it (with nothing after the number I suspect)
Try placing a s.nextLine(); after each nextInt() if you intend to ignore the rest of the line.
so the full code will be like :
Scanner s = new Scanner(System.in);
int i = s.nextInt();
double d = s.nextDouble();
s.nextLine();
String ss = s.nextLine(
System.out.println("String: "+ss);
System.out.println("Double: "+d);
System.out.println("Int: "+i);

Use of nextLine() method after using nextInt() method [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I am not able to use nextLine method after using nextInt method.This is the note given below....
note in hacker rank:(If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
The nextLine method is not getting skiped but it is empty.
Code:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d=scan.nextDouble();
String s=scan.nextLine();
// Write your code here.
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
Output:
String:
Double: 3.1415
Int: 42
In Scanner class if we call nextLine() method after any one of the seven nextXXX() method then the nextLine() doesn’t not read values from console and cursor will not come into console it will skip that step. The nextXXX() methods are nextInt(), nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong(), next().
That's because the Scanner class' nextInt() method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner class' nextLine().
You can fire a blank Scanner class' nextLine() call after Scanner#nextInt to consume the rest of that line including newline
int option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();
You may try this.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
double y = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + y);
System.out.println("Int: " + x);
}
Yes it reads the remaining line which is empty. So while giving input pass whitespaces you will see the output, instead of printing string print it's length
When you are entering the integer for nextInt() then immediate you pres enter key and this enter key caught by nextLine(). s stores enter and that is known as whitespace so it not shows.

Concat() in Java [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I've been trying this program. But I'm not getting the required output.
import java.util.*;
class MiscTest {
public static void main(String[] args) {
int i = 10;
double d = 4.0;
String s = "Lavante ";
Scanner scanner = new Scanner(System.in);
int j;
double dd;
String ss;
j = scanner.nextInt();
dd = scanner.nextDouble();
ss = scanner.next();
System.out.println("\n" + (i + j));
System.out.println(d + dd);
System.out.println(s.concat(ss));
}
}
The input I've given:
The Output I got:
I need the whole sentence "Lavante is from Maserati" as output. But, I'm getting only one word from the Second String. Help me.
Thanks in advance.
Scanner#next() reads up to the first whitespace. If you want to read up to the end of the line, you should use nextLine() instead:
ss = scanner.nextLine();
You need to use nextLine() otherwise, Scanner stops at the whitespace delimiter using next()
Also, after having used scanner.nextDouble(), use scanner.next() to consume the rest of the characters not read by the previous call, just like below.
dd = scanner.nextDouble();
scanner.next();
ss = scanner.nextLine();
I guess you are hitting enter button after providing input of double variable. try code snippet.
dd = scan.nextDouble();
ss = scan.nextLine().trim();
if (ss.isEmpty()) {
ss = scan.nextLine();
}
You are currently using the next() Function which is using to take only a String before white spaces
Suppose Input : Hello World
Then If User using next()
Output: Hello
To take the string till the End of line Use nextLine()
Input: Hello World
If user using nextLine()
Output: Hello World

Categories

Resources