[英]How can I make sure that the user did not enter his/her entire name in the First Text Field named as "First Name"
這個問題說要求用戶提供“名字”和“姓氏”,然后顯示消息 Welcome with the full name 。 還要確保用戶沒有在第一個只要求輸入名字的文本字段中輸入他/她的全名我認為如果用戶在第一個文本字段中輸入他/她的全名,我們可以從事實中知道他/她輸入了空格或 (' ') 與否。 如果沒有,我們可以簡單地顯示消息 Welcome + full name 。 然而,它並沒有像我想象的那樣工作......有人可以幫我在這里輸入圖片描述嗎
如果我理解你,下面將通過忽略空格后的數據並詢問用戶他們的姓氏來完成你需要的工作。
代碼: 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 時更了解它,您只需根據需要對其進行更改即可。
代碼:公共類名字姓氏{
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.