简体   繁体   中英

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:

First Nr.: 4 Second Nr.: 5


What I want:

Please type two number:

First Nr.: 4 Second Nr.: 5

(The bold numbers are the user input)

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.

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);
}

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 + ".");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM