user10949703
user10949703

Reputation:

Is there a way you can get two Scanner input(integers) without going to the next line?

I am working on grade calculator and I intend to get marks scored and the maximum marks. I need to use Scanner such that, if the number of tests taken is two it will prompt the user to enter the score and the maximum score on the same line. After that it goes to the next line and asks the user to input score as well as maximum score. It thereafter finds the sum of score and the sum of maximum score separately.

enter image description here

Upvotes: 0

Views: 154

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48610

You can queue-up integer values on the same line by using scan.nextInt(). It will wait until it reads two integers, either separated by spaces or new-lines.

import java.util.Scanner;

public class ScanTest {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter grade(s): ");
        int score = scan.nextInt();
        int maxScore = scan.nextInt();
        scan.nextLine();

        System.out.printf("Score: %d, Max: %d%n", score, maxScore);

        scan.close(); // Close scanner.
    }
}

Upvotes: 4

Related Questions