2016-04-30 82 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