0

here is a very simple code, in which i am trying to take input from keyboard in a loop. For every input, the loop is automatically running two extra times and taking the values 13 and 10, no matter what i give as input. can you please point out what i am doing wrong.

CODE:

public static void main(String args[]) { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); boolean loop_cond=true; int n=1; while(loop_cond==true) { try { System.out.print("input : "); n=br.read(); } catch (IOException e) { e.printStackTrace(); } System.out.print(n+"\n"); } } // end Main 

OUTPUT :

input : 6 54 input : 13 input : 10 input : 9 57 input : 13 input : 10 input : 1 49 input : 13 input : 10 input : 
3
  • 2
    13 is a carriage return and 10 is a newline. unixhelp.ed.ac.uk/CGI/man-cgi?ascii+7 Commented Mar 21, 2013 at 3:59
  • I believe your program also reads in the "Enter/New line" character Commented Mar 21, 2013 at 4:00
  • Understood it. But how to prevent this ? i only want to run the loop only once for every input i provide. Commented Mar 21, 2013 at 4:02

2 Answers 2

1

Those are probably \r\n values. Try Scanner to take in values.

 Scanner input = new Scanner(System.in); int i = input.nextInt(); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much Sudhanshu. It is working just the way i want. But can you tell me how to implement this in BufferedReader ?
use readLine() instead of read(). readLine() returns String so you might have to convert it to int.
1

Change

n=br.read(); 

to

n = Integer.parseInt(br.readLine()); 

But I would recommend you to use Scanner class to avoid the Integer conversion.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.