2014-02-23 25 views
1

所以我已經得到這兩個陣列,以便在無需攜帶任何東西時能夠正確添加。所以[0,1,1] + b [0,1,1]會給我c [0,0,2,2],但是如果我同樣做一個[0,9,9] + b [0, 9,9]我只得到c [0,0,8,8]。方法addBigInts中的循環似乎不像我想的那樣工作。任何想法都表示讚賞。按元素求和兩個數組,問題與攜帶1

import java.util.*; 

public class AddBigInts { 

public static void main(String[] args) { 
    Scanner console = new Scanner(System.in); 
    //init firstNum array 
    int[] firstNum = new int[getDigit()]; 
    System.out.println("First number:"); 
    //gets input to pop array 
    firstNum = getInt(firstNum); 
    //second array is same length 
    int[] secondNum = new int[firstNum.length]; 
    System.out.println("Second number:"); 
    //pop second array 
    secondNum = getInt(secondNum); 
    System.out.println(Arrays.toString(firstNum)); 
    System.out.println(Arrays.toString(secondNum)); 
    addBigInts(firstNum, secondNum); 
} 

//creates array that is one place bigger than entered # 
public static int getDigit(){ 
    Scanner console = new Scanner(System.in); 
    System.out.print("How many digits? "); 
    int arraySize = console.nextInt(); 
    return arraySize + 1; 
} 

//populates array 
public static int[] getInt (int[] num){ 
    Scanner console = new Scanner(System.in); 
    for (int i=num.length-1; i>0; i--){ 
     System.out.print("Digit " + i + ": "); 
     num[i] = console.nextInt(); 
    } 
    return num; 

} 

//adds both arrays by index into the sum array 
public static int[] addBigInts (int[]numArray1, int[] numArray2){ 
    int count = Math.max(numArray1.length, numArray2.length); 
    int[] sum = new int[count+1]; 
    //starting at numArray1 & 2 index, sums ints 
    for (int i=count-1; i>=0; i--){ 
     //sum has to be +1 for numArray1 & 2 indexes 
     sum[i+1] = numArray1[i] + numArray2[i]; 
     if (sum[i+1]>9){ 
      //this line below doesn't seem to execute 
      sum[i]++; 
      sum[i+1] = sum[i+1] - 10; 
     } 
     else; 

     } 
    System.out.println(Arrays.toString(sum)); 
    return sum; 
    } 
} 
+0

嗨。要求人們發現代碼中的錯誤並不是特別有效。您應該使用調試器(或者添加打印語句)來分析問題,追蹤程序的進度,並將其與預期發生的情況進行比較。只要兩者發生分歧,那麼你就發現了你的問題。 (然後,如果有必要,你應該構造一個[最小測試用例](http://sscce.org)。) –

+0

首先,請注意,如果兩個操作數數組的長度不相同,那麼您的代碼很容易出錯。如果兩個長度不同,你會在這一行得到一個'ArrayIndexOutOfBoundsException':'sum [i + 1] = numArray1 [i] + numArray2 [i];' –

+0

@D_C:+1發佈可編輯源文件和清晰描述的問題。 –

回答

2

您有:

sum[i+1] = numArray1[i] + numArray2[i]; 

您需要:

sum[i+1] += numArray1[i] + numArray2[i]; 

通過分配而不是添加,您將覆蓋前一位數字中攜帶的1。

+0

這就是它!我在指責錯誤的路線。謝謝! –

0

在外接bigints功能,嘗試改變店鋪加入到一個臨時變量和使用,在if語句

int temp = numArray1[i] + numArray2[i] if(temp > 9)

+0

這隻會添加一個不必要的步驟,因爲我想和數組 –