繁体   English   中英

Java读取多行后打印多行

[英]Java print multiple lines after reading multiple lines

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

我需要计算

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

我试图计算输入行数,并构建一个具有该大小的数组以存储结果。

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

您可以使用List<String>将用户输入的内容存储在初始循环中,我建议在一个空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

暂无
暂无

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

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