代码之家  ›  专栏  ›  技术社区  ›  V.Liang

Java在读取多行后打印多行

  •  0
  • V.Liang  · 技术社区  · 7 年前

    (这是我的家庭作业。所以我不能像更改输入规则那样对任务进行任何更改。)

    我需要计算一下

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

    我试图数一数输入行,并构建一个这样大小的数组来存储结果。

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Elliott Frisch    7 年前

    您可以使用 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