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



这个问题说,询问用户的"名字"one_answers"姓氏",然后显示消息Welcome和用户的全名。还要确保用户没有在只要求输入名字的第一个文本字段中输入他/她的全名我认为,如果用户在第一个文本字段中输入他/她的全名,我们可以从他/她是否输入了空格或("(这一事实中知道这一点。如果没有,我们可以简单地显示消息欢迎+全名。然而,它并没有像我想象的那样工作。。。有人能帮我在这里输入图像描述吗

如果我理解您的理解,下面的工作将通过忽略空格后的数据并询问用户的姓氏来完成您所需要的。

代码: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);

}

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

代码:公共类FirstNameLastName{

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

代码的问题是,检查每个字符,然后对每个字符执行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
}

最新更新