练习: (最长公共前缀)编写一个程序,提示用户输入两个字符串并显示两个字符串的最大公共前缀。学习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