how to take char input before int input in java? - java

public class Pack1 {
public static void main(String ar[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the character");
char c=(char)br.read();
System.out.println(c);
System.out.println("enter the integer");
long l=Integer.parseInt(br.readLine());
System.out.println("long l="+l);
System.out.println(c);
}
}

Let's say the user types X and presses Enter on the first question, then types 123 and presses Enter on the second question, that would mean that the input stream contains the following characters:
X <CR> 1 2 3 <CR>
When you call read(), you only read the X. When you then call readLine(), you read the <CR> and get a blank string back.
The 1 2 3 <CR> is still sitting unread in the input stream.
Solution: Call readLine() after reading the X to skip past the rest of the line, or use readLine() to read the X as a String, instead of as a char.
FYI: This is the exact same problem people keep having when using Scanner and mixing calls to nextLine() with calls to other nextXxx() methods, like nextInt().

Change this:
long l=Integer.parseInt(br.readLine());
to :
long l=Long.parseLong(br.readLine(), 10);
This is because you are trying to convert the String to Long and not an Integer type.

Related

Read user input [duplicate]

This question already has answers here:
What is the use of System.in.read()?
(10 answers)
Closed 4 years ago.
I am really new to Java, and I was following a book tutorial on how to read user input. Their code was...
class Example {
public static void main(String args[]) throws java.io.IOException {
// System.out.println()
char ch;
System.out.print("Press a key followed by ENTER: ");
ch = (char) System.in.read();
System.out.println("Your key is: " + ch);
}
}
I tried to experiment and read user input as an integer like this...
class Example {
public static void main(String args[]) throws java.io.IOException {
int foo;
System.out.print("Enter a number: ");
foo = (int) System.in.read();
System.out.print("Your number was: " + foo);
}
}
However, upon typing for example number 12, I get the output as 49. Why is that? How come the book tutorial worked then?
EDIT: When I type in 'w' in my program, it still prints out 119. Surely I thought the throws thing was dealing with that? Or is it not?
And what is a Scanner (just saw it in the comments)?
System.in.read() Reads the next byte of data from the input stream.
So you are just reading 1 from input and you are printing ASCII code of 1 which is 49. If you want to show the character you should read it as char or convert it:
System.out.print("Your number was: " + (char) foo)
Answering Your Question
However, upon typing for example number 12, I get the output as 49.Why
is that?
The reason you got 49, is because you only read the first char of the input (the program only read the '1' digit). The ASCII value of 1, surprisingly equals to 49.
Better Approach
I would suggest to use the Scanner object to read inputs from System.in, like this.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();
This approach will populate the 'sentence' String, with the entire line entered in the console.
If you need a number and not a String, parse that string to an int using Integer.valueOf(yourString);

confused with buffered reader in java

when i run the code only with //1 - start, the output is ascii value of input character
when i run the code only with //2 - start, the output is the entered string terminated by newline character
when i run the code with both (as shown in below code), only //1 - start executes, readLine() is being considered in a strange way.
when i run the code with both (with //2 - start placed above //1 - start), both the codes executes fine,
Please explain why this strange behavior happens in case 3 but not in case 4.
public class InputBufferedReader {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
//1-start
//read one character
System.out.println("enter input: ");
int b= br.read();
System.out.println(b);
//end
//2-start
//read a string
System.out.println("enter input string: ");
String a = br.readLine();
System.out.println(a);
//end
} catch (IOException e) {
e.printStackTrace();
}
}
}
Your BufferedReader uses the InputStreamReader with System.in. The BufferedReader uses the read() method from InputStreamReader to read the data from the standard input stream System.in. Now lets look into the API for this read() method.
[...] This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
Blocking means in this context waits for user to input data throu the console confirming with the Enter Key.
With that in mind lets examine your cases.
1. int b= br.read(); Nothing is already typed, so this method blocks until user typed something and then prints the ascci value of first character.
2. String a = br.readLine(); Nothing is already typed, so this method blocks until user typed something and then prints the whole line.
3.
int b= br.read();
Lets image user typed a confirming with Enter Key that means the input is a\n. Now read() reads the first character which is a.
String a = br.readLine();
This read() call will not block and ask for user input because there is unconsumed input left \n. So readLine() will read \n.
4.
String a = br.readLine();
User is asked for input which is confirmed with Enter Key. And the whole line will be read.
int b= br.read();
There are no unconsumed data left, because readLine() already has read the whole line including \n character. So this read() call blocks and user is asked for input.
int read() method attempts to Read Next Character from the Console(or File) and Return its Unicode Value,
As this Method Returns Unicode Value Compulsory at the Time of Printing we- should perform type- Casting.
If there is No Next Character the we will get -1.
String readLine() Method attempts to Read Next Line from Console(or File) and Returns it, if it is available.
If the Next line is Not available, then return null.

Scanner wont work [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I have problem with Scanner
When I run the program it skips this one after
System.out.println("name");
n1=s.nextLine();
This is the program "CEmploye " is a class
package Ex5_2;
import java.util.*;
public class XXXX {
public static void main(String[] args) {
int input;
int c1 ;
String n1;
Date d1 = null;
float p1;
float [] t = new float[3];
System.out.println("give nb of emp");
Scanner s = new Scanner(System.in);
input=s.nextInt();
Vector v = new Vector(input);
for(int i=0 ;i <input;i++)
{
System.out.println("cin");
c1=s.nextInt();
System.out.println("name");
n1=s.nextLine();
System.out.println("price");
p1=s.nextFloat();
for(int k=0 ; k<3;k++)
{
System.out.println("nb of hour");
CEmploye.tab[k]=s.nextFloat();
}
CEmploye emp = new CEmploye(c1,n1,d1,p1);
emp.CalculSalaire();
System.out.println(emp.salaire);
}
}
}
Can anyone give me solution ?
System.in's buffer isn't flushed until it gets a newline. So you can't use nextInt() or nextFloat() because they block until a newline.
You'll need to read everything on a line by itself then parse it (with some validation as needed):
cl = Integer.parseInt(s.nextLine());
and
pl = Float.parseFloat(s.nextLine());
and
CEmploye.tab[k]=Float.parseFloat(s.nextLine());
You can't use n1=s.nextLine(); with n1=s.nextInt(). Use n1=s.next();
nextInt() only reads the next integer available and leaves a newline character in the inputstream.
Your s.nextLine() then gets consumed thus not prompting for additional inputs.
Simply add another nextLine() to read more lines
c1=s.nextInt();
This just reads the integer value not the end of line. So when you do
n1=s.nextLine();
it just reads the end of line that you provided by pressing the enter while providing the integer input for the previous variable (c1) and thus seems like it skipped the input. (If you put an integer and some string in the same line when taking c1 input, you will get values for c1 and n1 both. You can check the same)
In order to fix it, either put nextLine() input after each nextInt(). Hope it helps.

Counting carriage return, Java

I am trying to count carriage return occurrences within string input. I tried both Scanner and BufferedReader. With Scanner, nextLine() does not pick up Carriage Returns. next() with Scanner looks for tokens, such as a space in input, and token splits up the input. I want the entire input to be read as single input. This probably means I cannot use Scanner.
With BufferedReader, readLine() reads up to a Carriage Return, but does not return a Carriage Return in input. If I use "reader.read();" then it tells me that the variable user_input HAS to be int. user_input is supposed to be a string input that MAY have an integer, but it also may not. The only thing is that program would continue until input contains "/done". I would appreciate it if somebody would simply point me in the right direction!
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String user_input = "";
System.out.println("Enter a string: ");
while (!user_input.contains("/done")) {
user_input = reader.readLine(); //cannot be readLine because it only reads up to a carriage return; it does NOT return carriage return
//*Sadly, if I use "reader.read();" then it tells me that user_input HAS to be int. user_input is a string input
String input = user_input;
char[] c = input.toCharArray();
int[] f = new int[114];
System.out.println("Rest of program, I convert input to ascii decimal and report the occurences of each char that was used");
}
catch (IOException e) {
e.printStackTrace();
}
}
Is this what you're looking for?
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\\z"); //"\\z" means end of input
String input = scanner.next();
EDIT: If you want the "\n" to show as "CR", just do this:
input.replaceAll("\\n", "CR");
There's a library called StringUtils that can do this very easily. It has a method named countMatches. Here's how you can use it. But first, you should combine your input into one string:
package com.sandbox;
import org.apache.commons.lang.StringUtils;
public class Sandbox2 {
public static void main(String[] args) {
String allInput = "this\nis\na\n\nfew\nlines\nasdf";
System.out.println(StringUtils.countMatches(allInput, "\n"));
}
}
This outputs "6".
Read characters one by one until EOF is encountered using read() method.
JAVA DOCS
read() in java reads any character(even \n, \r or \r\n). Thus read character one by one and check whether the character read in "Carriage return" or not.
If yes, then increase the counter.

Scanner input from InputStream

I'm doing test driven development which requires me to write a test function for a class that takes input from the user. Since the console input function stops for input during tests, I wrote the tests using an InputStream which uses a string.
String str="3\n2\n1\n4\n";
InputStream is = new ByteArrayInputStream(str.getBytes());
assertTrue(app.RunApp(is));
This leads to the calling of the function getChoice(InputStream i) which involves console input from a Scanner.
public int getChoice(InputStream i) throws IOException {
Scanner s=new Scanner(i);
s.useDelimiter("\n");
String y= s.next();
int x=Integer.parseInt(y);
return x;
}
I want the above code to take the numbers in the string one by one. But, what is happening is that it takes the first number properly and then, the position of the stream goes directly to the end of the stream which causes a NoSuchElementException. Please Help!
Use...
String y = s.nextLine(); // That will take the entire line instead of only 1st word

Categories