如果您只想检查它们是否相等,可以使用:
int val = org.compareTo(check);
如果它们相等,它将返回 0,如果 org 在 check 之前返回负值,如果 org在check之后返回正值。
如果您真的想返回它们不相等的第一个位置,请使用此函数:
int firstMismatch(String org, String check)
{
int limit = (org.length()>check.length())?org.length():check.length();
for(int i=0;i<limit;i++)
{
try{
if(org.charAt(i)!=check.charAt(i))
{
return i; //If one of the strings end, that's the position they are different, otherwise there is a mismatch. Either way, just return the index of mismatch
}
}
catch(Exception e)
{
if(org.length()!=check.length())
{
return(i); //Execution comes here only when length of strings is unequal
//Exception occurs because first string is smaller than
// the second or vice versa. Say if you use "fred" and"fredd" as org and check
//respectively, "fred" is smaller than "fredd" so accessing org[4] is not allowed.
//Hence the exception.
}
System.out.println("Problem encountered"); //Some other exception has occured.
return(-2);
}
}
return(-1); //if they are equal, just return -1
}
编辑:在您的代码中,调用如下:
public class CheckPasswords extends ConsoleProgram
{
public void run()
{
while(true)
{
String org = readLine("Enter Password: ");
String check = readLine("Confirm Password: ");
int mismatchPosition = firstMisMatch(org,check);
if(mismatchPosition==-1)
{
println("Password Confirmed");
}
else
{
println("Passwords do not match from position "+mismatchPosition);
}
}
}
}