2016-04-30 88 views
-2

練習: (最長公共前綴)編寫一個程序,提示用戶輸入兩個字符串並顯示兩個字符串的最大公共前綴。學習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); 
     } 

    } 

} 

這有什麼錯我的代碼? 爲什麼我不能得到正確的結果?

+0

歡迎使用StackOverflow,請記住在發佈問題時要包括運行代碼時獲得的輸出以及預期的輸出結果。 – CConard96

回答

1
if (firstString.charAt(n) == firstString.charAt(n)) { 
      commonPrefix += firstString.charAt(n); 
} 

應該是:

if (firstString.charAt(n) == secondString.charAt(n)) { 
      commonPrefix += firstString.charAt(n); 
} 

以前您的第一個字符串與自己進行比較。

+0

謝謝,我一定太累了。 – camelcigar

1

您正在將firstString與if語句中的自身進行比較。

if (firstString.charAt(n) == firstString.charAt(n)) { 
    commonPrefix += firstString.charAt(n); 
} 
+0

這是我的第一個節目,我是一個粗心的人! – camelcigar