我的程序抛出了一个java.lang.ArrayIndexOutOfBoundsException

时间:2013-12-17 20:41:42

标签: java arrays

我的代码中有错误,似乎无法找到解决方案,请有人调试我的代码吗?

import java.util.* ; 

  public class Calculator {
    public static void main(String[] args) {   

    Scanner s = new Scanner(System.in);
    System.out.print("Enter the first number:");
    String a = s.nextLine(); 
    System.out.print("Enter the second number:");
    String b = s.nextLine();   

    int[] num1 = new int[a.length()];
    int[] num2 = new int[b.length()];

    for (int i=0;i<a.length();i++) {
      num1[i] = (int) a.charAt(i);
      num2[i] = (int) b.charAt(i);
    }

    int[] sum = new int[a.length()];

    for (int i = a.length() - 1; i >= 0; i--){
      if (num1[i] + num2[i] >= 10){
        sum[i] = (num1[i]+num2[i]) - 10;
        **sum[i-1] = 1;**
      } else {
          sum[i] = num1[i] + num2[i];   
      }
    }

    for (int i = 0; i < a.length(); i++) {
      System.out.print(sum[i]+" ");
    }  

  }
}

2 个答案:

答案 0 :(得分:5)

a.length()可能不等于b.length()

有问题的代码

int[] num1 = new int[a.length()];
int[] num2 = new int[b.length()];

for (int i=0;i<a.length();i++) {
  num1[i] = (int) a.charAt(i);
  num2[i] = (int) b.charAt(i);
}

例如:考虑a.length() = 10b.length() = 2

的情况

进一步有问题的代码:

for (int i = a.length() - 1; i >= 0; i--){
  if (num1[i] + num2[i] >= 10){
    sum[i] = (num1[i]+num2[i]) - 10;
    **sum[i-1] = 1;**
  } else {
      sum[i] = num1[i] + num2[i];   
  }
}

答案 1 :(得分:0)

你可以这样做。

public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Enter the first number");
String a = s.nextLine(); 
System.out.print("Enter the second number:");
String b = s.nextLine();   
int[] num1 = new int[a.length()];
int[] num2 = new int[b.length()];

for (int i=0;i<a.length();i++) {
  num1[i] = (int) a.charAt(i);

}
for (int i=0;i<b.length();i++)
{
  num2[i] = (int) b.charAt(i);
}
int[] sum;
if(a.length()>b.length())
{
   sum = new int[a.length()];
   for (int i = a.length() - 1; i >= 0; i--)
   {
       if (num1[i] + num2[i] >= 10)
          {
              sum[i] = (num1[i]+num2[i]) - 10;
              /*sum[i-1] = 1;*/
    } 
    else {
       sum[i] = num1[i] + num2[i];   
    }
 }

}
else
{
    sum = new int[b.length()];

    for (int i = a.length() - 1; i >= 0; i--)
    {
       if (num1[i] + num2[i] >= 10)
          {
              sum[i] = (num1[i]+num2[i]) - 10;
              /*sum[i-1] = 1;*/
    } 
    else {
       sum[i] = num1[i] + num2[i];   
    }
 }
}


for (int i = 0; i < a.length(); i++) {
  System.out.print(sum[i]+" ");
}
}