gpt4 book ai didi

Java - 方法的输出

转载 作者:行者123 更新时间:2023-12-02 00:23:22 24 4
gpt4 key购买 nike

查看这个特定方法的输出让我感到困惑。我试图准确地理解它在做什么。

方法是这样的:

for (int i = 0; i < 4; i ++) {
for (int j = 0; j < 9; j++) {
if (j==5) {
break;
}
if ((j==0) || (i==0)) {
continue;
}
if (!((j*i % 3) != 0)) {
System.out.println(j*i);
}
}

}

我知道输出是什么,但我仍然不确定它是如何工作的,这就是我在这里问的原因。因此,该方法将遍历 j 直到达到 5,然后中断。

然后它递增 i,j 为 0。 J != 5 所以它不会中断,j == 0 所以继续但随后 J 变为 3,而 I 变为 1。这就是我迷失的地方。 3从哪里来的?

我用它来打印幕后发生的事情

    public static void tester() {
for (int i = 0; i < 4; i ++) {
for (int j = 0; j < 9; j++) {
if (j==5) {
System.out.println("j == 5, breaking");
break;
}
if ((j==0) || (i==0)) {
System.out.println("J is " + j);
System.out.println("I is " + i);
System.out.println("j or i == 0, continuing");
continue;
}
if (!((j*i % 3) != 0)) {
System.out.println("J is " + j);
System.out.println("I is " + i);
System.out.println(j*i);
}
}
System.out.println();
}
}

输出如下:

J is 0

I is 0

j or i == 0, continuing

J is 1

I is 0

j or i == 0, continuing

J is 2

I is 0

j or i == 0, continuing

J is 3

I is 0

j or i == 0, continuing

J is 4

I is 0

j or i == 0, continuing

j == 5, breaking


J is 0

I is 1

j or i == 0, continuing

J is 3

I is 1

3

j == 5, breaking


J is 0

I is 2

j or i == 0, continuing

J is 3

I is 2

6

j == 5, breaking


J is 0

I is 3


j or i == 0, continuing

J is 1

I is 3

3

J is 2

I is 3

6

J is 3

I is 3

9

J is 4

I is 3

12

j == 5, breaking

最佳答案

3(以及后来的6)是从这段代码中出现的......

        if (!((j*i % 3) != 0)) {
System.out.println("J is " + j);
System.out.println("I is " + i);
System.out.println(j*i);
}

实际上,!((j*i % 3) != 0) 所说的是,当 j*i/3 的余数为 0 时,它运行此 if 语句中的代码。换句话说,只要 j*i3 的倍数(3, 6912)

逻辑很难理解 - 最好这样写......

        if ((j*i % 3) == 0) {
System.out.println("J is " + j);
System.out.println("I is " + i);
System.out.println(j*i);
}

在原来的方式中,所有的 ! 符号和多个方括号/大括号使得阅读变得困难。

关于Java - 方法的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10499800/

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