Multiple User Inputs Problem
Stupid question from a new programmer, but bear with me. I'm trying to get this program to work:
import java.io.*;
public class ReadTest {
public static void main(String[] args) throws IOException {
byte[] one = new byte[1];
byte[] two = new byte[1];
System.in.read(one);
System.in.read(two);
System.out.println(one[0] + two[0]);
}
}
The user is supposed to enter a number, hit return, enter another number, and hit return. The output is the sum of the two numbers. The problem is that I can't get it to accept the second number. I type in the first number and the program terminates. I'm guessing I need to clear the input buffer or something like that, but how?
[739 byte] By [
Mr_Effa] at [2007-10-2 6:08:29]

read(byte[]) doesn't do what you think it does.You need to read strings, and convert the strings into integers (or longs, or whatever the maximum size of numbers you're designing for). Or use the Scanner class to help you out.
Even if I use strings, it doesn't work. If I use
import java.io.*;
public class ReadTest {
public static void main(String[] args) throws IOException {
byte[] array1 = new byte[1];
byte[] array2 = new byte[2];
System.in.read(array1);
String string1 = new String(array1);
System.in.read(array2);
String string2 = new String(array2);
System.out.println(Integer.parseInt(string1.trim()) + Integer.parseInt(string2.trim()));
}
}
This throws an exception because no int value is ever put into string2 because it never lets me enter it. I don't care what the output is, I just want a program that accepts two inputs. The scanner class works, but I'd rather know what the problem is with the code I've got.