如何确保用户没有在名为 "First Name" 的第一个文本字段中输入 his/her 全名

How can I make sure that the user did not enter his/her entire name in the First Text Field named as "First Name"

这个问题说要求用户提供 'First Name' 和 'Last Name',然后显示带有用户全名的消息 Welcome 。还要确保用户没有在第一个仅要求输入名字的文本字段中输入 his/her 全名 我认为如果用户在第一个文本字段中输入 his/her 全名,我们可以从 he/she 输入 space 或 (' ') 或不输入的事实中知道。如果不是,我们可以简单地显示消息 Welcome + full name 。然而它并没有像我想象的那样工作......有人可以帮助我吗enter image description here

实际上有几种方法可以做到这一点,但如果我正确理解你的问题,下面是一个简单的方法,它来自 http://math.hws.edu/javanotes/c2/ex6-ans.html 并帮助我理解 Java 当我正在学习它,你会根据你的需要改变它。

代码: public class 名姓 {

public static void main(String[] args) {
    
    String input;     // The input line entered by the user.
    int space;        // The location of the space in the input.
    String firstName; // The first name, extracted from the input.
    String lastName;  // The last name, extracted from the input.
    
    System.out.println();
    System.out.println("Please enter your first name and last name, separated by a space.");
    System.out.print("? ");
    input = TextIO.getln();
    
    space = input.indexOf(' ');
    firstName = input.substring(0, space);
    lastName = input.substring(space+1);
    
    System.out.println("Your first name is " + firstName + ", which has "
                              + firstName.length() + " characters.");
    System.out.println("Your last name is " + lastName + ", which has "
                              + lastName.length() + " characters.");
    System.out.println("Your initials are " + firstName.charAt(0) + lastName.charAt(0));
    
}

}

编辑: 如果这没有意义,我可以用一个更好的例子和更多细节给出更好的解释。

关于类似问题的更多说明。 https://www.homeandlearn.co.uk/java/substring.html

如果我理解你的话,下面将通过忽略 space 之后的数据并询问用户的姓氏来完成你需要的。

代码: public static void main(String[] args) {

    // Properties
    Scanner keyboard = new Scanner(System.in);
    String firstName, lastName

    // Ask the user for their first name
    System.out.println("What is your first name? ");
    System.out.print("--> "); // this is for style and not needed
    firstName = keyboard.next();

    // Ask the user for their last name
    System.out.println("What is your last name? ");
    System.out.print("--> "); // this is for style and not needed
    lastName = keyboard.next();

    // Display the data
    System.out.println("Your first name is : " + firstName);
    System.out.println("Your last name is : " + lastName);


}

您的代码存在的问题是,您检查了每个字符,然后对每个字符执行 if/else。这意味着如果最后一个字符不是空格,它将在最后处理 else 树。

解决方法是只检查一次:

if(fn.contains(' '){
    //Do what you want to do, if both names were entered in the first field
}else{
    //Everything is fine
}