子字符串方法,用于标识字符串值中的字符值



我在使用子字符串方法查找字符串变量中的特定字符时遇到问题。目前,我有一个for循环设置来循环名为name的字符串变量的长度。然后,我在if语句中使用substring方法来查找我的特定字符,在本例中它是一个"."

我不能让这个工作,将感谢任何帮助。谢谢你。

System.out.println("nEnter name: ");
String name = in.nextLine();
int length = name.length();
for (int x = 0; x < length; x++) {

if(name.substring(x,x+1).equals(".")) {

System.out.println("Error! - name can not contain (.) valuesn"
+ "***************************************************");

System.out.println("nWould you like to capture another name?" +
"nEnter (1) to continue or any other key to exit");
String opt1 = in.nextLine();
// If statement to run application from the start 
if (opt1.equals("1")) {

System.out.println("menu launch");
}
else { System.exit(0); }
}            
else { break; } 
}

别白费力气了。不需要循环遍历字符串的字符,您可以使用contains方法:

if (name.contains(".")) {
// logic comes here...

虽然Mureinik在实现目标的最佳方式上是正确的,但您的功能不起作用的原因是您的else { break; }语句。

break终止循环,因此除非第一个字符是.,否则循环将在第一次迭代后立即退出。当您想要增加循环时,正确的关键字是continue,尽管在这种情况下没有必要这样做,因为所有的逻辑都包含在if语句中。因为没有其他逻辑需要避免,所以应该删除else语句。