gpt4 book ai didi

java - while (n-- != 0){} 在此代码中做了什么?

转载 作者:行者123 更新时间:2023-11-29 03:00:31 25 4
gpt4 key购买 nike

在下面的代码中,这一行翻译成什么?

while (n-- != 0){}?如果我没有误认为 n 是 18,当 searchMe 的长度从子字符串的长度中扣除时,那么这一行是否表示当 18 递减 (17) 不等于 0 时进行搜索?

class ContinueWithLabelDemo {
public static void main(String[] args) {

String searchMe = "Look for a substring in me";

String substring = "sub";
boolean foundIt = false;

int max = searchMe.length() -
substring.length();


test:
for (int i = 0; i <= max; i++) {

int n = substring.length();

int j = i;

int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}

最佳答案

while (n-- != 0) { // checks  (n != 0) then n = n-1;
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}

这个 n-- 将执行后递减,首先它会检查条件,然后它将 n 的值减 1。

假设n的值为10。那么首先它会检查条件,
if(10 != 0) 之后它将减少到 9。

关于java - while (n-- != 0){} 在此代码中做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35283292/

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