问题描述
此问题说,向用户询问“名字”和“姓氏”,然后显示消息“ Welcome”以及用户的全名。还请确保用户没有在仅要求输入名字的第一个文本字段中输入他/她的全名 我认为,如果用户在第一个文本字段中输入他/她的全名,我们可以从他/她是否输入空格或('')的事实中得知这一点。如果不是,我们可以简单地显示“欢迎+全名”消息。但是,它并没有按照我认为的那样工作。有人可以帮我解决这个问题enter image description here
解决方法
实际上有几种方法可以执行此操作,但是如果我能正确理解您的问题,那么下面是一种简单的方法,该方法来自http://math.hws.edu/javanotes/c2/ex6-ans.html,可以帮助我在学习Java的同时更加了解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
,如果我理解您的意思,那么以下内容将通过忽略空格后面的数据并询问用户的姓氏来满足您的要求。
代码: 公共静态无效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
}