你應該居然還要檢查,看看是否輸入的字符串的長度相等(以下如果需要,可以縮短檢查大於或等於使用>=
或小於或等於使用到<=
):
import java.util.Scanner;
class Bigger {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// get user name from the user
System.out.print("Please enter your user name: ");
String userName = input.nextLine();
// get second name from the user
System.out.print("Please enter your second name: ");
String secondName = input.nextLine();
// use an appropriate method to find the number of letters and prompt user
if(userName.length() == secondName.length()) {
System.out.println(userName + " is equal in length than " + secondName);
} else if(userName.length() > secondName.length()) {
System.out.println(userName + " is longer in length than " + secondName);
} else {
System.out.println(userName + " is shorter in length than " + secondName);
}
}
}
實例應用:
Please enter your user name: MarkDoherty
Please enter your second name: Denmark
MarkDoherty is longer in length than Denmark
另外,您可以使用字符串格式化像這樣:
// use an appropriate method to find the number of letters
if(userName.length() == secondName.length()) {
System.out.printf("%s (%d characters long) is equal in length than %s (%d characters long)\n", userName, userName.length(), secondName, secondName.length());
} else if(userName.length() > secondName.length()) {
System.out.printf("%s (%d characters long) is longer in length than %s (%d characters long)\n", userName, userName.length(), secondName, secondName.length());
} else {
System.out.printf("%s (%d characters long) is shorter in length than %s (%d characters long)\n", userName, userName.length(), secondName, secondName.length());
}
實例應用:
Please enter your user name: MarkDoherty
Please enter your second name: Denmark
MarkDoherty (11 characters long) is longer in length than Denmark (7 characters long)
告訴我們您遇到什麼問題試試看here!
開始。 – bejado
這不是代碼審查的地方。如果你有關於代碼的具體問題,那麼你需要明確地問它。否則,人們不太可能爲你調試你的代碼。 – Encaitar
因此......'System.out.print(userName +「是最長的字符串」);'? –