gpt4 book ai didi

java - 数组不会通过 for 循环到达下一个位置

转载 作者:行者123 更新时间:2023-12-01 18:56:09 24 4
gpt4 key购买 nike

这是我的代码:

ArrayFunHouseTwo

public class ArrayFunHouseTwo
{
//goingUp() will return true if all numbers
//in numArray are in increasing order
//[1,2,6,9,23] returns true
//[9, 11, 13, 8] returns false
public static boolean goingUp(int[] numArray)
{
int num = 0;
int numMinus = 0;
for(int x = 1; x < numArray.length; x++){
System.out.println(x);
num = numArray[x];
numMinus = numArray[x-1];

if(num > numMinus){
return true;
}

}
return false;
}

以及关联的运行器类:

import java.util.Arrays;

public class Lab14b
{
public static void main( String args[] )
{
int[] one = {1,2,3,4,5,6,7,8,9,10};
int[] two = {1,2,3,9,11,20,30};
//add more test cases
//int[] three = {9,8,7,6,5,4,3,2,0,-2};
//int[] four = {3,6,9,12,15,18,21,23,19,17,15,13,11,10,9,6,3,2,1,0};

System.out.println(Arrays.toString(one));
System.out.println("is going Up ? " + ArrayFunHouseTwo.goingUp(one));
System.out.println(Arrays.toString(two));
System.out.println("is going Up ? " + ArrayFunHouseTwo.goingUp(two));
//add more test cases
//System.out.println(Arrays.toString(three));
//System.out.println("is going Up ? " + ArrayFunHouseTwo.goingUp(three));
//System.out.println(Arrays.toString(four));
//System.out.println("is going Up ? " + ArrayFunHouseTwo.goingUp(four));

我希望它打印出来,从而证明它正在读取整个数组,但它读取的唯一数组是第三个数组,它将打印位置 x 处的所有值或 x 的值,取决于我如何编写 println() 语句

最佳答案

if(num > numMinus){
return true;
}

这意味着一旦发现一个数字大于之前的数字,就会终止循环。此时您想要做的事情是这样的。

...
if(num <= numMinus){
return false;
}
}
return true;
}

编辑:将条件修复为 <=基本上,您检查连续的数字,如果数字相等或递减,则将标志设置为 false(实际上此时您可以返回 false)

关于java - 数组不会通过 for 循环到达下一个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13871774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com