JAVA:多行输入并用空格分隔

问题描述 投票:0回答:2

编程新手,你们能告诉我在java中进行多行输入的最佳方法吗?这样的一点点。

程序1st询问用户案例数。然后要求用户输入由空格分隔的2个整数。

第1列仅表示列数。 id也喜欢能够获得第二列整数的总和(25000 + 1000 =?)

sample input
2
1 25000
2 1000

sample output
26000
java arrays multidimensional-array
2个回答
1
投票

试试这个

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

你可以尝试

sample input
2
1 25000
2 1000

sample output
26000

0
投票

你可以使用这样的东西,

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

}
© www.soinside.com 2019 - 2024. All rights reserved.