To do this, we could read in the user’s input String by wrapping an InputStreamReader object in a BufferedReader object.
Then, we use the readLine() method of the BufferedReader to read the input String – say, two integers separated by a space character. These can be parsed into two separate Strings using the String.split() method, and then their values may be assigned to a and b, using the parseInt method as you suggest above.
(We would likely want to verify the user input as well to ensure it is in the desired format, but that issue hasn’t been addressed here.)
First, remember to import java.io 58.* for the Reader objects. The readLine() method throws an IOException, so the Main method can go like this:
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(
new InputStreamReader(
System.in));
String[] input = new String[2];
int a;
int b;
System.out.print("Please enter two integers: ");
input = in.readLine().split(" ");
a = Integer.parseInt(input[0]);
b = Integer.parseInt(input[1]);
System.out.println("You input: " + a + " and " + b);
}
------------- ADDITIONAL INFO --------------
I forgot about the Scanner object. This can make things a lot simpler. Instead of importing the Reader objects, we import java.util.Scanner
The Scanner object can parse user input directly, so we don’t have to split Strings or use parseInt. Also, we don’t necessarily need to worry about catching an IOException. And, the user may input both integers on the same line, or even on different lines, as desired.
Using the Scanner object, our much simpler main function can go like this:
public static void main(String[] args)
{
System.out.print("Please enter two integers: ");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("You input: " + a + " and " + b);
}