練習: (最長公共前綴)編寫一個程序,提示用戶輸入兩個字符串並顯示兩個字符串的最大公共前綴。學習java:字符比較
下面是一些樣品運行:
Enter the first string: Welcome to C++
Enter the second string: Welcome to programming
The common prefix is Welcome to
第二輪:
Enter the first string: Atlanta
Enter the second string: Macon
Atlanta and Macon have no common prefix
我的回答:
package chapter5;
import java.util.*;
public class Exer5_51 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first string: ");
String firstString = input.nextLine();
System.out.println("Enter the second string");
String secondString = input.nextLine();
input.close();
int length = Math.min(firstString.length(), secondString.length());
String commonPrefix = "";
for (int n = 0; n < length; n++) {
if (firstString.charAt(n) == firstString.charAt(n)) {
commonPrefix += firstString.charAt(n);
}
else {
break;
}
}
if (commonPrefix.length() != 0) {
System.out.printf("The common prefix is %s", commonPrefix);
}
else {
System.out.printf("%s and %s have no common prefix", firstString, secondString);
}
}
}
這有什麼錯我的代碼? 爲什麼我不能得到正確的結果?
歡迎使用StackOverflow,請記住在發佈問題時要包括運行代碼時獲得的輸出以及預期的輸出結果。 – CConard96