System.out.println("Enter an integer:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); num = br.read();
here br.read returns byte. so, a byte can read -126 to 127 values. u enter any value at system.in, u r trying to read only first byte in reader object. try to read whole line, then make it what u want. if u need integer then this may help u.
import java.io.*; class foobar { int num; public static void main (String arguments[]){ foobar fb = new foobar(); fb.enterFoobar(); } void enterFoobar(){ System.out.println("Enter an integer:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ String line = br.readLine(); num = Integer.parseInt(line); } catch(Exception e){ System.exit(1); }System.out.println(num); } }
Just on little remark (which has little to do with question). Make sure you define the variables outside the the scope of a loop (like shown in the code herebelow).
I am spending hours looking at code for code reviews. what I mention is not a code improvement & should be picked up by an Compiler doing simple optimization.
It's however a bad practice in my mind, as it's a proove that the people don't realize what is (really) going on !
import java.io.*;
class foobar
{
int num;
publicstaticvoid main (String arguments[])
{
foobar fb = new foobar();
fb.enterFoobar();
} // End of main
void enterFoobar ()
{
System.out.println("Enter an integer:");
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));
try
{
String line = null;
int num = -1;
do
{
line = br.readLine();
num = Integer.parseInt(line);
System.out.println(num);
} while (num != -1)
} catch(Exception e)
{
e.printStackTrace ();
System.exit(1);
}
} // End of enterFoobar
} // end of Class
Rgds,
Thomas SMETS, SCJP2 - Brussels
p.s. : As there was not loop, Venugopal 's code was dead correct ( & efficient ).