我是Java的新手,在打印两个独立的阵列时遇到问题。我定义了一个长度为3的int数组和一个长度相同的第二个数组,它由第一个数组除以数字19的余数填充。第一个数组存储随机生成的值。这是我的代码:
import java.util.Random;
public class Hashing {
public static void main(String[] args) {
int[] array = new int[3];
Random generator = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = generator.nextInt(80);
int[] newarray = new int[3];
for (int j = 0; j < newarray.length; j++) {
newarray[j] = array[i] % 19;
System.out.println("array= " + array[i]);
System.out.println("residuals=" + array[j]);
System.out.println("\n");
}
}
}
}
此代码有问题。我想要的是这个;
array[0]
array[1]
array[2]
然后
residuals[0]
residuals[1]
residuals[2]
但结果如下:
array[0]
residuals[0]
array[1]
residuals[1]
array[2]
residuals[2]
我该怎么纠正这个?我尝试通过进行以下修改来纠正打印
import java.util.Random;
public class Hashing {
public static void main(String[] args) {
int[] array = new int[2];
Random generator = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = generator.nextInt(80);
System.out.println("array= " + array[i]);
System.out.println("\n");
}
int[] newarray = new int[2];enter code here
for (int j = 0; j < newarray.length; j++) {
newarray[j] = array[i] % 19;
System.out.println("residuals=" + array[j]);
System.out.println("\n");
}
}
}
但这次我在这部分中遇到错误:
newarray[j] = array[i] % 19;
它说它无法解析为变量。然而,它已经在上面的循环中定义:(有人可以帮我一把吗?谢谢
答案 0 :(得分:1)
打印一个数组,然后打印另一个
for (int j = 0; j < newarray.length; j++) {
newarray[j] = array[i] % 19;
System.out.println("array= " + array[i]);
System.out.println("\n");
}
for (int j = 0; j < newarray.length; j++) {
System.out.println("residuals=" + array[j]);
System.out.println("\n");
}
答案 1 :(得分:0)
import java.util.Random;
public class Hashing {
public static void main(String[] args) {
int[] array = new int[3];
Random generator = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = generator.nextInt(80);
System.out.println("array= " + array[i]);
}
System.out.print("\n");
int[] newarray = new int[3];
for (int j = 0; j < newarray.length; j++) {
newarray[j] = array[j] % 19;
System.out.println("residuals=" + newarray[j]);
}
}
}
答案 2 :(得分:0)
请尝试以下代码:
import java.util.Random;
public class Hashing {
public static void main(String[] args) {
int[] array = new int[3];
Random generator = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = generator.nextInt(80);
int[] newarray = new int[3];
newarray[i] = array[i] % 19;
for (int j = 0; j < newarray.length; j++) {
System.out.println("array= " + array[i]);
}
System.out.println("");
for (int j = 0; j < newarray.length; j++) {
System.out.println("residuals=" + array[j]);
}
System.out.println("");
}
}
}
我希望这就是你要找的东西。