Forum Stats

  • 3,741,306 Users
  • 2,248,410 Discussions
  • 7,861,732 Comments

Discussions

skipping the statement in the code

945595
945595 Member Posts: 73
Hi all, I have doubt in following java code , Bolded line is not executing(instead its skipping) I mean i cant enter name.

Code :
import java.io.*;
public class ManyInputs {
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));


System.out.print("Enter your id:");
int n=Integer.parseInt(br.readLine());

System.out.print("Enter your sex M/F:");
char c=(char)br.read();
System.out.print("Enter your name:");
String name=br.readLine();




System.out.println("Your Id:"+n);
System.out.println("Your sex:"+c);
System.out.println("Your name:"+name);
}

}


Output:
Enter your id:504
Enter your sex M/F:m
Enter your name:Your Id:504
Your sex:m
Your name:

But if i change the order of the statements its working perfectly, like below

COde:

import java.io.*;
public class ManyInputs {
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));


System.out.print("Enter your id:");
int n=Integer.parseInt(br.readLine());
System.out.print("Enter your name:");
String name=br.readLine();
System.out.print("Enter your sex M/F:");
char c=(char)br.read();





System.out.println("Your Id:"+n);
System.out.println("Your sex:"+c);
System.out.println("Your name:"+name);
}

}

Output:
Enter your name:Reddy
Enter your sex M/F:m
Your Id:504
Your sex:m
Your name:Reddy


Regards,
Uvaraja
Tagged:
Rakesh Yadav Dasari

Answers

  • EJP
    EJP Member Posts: 32,920 Gold Crown
    read() doesn't retrurn until you press the enter key, but the enter key remains buffered so when you call readLine() it is the next character read, so you read an empty line. Use readLine() for both.
    Rakesh Yadav Dasari
This discussion has been closed.