[英]Studing java: character comparing
練習:(最長公共前綴)編寫一個程序,提示用戶輸入兩個字符串並顯示兩個字符串中最大的公共前綴。
以下是一些示例運行:
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);
}
}
}
我的代碼有什么問題嗎? 為什么我不能得到正確的結果?
if (firstString.charAt(n) == firstString.charAt(n) ) {
commonPrefix += firstString.charAt(n);
}
應該:
if (firstString.charAt(n) == secondString.charAt(n) ) {
commonPrefix += firstString.charAt(n);
}
您之前正在將第一個 String 與其自身進行比較。
您正在 if 語句中將 firstString 與其自身進行比較。
if (firstString.charAt(n) == firstString.charAt(n) ) {
commonPrefix += firstString.charAt(n);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.