【问题标题】:JAVA: multi-line input and separated by spacesJAVA:多行输入并用空格分隔
【发布时间】:2018-11-21 17:18:19
【问题描述】:

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

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

第一列仅表示列数。 id也希望能够得到第2列整数的总和(25000+1000=?)

sample input
2
1 25000
2 1000

sample output
26000

【问题讨论】:

  • 创建一个 Scanner,读取一个 int,循环直到给定的 int,每次迭代都接受一个 int,然后将该 int 添加到总和中。循环结束后,打印总和

标签: java arrays multidimensional-array


【解决方案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

【讨论】:

    【解决方案2】:

    你可以使用这样的东西,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-17
      • 2021-06-12
      • 2015-03-08
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2016-03-12
      相关资源
      最近更新 更多