Java 计数子串,而不是循环
} 在这里,我需要打印用户输入的包含子字符串“Stir”的单词数。但是,我不确定如何让它工作,或者我是否一开始就做对了Java 计数子串,而不是循环,java,string,Java,String,} 在这里,我需要打印用户输入的包含子字符串“Stir”的单词数。但是,我不确定如何让它工作,或者我是否一开始就做对了 谢谢你的帮助 应该使用String.contains(“Stir”)而不是String.substring(0,4).equals(“Stir”) 如前所述,这种方法 当且仅当此字符串包含指定的 字符值的序列 String.contains(“Stir”) 将对您的情况有所帮助。在您的代码中,以下行:输入一个超过4个字符的单词,然后按q退出将在每次迭代中打印两次。另外,您使用了
谢谢你的帮助 应该使用
String.contains(“Stir”)
而不是String.substring(0,4).equals(“Stir”)
如前所述,这种方法
当且仅当此字符串包含指定的
字符值的序列
String.contains(“Stir”)
将对您的情况有所帮助。在您的代码中,以下行:
输入一个超过4个字符的单词,然后按q退出
将在每次迭代中打印两次。另外,您使用了错误的函数来检查字符串是否包含子字符串。您的一些if-else
语句需要更改。以下是代码的更好版本:
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();
}
}
}
请注意,在这种情况下,您被困在无限while循环中。为了在输入
q
时真正“退出”,您应该中断并从退出,而注意字符串.substring(0,4).equals(“Stir”)
等同于字符串.startsWith(“Stir”)
@assylias不,不是!第一个可以抛出IndexOutOfBoundsException
。
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