gpt4 book ai didi

java - 计算子字符串,while循环

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

public class SubstringCount
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a word longer than 4 characters, and press q to quit");
int count = 0;


while (scan.hasNextLine())
{
System.out.println("Enter a word longer than 4 characters, and press q to quit");
String word = scan.next();

if (word.substring(0,4).equals("Stir"))
{
count++;
System.out.println("Enter a word longer than 4 characters, and press q to quit");
scan.next();
}

else if (word.equals("q"))
{
System.out.println("You have " + count + ("words with 'Stir' in them"));
}

else if (!word.substring(0,4).equals("Stir"))
{
System.out.println("Enter a word longer than 4 characters, and press q to quit");
scan.next();
}
}
}

}

这里我需要打印用户输入的有多少个单词包含子字符串“Stir”。但是我不确定如何让它发挥作用,或者我是否一开始就做对了!

感谢您的帮助!

最佳答案

在您的代码中,以下行:输入长度超过 4 个字符的单词,然后按 q 退出 将在每次迭代中打印两次。另外,您使用了错误的函数来检查字符串是否包含子字符串。您的一些 if-else 语句需要更改。这是您的代码的更好版本:

import java.util.Scanner;

public class SubstringCount
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a word longer than 4 characters, and press q to quit");
int count = 0;
while (scan.hasNextLine())
{
String word = scan.next();
if (word.contains("Stir"))
{
System.out.println("Enter a word longer than 4 characters, and press q to quit");
count++;
}
else if (word.equals("q"))
{
System.out.println("You have " + count + ( "words with 'Stir' in them"));
System.out.println("Enter a word longer than 4 characters, and press q to quit");
}
else
{
System.out.println("Enter a word longer than 4 characters, and press q to quit");
}
} //end of while
} //end of main
} //end of class

请注意,在这种情况下,您陷入了无限 while 循环。为了在输入q时真正“退出”,您应该break并从while中退出。

关于java - 计算子字符串,while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13503421/

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