繁体   English   中英

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

[英]JAVA: multi-line input and separated by spaces

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

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

第一列仅指示列数。 id还希望能够获取第二列整数的总和(25000 + 1000 =?)

sample input
2
1 25000
2 1000

sample output
26000

尝试这个

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

你可以这样使用

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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