我正在使用具有2个元素的数组(具体来说是new int [10] [2],我不知道如何将第0列除以每一行的第1列。
例如:第5行c0 [20] c1 [2] =程序应将其解释为20÷2,然后将答案输出为每行10。我的程序当前没有这样做。我要去哪里错了?
import java.util.Scanner;
public class 2darraydivision {
public static void main(String[] args) {
int[][] a = getArray();
System.out.print("");
for (int i = 0; i < a.length; i++) {
System.out.printf("\nStudent %d needs ", i + 1);
System.out.printf(sum(a) + " terms to graduate.");
}
System.out.println("\n\nData captured from user:");
for (int row = 0; row < a.length; row++) {
for (int column = 0; column < a[row].length; column++) {
System.out.print(a[row][column] + " ");
}
System.out.println();
}
}
public static int[][] getArray() {
int[][] b = new int[10][2];
java.util.Scanner input = new Scanner(System.in);
System.out.print("Enter classes remaining and taking each term for...\n");
for (int i = 0; i < b.length; i++) {
System.out.printf("Student %d: ", i + 1);
for (int j = 0; j < b[i].length; j++) {
b[i][j] = input.nextInt();
if ((b[j][0] < 1) || (b[j][0] > 20)) {
System.out.println("Please enter number of courses remaining between 1 and 20.");
} else if ((b[j][1] < 1) || (b[j][1] > 5)) {
System.out.println("Please enter number of courses taking between 1 and 5.");
}
}
}
input.close();
return b;
}
public static int sum(int[][] b) {
int total = 0;
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[j].length; j++) {
total = b[j][0] / b[j][1];
}
}
return total;
}
}
您说:
如何将第0列划分为每行的第1列
您说:
每行输出答案为10
似乎您的方法sum
是您尝试执行的操作,所以让我们看一下。
public static int sum(int[][] b) {
int total = 0;
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[j].length; j++) {
total = b[j][0] / b[j][1];
}
}
return total;
}
问题:
“每行”
如果要处理每一行,则需要一个循环,但是有两个嵌套循环,为什么?
删除j
循环。
“如何将列0划分为列1”
您正在执行此操作,除了将j
替换为i
,因为我们只是取消了j
循环。
int result = b[i][0] / b[i][1];
“输出答案”
这意味着要打印它,所以println
语句可能是适当的。
全部,也就是说:
// Using regular for loop
public static void divideAndPrint(int[][] b) {
for (int i = 0; i < b.length; i++) {
System.out.println(b[i][0] / b[i][1]);
}
}
// Using enhanced for loop
public static void divideAndPrint(int[][] b) {
for (int[] row : b) {
System.out.println(row[0] / row[1]);
}
}
// Using Java 8+ lambda:
public static void divideAndPrint(int[][] b) {
Arrays.asList(b).forEach(row -> System.out.println(row[0] / row[1]));
}
// Using Java 8+ streams:
public static void divideAndPrint(int[][] b) {
Arrays.stream(b).mapToInt(r -> r[0] / r[1]).forEachOrdered(System.out::println);
}