这里是新的 Java 开发人员,已经研究了一个星期并决定亲自动手。
我一直在尝试创建一个应用程序,用户可以在其中注册帐户。我现在处于用户必须输入全名的部分,并且程序必须确保名称之间有空格,否则它应该告诉用户重新输入带有空格的名称。
目前,我尝试设置一个 while 循环,并在 indexOf 条件 <=0(这意味着没有空间)时重复它。但是,我不确定一旦用户成功输入带有空格的名称,我将如何使其继续。
我当前的代码如下:
public static void companyEmail() {
System.out.println("+--------------------------------+");
System.out.println("| Company Email Registration |");
System.out.println("+--------------------------------+");
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter your full name: ");
String input = scanner.nextLine();
while (input.indexOf(' ') <=0) {
System.out.println("Please retype your full name with a space: ");
String secondInput = scanner.nextLine();
if(secondInput.indexOf(' ') <=0) {
break;
}
System.out.println("Program has worked");
}
}
感谢所有帮助。
谢谢。
最佳答案
您需要调用input.indexOf(' ') < 0
,因为第一个字符索引是 0
。
并且当secondInput
时您没有打破循环包含空格。
您只需使用一个字符串即可实现此目的:
while (input.indexOf(' ') < 0) {
System.out.println("Please retype your full name with a space: ");
input = scanner.nextLine();
}
System.out.println("Program has worked");
关于java - While 循环查找空格字符 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51156832/