问题是:读取表格中给出的一组数字,并显示总数。 (添加行和列) 这是我到目前为止所拥有的。我需要有关如何获得正确输出的指导。提前致谢。
*不想使用数组。
import java.util.Scanner;
public class tableintegers {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Give the number of rows and number of columns: ");
int rows=input.nextInt();
int cols=input.nextInt();
int total=0, sum=0, numbers=0;
for(int i=0;i<rows; i++) {
if (rows>i) {
System.out.print("Enter row " +(i+1)+ ":");
numbers=input.nextInt();
input.nextInt();
}
sum+=numbers;
total=sum+numbers;
}
System.out.println("The grand total is: " +total);
}
}
最佳答案
下面的程序将要求用户首先分别插入行数和列数。接下来,使用嵌套的 for 循环要求用户在每行中插入每列的值。
第一个 For 循环迭代行数。对于每次迭代,第二个 For 循环将迭代输入的列数。因此要求用户为每列输入一个值。
每行输入的值的总和将由 sumOfRow 计算。最后,这些值将相加并显示最终总计。
希望这有帮助:)
import java.util.Scanner;
public class tableintegers {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Enter the number of rows:");
int rows=input.nextInt();
System.out.print("Enter the number of columns:");
int cols=input.nextInt();
int total=0, sumOfRow=0, numbers=0;
for(int i=0; i<rows; i++) {
sumOfRow = 0;
System.out.println("\nRow No. " + (i + 1) );
for(int j=0; j<cols; j++) {
System.out.print("Enter value for Column " + (j+1) + ": ");
numbers = input.nextInt();
sumOfRow += numbers;
}
System.out.println("Sum of Row No. " + (i+1) + " Values: " + sumOfRow);
total += sumOfRow;
}
System.out.println("\nThe grand total is: " +total);
}
}
关于java - 需要帮助嵌套 for 循环来添加 java 中表中的所有行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58780577/