gpt4 book ai didi

java - 如何修复我的 java 方法以正确迭代字符串?

转载 作者:行者123 更新时间:2023-12-02 01:50:58 28 4
gpt4 key购买 nike

我需要一些重大帮助。

我的任务是识别小写字符串并返回 true 或 false 语句,尽管存在其他字符或单词。到目前为止,我能够识别全小写的字符串,但如果单词全大写,我的代码仍然返回 TRUE 值;我只希望它识别小写值。

任务:编写一个程序,接受一个字符串行,如果我的名字(“john”)的字母以相同的顺序出现在字符串中(全部为小写),则打印 true。请注意,我的名字的字母之间可能还有其他字符。

这是我的代码:

import java.util.Scanner;

class Main {

public static void main(String[] args) {
boolean output = Check();
if (output == true) {
System.out.println("true");
}

else if (output == false) {
System.out.println("false");
}
}

public static boolean Check() {
String random;
Scanner sc = new Scanner(System.in);
random = sc.nextLine();
String word = "john";

for (int i = 0; i < word.length(); i++) {
if (random.contains(word.substring((i)))) {
return true;
}
}
if (random.contains("JOHN")) {
return false;
}
return false;
}
}

任何帮助将非常感谢。一些示例输出:

示例输入 1:你好约翰示例输出 1:错误

示例输入 2:j123o23h56n示例输出 2:正确

示例输入 3:约翰示例输出 3:正确

示例输入 4:浩金示例输出 4:错误

示例输入 5:J2j#@oh123$NNNnn示例输出 5:正确

最佳答案

您需要编写一个逻辑,从“john”字符串中选取每个字符并按顺序进行比较,无论它们是否全部按该顺序出现。当它发现输入字符串中找到所有字符时,它立即返回 true,而不需要进一步扫描输入字符串。你可以写这样的东西,

public static boolean Check() {
String random;
Scanner sc = new Scanner(System.in);
random = sc.nextLine();
String word = "john";
sc.close();

int findIndex = 0;
char findChar = word.charAt(findIndex);
for (char c : random.toCharArray()) {
if (findChar == c) {
findIndex++;
if (findIndex == word.length()) {
return true;
}
findChar = word.charAt(findIndex);
}
}
return false;
}

关于java - 如何修复我的 java 方法以正确迭代字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52995197/

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