7-2 求解给定字符串的前缀 (10分)(Java)_while循环


这道题有点离谱,我用while循环写,全是答案错误(可能是判断条件有问题或者其他),用do while就可以。以后需要用do while的时候就不能冷落她了

import java.util.Scanner;

public class Main{
public static int fun(String a, String b){
int k = 0;
int len1 = a.length();
int len2 = b.length();
while(a.charAt(k) == b.charAt(k)){
k++;
}
return k;
}
public static void main(String[] args){
// System.out.println(Main.fun("filename", "filepath"));
Scanner input = new Scanner(System.in);
int num = 0;
int cnt = 0;
String ans = "";
do{
String a = input.nextLine();
if (a.equals("")){
break;
}
String[] strings = a.split(" ");
num = Main.fun(strings[0],strings[1]);
if (num != 0){
ans = a.substring(0,num);
System.out.println("The common prefix is " + ans);
}else{
System.out.println("No common prefix");
}
}while(true);



}
}