J. Doe
J. Doe

Reputation: 19

JAVA: multi-line input and separated by spaces

new to programming, can you guys show me the best method in doing a multi line input in java? a little something like this.

the program 1st asks the user the number of cases. then asks the user to input 2 integers separated by a space.

the 1st column just indicates the column count. id also like to be able to get the sum of the 2nd column of integers (25000+1000=?)

sample input
2
1 25000
2 1000

sample output
26000

Upvotes: 0

Views: 1598

Answers (2)

elbraulio
elbraulio

Reputation: 994

try this

import java.util.Scanner;

public class Launcher {

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            int inputs = scanner.nextInt();
            int sum = 0;
            while (inputs-- > 0) {
                // input 1 2500 in one line is read as two different inputs
                int row = scanner.nextInt();
                int value = scanner.nextInt();
                sum += value;
            }
            System.out.println(sum);
        }
    }
}

the you can try

sample input
2
1 25000
2 1000

sample output
26000

Upvotes: 1

Sandeepa
Sandeepa

Reputation: 3755

You can use something like this,

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int rows = new Integer(scanner.nextLine());
        int sum = 0;

        for (int i = 0; i < rows; i++) {
            sum = sum + new Integer(scanner.nextLine().split(" ")[1]);
        }

        System.out.println(sum);
    }

}

Upvotes: 0

Related Questions