gpt4 book ai didi

java - while 语句和 if 语句

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

我从 Oracle 的 Java 教程中获得了下面的代码,它工作得很好。

我了解 for-、while 循环和 if 语句的工作原理,但是,我很难理解 下面的 whileif 语句。

为什么下面的 while 和 if 语句中的一切都是原样?

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) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}

解释

While Statement

1.) n--(首先使用n,然后递减)!= 0,一直循环直到 n 达到 0

2.) 直到n不等于0,一直进入while循环内部

3.) 一旦进入 while 循环 ,它就会验证 if 条件

If Statement

if (searchMe.charAt(j++) != substring.charAt(k++))

searchMe.charAt(j++)//searchMe Stringj++ 位置的字符

substring.charAt(k++)//substring Stringk++ 位置的字符

If 语句 实际上匹配两个字符串中给定位置的字符

例如。

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

在任何给定实例中,j = 3, k= 1

searchMe.charAt(4)//返回字符k,记住索引从0

开始

substring.charAt(1)//返回字符u,记住索引从0

开始

如果这样比较的话,

if('k' != 'u')

关于java - while 语句和 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33931837/

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