Mk Berou
Mk Berou

Reputation: 11

Java: How to have two or more inputs in one line in the console

I am new to java and I wrote a Basic Input/Output program and in this program I want the user to provide 3 different inputs and be saved in 3 different variables, they are two int and one char.

public static void ForTesting() {
    Scanner newScanTest = new Scanner(System.in);
    ٍٍٍٍٍٍٍٍٍٍٍSystem.out.print("Please type two numbers: ");
    int numberOne = newScanTest.nextInt();
    int numberTwo = newScanTest.nextInt();
    System.out.println("First Nr.: " + numberOne + " Second Nr.: " + numberTwo);
}

In the consol

What I get:

Please type two number: 4

5

First Nr.: 4 Second Nr.: 5


What I want:

Please type two number: 4 5

First Nr.: 4 Second Nr.: 5

(The bold numbers are the user input)

Upvotes: 0

Views: 4533

Answers (3)

cameron1024
cameron1024

Reputation: 10136

nextLine(), as the name suggests, reads a single line. If both numbers are contained on this single line, you should read both integers from that line. For example:

Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();  // reads the single input line from the console
String[] strings = line.split(" ");  // splits the string wherever a space character is encountered, returns the result as a String[]
int first = Integer.parseInt(strings[0]);
int second = Integer.parseInt(strings[1]);
System.out.println("First number = " + first + ", second number = " + second + ".");

Note, this will fail if you don't provide 2 integers in the input.

Upvotes: 2

psi
psi

Reputation: 269

If you are very sure about input like (2+2) or (2-2) or (2*2) or (2/2) below should work -

Scanner scanner = new Scanner(System.in);
Integer first = scanner.nextInt();
String operator = scanner.next();
Integer second = scanner.nextInt();
System.out.println("First number = " + first + ", second number = " + second + ".");

Upvotes: 0

frianH
frianH

Reputation: 7563

Please try the bellow code, i try to convert integers to strings.

public static void ForTesting() {
    Scanner newScanTest = new Scanner(System.in);
    ٍٍٍٍٍٍٍٍٍٍٍSystem.out.print("Please type two numbers: ");
    int number = newScanTest.nextInt();
    int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
    int secondDigit = Integer.parseInt(Integer.toString(number).substring(1, 2));
    System.out.println("First Nr.: " + firstDigit + " Second Nr.: " + secondDigit);
}

Upvotes: 0

Related Questions