BufferedReader / Scanner Last Line Reading Issue - java

While solving a problem at hacker-rank I am facing the issue that scanner/bufferedreader is unable to read the last. As the input provided by them is like
10
abcdefghijk
2
R 1 2
W 3 4
So both scanner/bufferedreader is unable to read the last line. If the input is like then the code seems to work fine.
10
abcdefghijk
2
R 1 2
W 3 4
(End of Input)
public class ScannerTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int len = input.nextInt();
input.nextLine();
String inputString = input.nextLine();
int qc = input.nextInt();
input.nextLine();
System.out.println();
System.out.println(len + inputString + qc);
for(int i=0;i<qc;i++){
String l = input.next();
int le = input.nextInt();
int ri = input.nextInt();
input.nextLine();
System.out.println(l+le+ri);
}
input.close();
}
}
Here is the sample code which I am using. I know that we need a \r or\n at the end of line to readline from scanner / bufferedreader. But can anyone provide a solution to this issue as input comes from system that is predefined.

BufferedReader would read the last line even if it does not end in a line break. System.in is the culprit, that does its own line buffering.
A native system thing: suppose you pressed a couple of backspaces to change the last number...

The problem is here:
input.nextLine();
String inputString = input.nextLine();
You are consuming a line to just throw it away.
The other thing is: especially when dealing with standard libraries - don't assume that something is broken/doesn't work. In 99,999% of all case the problem is something within your code.

Related

read multiple variables with scanner in one line

I am trying to read multiple variables from the console with the scanner in only one line (separated with a blank space).
if I type:
int hight = Integer.parseInt(reader.nextLine());
int width = Integer.parseInt(reader.nextLine());
int depth = Integer.parseInt(reader.nextLine());
then it displays my numbers (for example 1,2,3) like this:
1
2
3
but I would want it to display my numbers like that: 1 2 3
Can someone help me?
One way to do this is to use nextInt instead of nextLine:
int hight = reader.nextInt();
int width = reader.nextInt();
int depth = reader.nextInt();
Your input can then be like this:
1 2 3
Note that you have to enter all three numbers before pressing ENTER, or else your input will look like this again:
1
2
3
Another way to do this is to use a regex to specify the exact format that you want your input to be in, call nextLine, and match the line that the user entered to the regex pattern:
Matcher matcher = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)").matcher(reader.nextLine());
if (matcher.matches()) {
int height = Integer.parseInt(matcher.group(1));
int width = Integer.parseInt(matcher.group(2));
int depth = Integer.parseInt(matcher.group(3));
} else {
// input was invalid!
}
As per your comment you can simply read numbers as integers like :
Scanner br =new Scanner(System.in);
int a=br.nextInt();
int b=br.nextInt();
int c=br.nextInt();
Give input as 1 2 3.
To input all 3 values in one line you can use. . readInt() three times instead of using .readNextLine(). That way you can put your input like this 1 2 3 and after pressing Enter on the keyboard (which is by default used to end the input) you get what you were asking for.
If your intention was to get an output in one line instead of multiline one, you should use other version of method printing to the console:
System.out.print(height + " " + weight + " " + depth)
System.out.println() prints the next line character after its argument, System.out.print() doesn't.
For input in single line in space separated format. You can do that using Scanner and BufferReader in Java.
1. Scanner class
Scanner sc = new Scanner(System.in);
int[] integers;
String input = sc.nextLine();
String[] strs= input().split(" ");
for(int i=0;i<strs.length;i++){
integers[i]=Integer.parseInt(strs[i]);
}
2. BufferReader Class
BufferReader br = new BufferReader(new InputStreamReader(System.in));
int[] integers;
String input = br.readLine();
String[] strs= input().trim().split("\\s+");
for(int i=0;i<strs.length;i++){
integers[i]=Integer.parseInt(strs[i]);
}

Java Scanners: How to keep the same line after an input

I have a small code segment that I do not know how to fix. This is it:
System.out.print("y=");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("x+");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();
The output is: y=3 on one line, and x+4 on the next. I would like them to be on the same line. How do I do this?
I'm not sure what you want to do there but maybe you just need to use one System.out.print? at the bottom of your code with example:
System.out.print("y= %d x+%d", m , b);
It is bit confusing to understand your question why you want it ?
But here is a snippet you can try and see if it can be useful to you!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class so1 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String arrayStr = br.readLine();
String[] auxStr = arrayStr.split(" ");
int[] arr = new int[2];
for(int i=0;i<auxStr.length;i++){
arr[i]= Integer.parseInt(auxStr[i]);
}
System.out.println("y="+arr[0] + " x+"+arr[1]);
}
}
Here is what you can get -
3 4
y=3 x+4
Update your question if you not find it useful . I will update accordingly.
Looks like this is how your program looks:
y=3<newline>
x+5<newline>
But you want it to look like:
y=3x+5
The problematic newlines come from using the scanner and the inherently buffered nature of standard input. In order for the scanner to know that it's reached the end of the number, there has to be whitespace (space, newline, etc.) And in order for the program to receive the input from STDIN, the character length of the int has to be larger than the buffer size, or ENTER has to be pushed.
TL;DR - What you want is very difficult to do, and maybe impossible, just using basic standard in. If you really want the output you desire you'll probably need to find a library for interacting with the console and use that.
However, if you reframe your input, you might be able to get something almost as good:
enter intercept: 5<enter>
enter slope: 3<enter>
y=3x+5
Your code, modified to produce that output:
System.out.print("enter intercept:");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("enter slope: ");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();
System.out.println("y="+m+"x+"+b);

How to pull int value from text file of strings and ints?

I'm trying to write a program that is practically a stack. Given a text file with certain keywords, I want my program to evaluate the text line by line and perform the requested action to the stack.
For example, if the input file is:
push 10
push 20
push 30
The resulting stack should look like:
30
20
10
However, I don't know how to push these values into the stack without hardcoding an int value after the word push. I made a String variable and assigned it to scanner.nextLine()
From there, I compare the line with strLine: if strLine is equal to push followed by some Number, then that number would be pushed on the stack.
However, it seems that the method nextInt() isn't taking this number from the input stream.
Scanner input = new Scanner(file)
int number;
String strLine;
while (input.hasNextLine()){
strLine = input.nextLine();
number = input.nextInt();
if(strLine.equals("push " + number)){
stack.push(number);
}
How can I fix this?
Thank you.
Get the input and split it with space " "!
That will give ["push","1"]
convert the first index to int and then push the value to stack!
while (input.hasNextLine()){
String[] strLine = input.nextLine().split(" ");
if(strLine[0].equals("push")){
stack.push(Integer.parseInt(strLine[1]));
}
else if(strLine[0].equals("pop")){
stack.pop();
}
else{
system.out.println("Please enter a valid input!");
}
}
Hope it helps!
input.nextLine reads the whole line, including the number. What you can do instead is to use input.next() to get the "push" and input.nextInt() to get the number. This example is using Scanner with System.in (so it needs "quit" to exit the while loop), but it should also work with a file (in which case you don't need to type "quit" to exit the program, as it will do so automatically when the input file has no more input). The advantage of using parseInt (as some of the other answers have suggested) is that you can catch any errors in integer input using a try/catch block.
import java.util.Scanner;
import java.util.Stack;
import java.util.InputMismatchException;
public class StackScanner {
public static void main(String args[]) {
Stack<Integer> stack = new Stack<Integer>();
Scanner input = new Scanner(System.in);
int number;
String strLine;
while (input.hasNext()){
strLine = input.next();
if(strLine.equals("push")){
try {
number = input.nextInt();
stack.push(number);
} catch ( InputMismatchException e) {
System.out.println("Invalid input. Try again.");
input.nextLine();
continue;
}
} else {
break;
}
}
System.out.println(stack);
}
}
Sample output:
push 5
push 6
push 3
quit
[5, 6, 3]
change this:
number = input.nextInt();
to this:
number = Integer.parseInt(input.nextLine());
nextLine method parses the whole line including any numbers in the line. So, you need to take care of splitting the line and parsing the number in your code.
Something like below will work where I split the line with spaces. Although, there are many such ways possible.
Scanner input = new Scanner(file);
String strLine;
Stack<Integer> stack = new Stack<>();
int number;
while (input.hasNextLine()){
strLine = input.nextLine();
if(strLine.startsWith("push")){
String[] sArr = strLine.split("\\s+");
System.out.println(strLine);
if(sArr.length==2){
number=Integer.parseInt(sArr[1]);
stack.push(number);
System.out.println(number);
}
}
}
If I understand your problem, I would simply tokenize the line by splitting on whitespace.
It looks like your input is relatively structured: you have a keyword of some kind then whitespace then a number. If your data is indeed of this structure, split the line into two tokens. Read the value from the second one. For example:
String tokens[] = strLine.split(" ");
// tokens[0] is the keyword, tokens[1] is the value
if(tokens[0].equals("push")){
// TODO: check here that tokens[1] is an int
stack.push(Integer.parseInt(tokens[1]));
} else if (tokens[0].equals("pop")) { // maybe you also have pop
int p = stack.pop();
} else if ... // maybe you have other operations

reading 3 integers in one line java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
help me finding a way to read from user 3 integers in one line and then treat each saparately as a,b,c .. please be quick because i had tried reading a whole line but i want to deal with each integer in later statement
import java.util.Scanner;
public class MHDKhaledTotonji_301300797 {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
int M,a,b,c;
System.out.println("Please, insert the normal dose in ml");
M = input.nextLine();
}
}
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
takes: 1 2 3
nextLine() returns a String, so M should be defined as a String.
Java naming conventions generally state that variables should start with lowercase letter, so M should be m.
As for the task of getting 3 integers from the user on one line, you have multiple choices, and it depends on how strict you want to be and how much error handling you need.
For very easy solution, with no error handling (kills program on bad input), Scanner is the answer. Error handling can be added, but is cumbersome.
Scanner in = new Scanner(System.in);
System.out.println("Please, insert the normal dose in ml");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
Another solution might be to read the line, like you are trying to do, then split the line and parse the values. A little more code, but forces user to enter all 3 on one line, which solution #1 doesn't.
Scanner in = new Scanner(System.in);
System.out.println("Please, insert the normal dose in ml");
String line = input.nextLine();
String[] values = line.split(" ");
int a = Integer.parseInt(values[0]);
int b = Integer.parseInt(values[1]);
int c = Integer.parseInt(values[2]);
For better control of the line from the user, a regular expression can be used. Here it is with full error handling.
Scanner in = new Scanner(System.in);
Pattern p = Pattern.compile("\\s*(\\d+)\\s+(\\d+)\\s+(\\d+)\\s*");
int a = 0, b = 0, c = 0;
for (;;) {
System.out.println("Please, insert the normal dose in ml");
String line = input.nextLine();
Matcher m = p.matcher(line);
if (m.matches())
try {
a = Integer.parseInt(m.group(1));
b = Integer.parseInt(m.group(2));
c = Integer.parseInt(m.group(3));
break;
} catch (Exception e) {/*fall thru to print error message*/}
System.out.println("** Bad input. Type 3 numbers on one line, separated by space");
}
use input.nextInt() instead of input.nextLine(). Also this is wrong because input.nextLine() returns String and you should parse to integer.
Simple change your code to:
M = input.nextInt();
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
Stick in mind that input.nextInt() ignores every white space including line feeds so you don't need to worry about reading from the same or different lines.

How do I make Java register a string input with spaces?

Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}

Categories

Resources