gpt4 book ai didi

Java for 循环在第二个条件中使用相等运算符

转载 作者:行者123 更新时间:2023-11-29 09:59:01 26 4
gpt4 key购买 nike

我正在尝试以相反的顺序打印一个数组。

代码如下:

import java.util.Scanner;

public class Main {

public static void main(String []argh) {

Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();

}

for (int j = n-1 ; j == 0; j--) {
System.out.print(arr[j] + " ");
}
in.close();
}
}

在这段代码中什么也没发生,但是当我将第二个 for 循环中的第二个条件从 j == 0 更改为 j >=0 时,它起作用了。我不明白为什么。在 j==0 中,不是应该递减 j 直到它等于 0 吗?

最佳答案

for (int j = n-1 ; j == 0; j--) 表示只要 j 等于 就会执行循环>0。由于 j 被初始化为 n-1,因此循环永远不会执行(假设 n != 1)。

关于Java for 循环在第二个条件中使用相等运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48765910/

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