摩根和一个字符串

时间:2015-05-11 07:51:01

标签: java arrays string indexoutofboundsexception

我正在尝试解决这个问题:https://www.hackerrank.com/challenges/morgan-and-a-string

这是我的代码:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution 
{

   public static void main(String[] args) 
  {
   Scanner sc = new Scanner(System.in);
   int t = Integer.parseInt(sc.nextLine());
    while((t--)>0)
    {
        String s1 = sc.nextLine();
        String s2 = sc.nextLine();
        System.out.println(ms(s1,s2));
    }
  }

 public static String ms(String s1, String s2)
 {
     StringBuffer sb = new StringBuffer();
     int i,j;
     for(i=0,j=0;i<s1.length() || j<s2.length() ;)
     {
        if(s1.charAt(i)>s2.charAt(j))
            {
                sb.append(s2.charAt(j));
                if(j==s2.length())
                    break;
                else
                    j++;
            }
        else
            {
                sb.append(s1.charAt(i));
                if(i==s1.length())
                    break;
                else
                    i++;
            }
     }

     if(j==s2.length())
     {  
     for(;i<s1.length();i++)
            sb.append(s1.charAt(i));

     return sb.toString();
     }

     else
     {
     for(;j<s2.length();j++)
            sb.append(s2.charAt(j));

      return sb.toString();
      }
   }   
 }

我收到此错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at Solution.ms(Solution.java:28)
at Solution.main(Solution.java:18)

有谁能告诉我哪里出错了?我无法找到错误...

2 个答案:

答案 0 :(得分:3)

我不知道您正在尝试使用该程序,但我认为这将消除您的错误

for(i=0,j=0;i<s1.length() & j<s2.length() ;)

答案 1 :(得分:2)

我刚刚更改了你的for循环,如下所示,我可以毫无问题地执行程序

for(i = 0, j = 0; i < s1.length() && j < s2.length();)

PFB源代码

import java.util.Scanner;

public class Test {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int t = Integer.parseInt(sc.nextLine());
    while ((t--) > 0) {
        String s1 = sc.nextLine();
        String s2 = sc.nextLine();
        System.out.println(ms(s1, s2));
    }
}

public static String ms(String s1, String s2) {
    StringBuffer sb = new StringBuffer();
    int i, j;
    for (i = 0, j = 0; i < s1.length() && j < s2.length();) {
        if (s1.charAt(i) > s2.charAt(j)) {
            sb.append(s2.charAt(j));
            if (j == s2.length())
                break;
            else
                j++;
        } else {
            sb.append(s1.charAt(i));
            if (i == s1.length())
                break;
            else
                i++;
        }
    }

    if (j == s2.length()) {
        for (; i < s1.length(); i++)
            sb.append(s1.charAt(i));

        return sb.toString();
    }

    else {
        for (; j < s2.length(); j++)
            sb.append(s2.charAt(j));

        return sb.toString();
    }
}
}