Reading Console input

Hi I'm new to Java. I'm trying to read console input using readLine() Method of BufferedReader class in such a way that each method call assigns values to variables. The program compiles fine, but while running its simply skipping the readLine steps .

System.out.println("Enter Name");

String str=br.readLine();

System.out.println("Enter priority");

int p= br.read();

It doesnt wait for user input when run.

[446 byte] By [Sud28a] at [2007-11-27 7:01:23]
# 1

I don't see your definition of 'br' here.

Try this:

System.out.println("Enter data :");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String str = br.readLine();

System.out.println("You entered :" + str);

Message was edited by:

java_knight

java_knighta at 2007-7-12 18:52:12 > top of Java-index,Java Essentials,New To Java...
# 2

Here is my working main method:

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter Name");

String str=br.readLine();

System.out.println("Enter priority");

// attention: this is not the value you entered

// it is the code of the first character you entered!

int p= br.read();

// this works better - but think of catching the

// NumberFormatException!

int p2 = Integer.parseInt(br.readLine());

System.out.println("Name: " + str + "\nPriority: " + p);

}

mezlera at 2007-7-12 18:52:12 > top of Java-index,Java Essentials,New To Java...
# 3
thanks Java_knight,But I have declared br the same way as u specified before the starting of the snippet. The problem is that Its displaying both output Statements and goes to other line of code but doesnt wait for user input.
Sud28a at 2007-7-12 18:52:12 > top of Java-index,Java Essentials,New To Java...
# 4

Sud,

If you're using java 1.6 then try the Console class instead of a buffered reader, it has a lot of convenience methods which help make your code much smaller, tighter, cleaner, and therefore less buggy.

http://java.sun.com/javase/6/docs/api/java/io/Console.html

Keith

Message was edited by: corlettk

example of Console in action here: http://java.sun.com/docs/books/tutorial/essential/regex/test_harness.html

corlettka at 2007-7-12 18:52:12 > top of Java-index,Java Essentials,New To Java...
# 5
Thanks. But the actual problem is that it doesnt wait or allow me to enter any input. Just jumps to immediate following statements
Sud28a at 2007-7-12 18:52:12 > top of Java-index,Java Essentials,New To Java...
# 6
Yeah, so try a Console instead.
corlettka at 2007-7-12 18:52:12 > top of Java-index,Java Essentials,New To Java...
# 7
Thanx keith & corlettk, This is actually working
Sud28a at 2007-7-12 18:52:12 > top of Java-index,Java Essentials,New To Java...
# 8
Oh, cool... Happy travels then.
corlettka at 2007-7-12 18:52:12 > top of Java-index,Java Essentials,New To Java...