(这是我的家庭作业。因此,我无法对任务进行任何更改,例如更改输入规则。)
我需要计算
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