Java BigInt Class: Adding Two Objects with Carryover | Plus Method

  • Context: Comp Sci 
  • Thread starter Thread starter apiwowar
  • Start date Start date
  • Tags Tags
    Java
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
31 replies · 12K views
i changed my test code to what i posted below. it seems that the numbers go in right. num3.digit[47] is 1, num3.digit[48] is 0 and num3.digit[49] is 0 and everything before 47 is 0. but if i just print out num 3 it comes out as 001000...

Code:
import java.util.Scanner;

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

	Scanner input = new Scanner(System.in);
	
	//int number1 = input.nextInt();
	//int number2 = input.nextInt();
	BigIntAlternate num1 = new BigIntAlternate(99);
		
	BigIntAlternate num2 = new BigIntAlternate(1);
	
	BigIntAlternate num3 = new BigIntAlternate();
	
	num3 = num1.plus(num2);
	for(int i = 0; i <= 49; i++)
	{
	
	
	System.out.println(i + " Num1 + Num2 = " + num3.digit[i]);
	}
	System.out.println("\ncompare num1 and num2 " + num1.compareTo(num2));
	
	}
}
 
Physics news on Phys.org
So don't use print or println to display all of the digits. What you did by using a loop to go through each element in the digit array is fine.

Does this work?
Code:
System.out.print(num3.digit)

An even better solution would be to write print and println methods for your class to display the digit array.

The code would look like this:
Code:
// Display the digits of a BigNum object.
void print(BigNum bn)
{
   for (int i = 0; i < max; i++)
   {
      print(bn.digit[i]);
   }
}

The code for println would be almost identical, except that it would print a newline character after the last digit.

Your last code snippet is much improved, but could use two tweaks - all of the statements in the body of main should be indented, and the body of the for loop should be indented, like the following. I've deleted a few of the lines you aren't using.

Code:
public static void main(String[] args)
{
   BigIntAlternate num1 = new BigIntAlternate(99);
   BigIntAlternate num2 = new BigIntAlternate(1);
   BigIntAlternate num3 = new BigIntAlternate();
	
   num3 = num1.plus(num2);
   for(int i = 0; i <= 49; i++)
   {
      System.out.println(i + " Num1 + Num2 = " + num3.digit[i]);
   }
   System.out.println("\ncompare num1 and num2 " + num1.compareTo(num2));
}