【问题标题】:Java print multiple lines after reading multiple linesJava在读取多行后打印多行
【发布时间】:2017-12-05 03:26:57
【问题描述】:

(这是我的家庭作业。所以我无法对任务进行任何更改,例如更改输入规则。)

我需要计算

a^m mod n 

并打印出结果。 (我已经想出了如何编写计算代码。)

但问题说会有多行输入:

IN:

12 5 47
2 4 89
29 5 54

并且需要在读取所有输入行后将所有结果一起打印。 (不能在输入一行后立即打印结果。)

OUT:

14
16
5

到目前为止我尝试过的代码:

import java.util.Scanner;

public class mod {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int count = 0;
        while (input.hasNextLine()){
            count++;
        }
        int[] array = new int[count];
        for (int i = 0; i < count; i ++){  
            int a = input.nextInt();
            int m = input.nextInt();
            int n = input.nextInt();
            int result = (int)((Math.pow(a, m)) % n);
            array[i] = result;
        }
        for (int x : array){
             System.out.println(x);
        }
    }
}

我尝试计算输入的行数并构建一个该大小的数组来存储结果。

但我的代码似乎无法检测到输入的结束并继续循环。

【问题讨论】:

  • 您需要在第一个循环中读取每一行并在该行上执行计算并输出结果,否则,您需要关闭并重新打开文件,然后再尝试再次读取它跨度>
  • 检查我的答案和解释。
  • 如何知道用户何时完成输入?
  • @MadProgrammer 谢谢!但任务要求我只在阅读所有行后输出结果。
  • @D M 是的,这是我的问题。我认为用户通过按“输入”键完成了输入。但我不确定如何检测到这一点。

标签: java loops input line


【解决方案1】:

您可以使用List&lt;String&gt; 将用户的输入存储在初始循环中,我建议在空的String 上终止循环并仅添加与由空格字符分隔的三个数字匹配的行。另外,我会在第二个循环中打印结果。那么你不需要结果array。我也更喜欢格式化的io(即System.out.printf)。喜欢,

Scanner input = new Scanner(System.in);
List<String> lines = new ArrayList<>();
while (input.hasNextLine()) {
    String line = input.nextLine();
    if (line.isEmpty()) {
        break;
    } else if (line.matches("\\d+\\s+\\d+\\s+\\d+")) {
        lines.add(line);
    }
}
int count = lines.size();
for (int i = 0; i < count; i++) {
    String[] tokens = lines.get(i).split("\\s+");
    int a = Integer.parseInt(tokens[0]), m = Integer.parseInt(tokens[1]), 
            n = Integer.parseInt(tokens[2]);
    int result = (int) ((Math.pow(a, m)) % n);
    System.out.printf("(%d ^ %d) %% %d = %d%n", a, m, n, result);
}

我使用您提供的输入进行了测试,

12 5 47
2 4 89
29 5 54

(12 ^ 5) % 47 = 14
(2 ^ 4) % 89 = 16
(29 ^ 5) % 54 = 5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-05
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 2020-09-03
    • 2013-12-08
    相关资源
    最近更新 更多