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