Closed. This question does not meet Stack Overflow guidelines。它当前不接受答案。
                            
                        
                    
                
            
                    
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        6年前关闭。
                    
                
        

我的代码有错误,我似乎找不到解决方案,请有人可以调试我的代码吗?

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]+" ");
    }

  }
}

最佳答案

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];
  }
}

关于java - 我的程序抛出一个java.lang.ArrayIndexOutOfBoundsException ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20644239/

10-11 22:52
查看更多