1

最初の位置を返す方法がわかりません org と check が異なります。部分文字列を使用する必要がありますか?

import acm.program.*;

public class CheckPasswords extends ConsoleProgram
{
  public void run()
  {  

   while(true)
   {
      String org = readLine("Enter Password: ");
      String check = readLine("Confirm Password: ");

      if(org.equals(check))
      {
        println("Password Confirmed");
      }
      else
      {
        println("Passwords do not Match");
        //???
      }
   }
  }
}
4

4 に答える 4

0

私の解決策は次のとおりです。

static public int indexOfDiff(String one, String two) {
    if(one!=null && two!=null) { 
        if(one==null || two==null) { 
            return 0;            
            }
        else {
            int ln=(one.length()<two.length() ? one.length() : two.length());
            for(int xa=0; xa<ln; xa++) {
                if(one.charAt(xa)!=two.charAt(xa)) { return xa; }
                }
            if(one.length()!=two.length()) {
                return ln;
                }
            }
        }
    return -1;
    }

-1これは、文字列が実際に等しい場合 (両方が である場合を含む) を返します。これは、文字null列が異なることが既にわかっているため、通常、実際の使用では当てはまりません。

于 2014-02-10T17:49:19.727 に答える
-1

それらが等しいかどうかを確認したい場合は、次を使用できます。

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

      }
   }
  }
}
于 2014-02-10T04:43:06.327 に答える