【发布时间】:2014-11-27 08:27:19
【问题描述】:
我正在编写这个程序,其中用户输入表格的维度,然后使用这些维度创建一个表格,其中的元素由具有 0 到 9 整数的随机生成器确定。然后,我需要什么要做的是创建一个循环来确定表中是否有四个连续的偶数。
2 5 8 7 1
3 2 9 4 7
5 1 2 0 3
8 0 1 2 7
在该表中,两个从第一个位置沿对角线连续出现。也可以是这样的:
9 5 3 7 0
2 5 7 3 1
8 5 0 2 9
4 5 1 7 5
在此表中,五个从第二个位置垂直向下显示。
这是我到目前为止所做的:
public class FourConsecutiveNumbers {
public static void main(String[] args) {
Scanner rowDimension = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int firstInput = rowDimension.nextInt();
Scanner columnDimension = new Scanner(System.in);
System.out.print("Enter the number of columns: ");
int secondInput = columnDimension.nextInt();
int[][] randomTable = new int[firstInput][secondInput];
for (int row = 0; row < firstInput; row++) {
for (int column = 0; column < secondInput; column++) {
randomTable[row][column] = (int)(Math.random() * 10 + 0);
System.out.print(randomTable[row][column] + " ");
}
System.out.println();
}
}
}
我知道这并不多,我只创建了两个扫描仪和桌子。我不知道如何去创建循环来确定四个连续的偶数。当我想到它时,我想知道这样做的方法是否是创建一个嵌套循环来检查第一行然后是第一列,然后确定该行或列中的任何一个是否包含相同的整数四次。然后根据用户输入的尺寸重复此操作。不过我不确定……
我知道这是主要的想法:
if there is x number that repeats consecutively four times in a row, then return true; else false
if there is x number that repeats consecutively four times in a column, then return true; else false
if there is x number that repeats consecutively four times in surrounding corner, then return true; else false.
现在,这只是要参考的伪代码,但我对如何做到这一点感到非常困惑,希望其他人提供一些意见。
【问题讨论】:
-
伪代码中是否有任何特定的部分让您感到困惑?
-
@CBredlow 不,我知道代码的想法是什么;如何实现这让我很头疼。
-
如果你必须在没有电脑的情况下自己做,你会怎么做?从第一部分开始(连续四次)。假设您必须通过某种目镜查看并且一次只能查看阵列中的一个数字(这样您就不会“发现”四个数字并排在一起)。你必须想出某种方法来解决这个问题——它会是什么?我想一旦你弄清楚了,你所要做的就是将你的想法转化为代码,这是你应该能够做到的。
-
P.S. “偶数”数是可被 2 整除的数(2、4、6、8,...) .
-
最好的方法是坐下来在一张纸上写出一个二维数组,然后查看伪代码,然后在脑海中计算,写下所有步骤您确实遵循了该代码。这将导致正确的算法。从那里您可以继续编写代码。