学习java:字符比较

时间:2016-04-30 01:00:51

标签: java character

练习: (最长公共前缀)编写一个程序,提示用户输入两个字符串并显示两个字符串的最大公共前缀。

以下是一些示例运行:

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);
        }

    }

}

我的代码有什么问题吗? 为什么我无法获得正确的结果?

2 个答案:

答案 0 :(得分:1)

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

应该是:

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

您之前正在比较第一个字符串。

答案 1 :(得分:1)

您正在if语句中将firstString与其自身进行比较。

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