I have attached 2 java files which, when run, simulate a calculator that performs addition and multiplication only. I have been working on it for some time...getting assistance from varioius sources. I am having two issues I need help in correcting. They are as follows:

1) When multiplying two single digit numbers...a leading zero is attached
to the bottom digit (num2) I wish to remedy this by either removing it
for single digits or add a zero to the top digit (num1). I'm referring
to the output display.

2) When the output is displayed...the top number (num1) is shifted to
much to the right. I would like for it to be a bit more uniform.


I am trying to learn JAVA and this is my first attempt at a program other than the example from "JAVA for Dummies!" lol. Thanks in advance.

Attachments
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Class:  			BigInt()													\\
// Description:		This class performs a number of methods, primarily the 		\\
//					mathimatical operations of addition and multiplication 		\\
//					are performed on other objects associated with BigInt.  	\\
//					Per the clients request, the BigInt can handle very 		\\
//					large non-negative whole numbers in its operation(s).		\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

class BigInt 
{

	// data strucure representing the array of digits in this number
	private int[] digits;

	// boolean representing whether this integer is zero
	private boolean isZero=false;

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Constructor:  	BigInt(String)												\\
// Description:		New instance of BigInt is created based on string 			\\
//					parameter, val.  The string is checked for validity.  		\\
//					Once OK'ed it is parsed and used to create the "digits" 	\\
//					array.  													\\
// Precondition:	If val is of length 0 then Exception.  						\\
// Postcondition:	Digits array field populated with new value of 				\\
//					parameter val.												\\
// Exception:		NumberFormatException										\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

	// constructor...the string may contain leading zeros.
	public BigInt(String val)
	{
	  // check whether string is of lenght 0
	  if(val.length()==0)
	  {
		throw new NumberFormatException("Zero length BigInt");
	  }

      // check the string and make sure it's valid
	  for(int i=0; i<val.length(); ++i)
	  {
	   char character=val.charAt(i);
	  if( !Character.isDigit(character) )
	   {
	   throw new NumberFormatException("Non-digit character in BigInt "+val);
	   }
	  }
		
		// if string is ok parse it and create the digits array
		this.digits=parseString(val);

		// first digit is 0 only if this BigInt is zero
		if(digits[0] == 0)
		{
			isZero=true;
		}

	}  // end constructor

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		parseString(String val)										\\
// Description:		Method passes String val and checks to see if string 		\\
//					represents zero												\\
// Precondition:																\\
// Postcondition:																\\
// Exception:																	\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

	// parse it and create an int array
	private int[] parseString(String val) 
	{
		int valLength=val.length();

		// check if this string represent zero
		boolean allZeroes=true;
		for(int i=0; i<valLength; ++i)
		{
			char character=val.charAt(i);
			if(character!='0')
			{
				allZeroes=false;
				break;
			}
		}

		if(allZeroes)
		{
			int[] digit=new int[1];
			digit[0]=0;
			return digit;
		}

		// remove leading zeroes from the string
		for(int i=0; i<val.length(); ++i)
		{
			char character=val.charAt(i);
		// if zero found trim the string by one at beginnng
		// i.e. if string is 0456 then after taking substring it is 456
			if(character=='0')
			{
				val=val.substring(1);
			}
			else
			{
				break;
			}
		}  // end for

	// create an array to hold the digits
		int[] tempDigits=new int[val.length()];
		
	// check each digit in string & convert to an int & store in array
		for(int i=0; i<val.length(); ++i)
		{
			char character=val.charAt(i);
			tempDigits[i]=Integer.parseInt(""+character);
		}  // end for

		return tempDigits;

	}  // end method
	
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		display()													\\
// Description:		Do not write leading zeros, but if number consists of 		\\
//					all zeros, write a single zero.								\\
// Precondition:	None														\\
// Postcondition:	Removal of leading 0's.  Display a single 0 if all are 0	\\
// Exception:		None														\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

	public void display()
	{
		for(int i=0; i<digits.length; ++i)
		{
			System.out.print(digits[i]);
		}
	}  // end method

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		BigInt add(BigInt)											\\
// Description:		This method takes two object of BigInt type and adds 		\\
//					them together.  Other operations are performed here 		\\
//					such as appending 0's onto smallest # to match length 		\\
//					with larger #. The possibility of "carry" is considered 	\\
//					and accounted for.											\\
// Precondition:	........................									\\
// Postcondition:	........................									\\
// Exception:		None														\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

// method that returns sum of val and instance of BigInt that invokes add
	public BigInt add(BigInt val)
	{
		// find the smallest number
		BigInt large=val;
		BigInt small=this;

		// if both are not of equal sizes...
		if(large.digits.length != small.digits.length)
		{
			if(this.digits.length > val.digits.length)
			{
				large=this;
				small=val;
			}
			else{
				large=val;
				small=this;
			}

// append 0's to beginning of smallest number to make its length equal to largest 
			int diff=large.digits.length - small.digits.length;
			int[] tempDigits=new int[large.digits.length];

			for(int i=0;i<diff; ++i)
			{
				tempDigits[i]=0;
			}

			int j=0;
			for(int i=diff; i<tempDigits.length; ++i)
			{
				tempDigits[i]=small.digits[j++];
			}

			small.digits=tempDigits;
		}
		
		// do the addition
		String result="";
		int carryForward=0;
		int register=0;

		// add the numbers digit by digit
		for(int i=large.digits.length-1; i>=0; --i)
		{
			// System.out.println("\ni = "+i);
			register=large.digits[i] + small.digits[i] + carryForward;
			if(register>9)
			{
				carryForward=1;
				register-=10;
			}
			else
			{
				carryForward=0;
			}
			
			result= register + result;
		}

		if(carryForward>0)
		{
			result= carryForward+result;
		}

		return new BigInt(result);
	}  // end method

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		isOne()														\\
// Description:		Used to determine if BigInt is equal to 1					\\
// Precondition:	None														\\
// Postcondition:	Boolean flag of true or false is returned based on if 		\\
//					statement conditions.  Returns "true" if value is one.		\\
// Exception:		None														\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

	private boolean isOne()
	{
		if(this.digits.length==1 && this.digits[0]==1)
		{
			return true;
		}
		else
		{
			return false;
		}
	}  // end method
	
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		BigInt multiply(BigInt val)									\\
// Description:		Following method performs multiplication by addition.  		\\
//					"If" statements check for two unique inputs...				\\
//					one number = 0 or 1.										\\
// Precondition:	None														\\														
// Postcondition:	None														\\
// Exception:		None														\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

	// A method that returns product of val and the instance of BigInt that 
	// invokes multiply
	public BigInt multiply(BigInt val)
	{
		// if one of the numbers is zero return 0
		if(isZero || val.isZero)
		{
			return new BigInt("0");
		}

		// if one of the numbers is one return the other
		if( isOne() )
		{
			return val;
		}

		if( val.isOne() )
		{
			return this;
		}

		// else multiply the two numbers by adding the bigger one to itself
		// find the smallest number
		BigInt large=null;
		BigInt small=null;
		if(this.digits.length > val.digits.length)
		{
			large=this;
			small=val;
		}
		else
		{
			large=val;
			small=this;
		}

		// multiplication by repeated addition
		BigInt result=new BigInt("0");

		int multiplyBy=1;
		for(int i=small.digits.length-1; i>=0; --i )
		{
			int number=small.digits[i] * multiplyBy;  
			//System.out.println("number "+number);

			for(int j=1; j<=number; ++j)
			{
				result=result.add(large);

			}  // end inner for

			multiplyBy *= 10;
		}  // end outer for

		return result;

	}  // end method

}  // end class
import java.io.*;		// import package
import java.util.*;		// import package

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Class:  			InteractiveCalculator()											\\
// Method:			Main()															\\
// Description:		Purpose of InteractiveCalculator class is to force 				\\
//					associated classes to act.  Purpose of the Main method is 		\\
//					to create an instance of the calculator and start it.			\\
// Precondition:	None															\\
// Postcondition:	Create an instance of the calculator							\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

public class InteractiveCalculator 
{

	// main method of the application
	public static void main(String[] args)
	{
		InteractiveCalculator interactiveCal=new InteractiveCalculator();
		interactiveCal.startCalculator();

	}  // end main
	
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		StartCalculator()												\\
// Description:		Purpose of StartCalculator is to print an introduction 			\\
//                  specifing input format. A request for input data is 			\\
//					also displayed.  												\\
// Precondition:	None															\\
// Postcondition:	Accepted input from user "inputLine"							\\
// Exception:		IOException														\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\	

	private void startCalculator()
	{
		// read from the console
		BufferedReader cReader=new BufferedReader(new InputStreamReader(System.in));

		 // print introduction
		System.out.println("---------------------------------------------------");
 		System.out.println("This program demonstrates the BigInt class.");
 		System.out.println("Please enter expressions to evaluate in the format:");
 		System.out.println("\n                a + b   addition");
 		System.out.println("                      or");
 		System.out.println("                a * b   multiplication");
 		System.out.println("\nAny other input will terminate the program.");
 		System.out.println("\nType .");
 		System.out.println("---------------------------------------------------");

 		do
 		{
  			String inputLine=null;

  			System.out.print("\n\nEnter command in one of two formats shown above:");
	 	try
	  	{
			inputLine=cReader.readLine().trim();
	  	}
		catch(IOException io)
		{
          System.out.println("\nError while reading from console.");
		}

			if(inputLine.equals("quit"))
			{
				break;
			}

		// parse the input line and display output
		parseInputLineAndDisplayResult(inputLine);
		}
			while(true);

		System.out.println("\nQuitting...");
	}  // end method
 
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		parseInputLineAndDisplayResults(String inputLine)			\\
// Description:		The following method breaks up the input line by 			\\
//					tokenizing it where it encounters "spaces" Three tokens 	\\
//					are created: num1, op, and num2.  If 3 tokens are not 		\\
//					read/created then user is informed of the correct 			\\
//					syntax and given a chance to re-enter data.  Operator 		\\
//					(+ or *) is validated as well. If anything other than		\\
//					+ or * is input, an error appears informing you of 			\\
//					proper operators.  Based on operator, the desired			\\
//					operation is performed and the result is displayed.			\\
// Precondition:	Some input "inputline"										\\
// Postcondition:	Displays the output (ANSWER) in the proper format as 		\\
//					requested by the client										\\
// Exception:		NumberFormatException										\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

   private void parseInputLineAndDisplayResult(String inputLine)
   {
	// tokenize the string on space
   	StringTokenizer strTok=new StringTokenizer(inputLine," ");

	// there should be exactly 3 tokens, num1, op, and num2
		if(strTok.countTokens() != 3)
   		{
			System.out.println("Invalid inputline. Syntax is \' num1 op num2 \' ");
				return;
   		}

			// if string syntax is ok tokenize and get the tokens
	  		String num1=strTok.nextToken();
	 		String op=strTok.nextToken();
	  		String num2=strTok.nextToken();

		// validate the operator. it can be either + or *
		if( !op.equals("+") && !op.equals("*") )
		{
     		System.out.println("Invalid Operator. Only \'+\' and \'*\' allowed");    
	    		return;
		}

			// create BigInts
			BigInt bgInt1=null;
			BigInt bgInt2=null;
			BigInt result=null;

		try
		{
			bgInt1=new BigInt(num1);
			bgInt2=new BigInt(num2);
		}
		
		catch(NumberFormatException nx)
		{
			System.out.println("Error: "+nx.getMessage());
			return;
		}

		// now perform the operation
		if(op.equals("+"))
		{
			result=bgInt1.add(bgInt2);
		}
		
		else
		{
			result=bgInt1.multiply(bgInt2);
		}

			// display the result
			System.out.println(" ");
			bgInt1.display( );
			System.out.print("\n"+ op +" ");
			bgInt2.display();
			System.out.println("\n--------------------------");
			result.display();

	}  // end method

}  // end class

You'll have to explain the 1st question a little more.

One the second question, if you are using a JTextField to display data, you can set the horizontal alignment.

textField.setHorizontalAlignment(JTextField.CENTER);
                                                    or   .RIGHT
                                                    or   .LEFT
                                                    or   .LEADING
                                                    or   .TRAILING

Can you enhance your program with adding and subtracting method as well? I'd love to see the complete calculator if you dont mind. The program occurs because of your display method. You'll need to add some code to check if the preceeding number is 0, it has to be gotten rid of before being printed out to the screen.

To server_crash, you will understand the first question if you try to run the program with some trial input. About the second question, I dont think your answer is helpful at all.

To server_crash, you will understand the first question if you try to run the program with some trial input. About the second question, I dont think your answer is helpful at all.

I don't have time to run everyone's code. If you do, that's great. About your second comment, I just now looked at the code and saw that he's using the command line to run this.d

hi compiler

I have changed your code at a couple of places.
try running your code and tell me is this what was in your mind?

regards
Srinivas

Attachments
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Class:  			BigInt()													\\
// Description:		This class performs a number of methods, primarily the 		\\
//					mathimatical operations of addition and multiplication 		\\
//					are performed on other objects associated with BigInt.  	\\
//					Per the clients request, the BigInt can handle very 		\\
//					large non-negative whole numbers in its operation(s).		\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

class BigInt 
{

	// data strucure representing the array of digits in this number
	private int[] digits;

	// boolean representing whether this integer is zero
	private boolean isZero=false;

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Constructor:  	BigInt(String)												\\
// Description:		New instance of BigInt is created based on string 			\\
//					parameter, val.  The string is checked for validity.  		\\
//					Once OK'ed it is parsed and used to create the "digits" 	\\
//					array.  													\\
// Precondition:	If val is of length 0 then Exception.  						\\
// Postcondition:	Digits array field populated with new value of 				\\
//					parameter val.												\\
// Exception:		NumberFormatException										\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

	// constructor...the string may contain leading zeros.
	public BigInt(String val)
	{
	  // check whether string is of lenght 0
	  if(val.length()==0)
	  {
		throw new NumberFormatException("Zero length BigInt");
	  }

      // check the string and make sure it's valid
	  for(int i=0; i<val.length(); ++i)
	  {
		char character=val.charAt(i);

		if( !Character.isDigit(character) )
		{
		throw new NumberFormatException("Non-digit character in BigInt "+val);
		}
	  }
		
		// if string is ok parse it and create the digits array
		this.digits=parseString(val);

		// first digit is 0 only if this BigInt is zero
		if(digits[0] == 0)
		{
			isZero=true;
		}

	}  // end constructor

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		parseString(String val)										\\
// Description:		Method passes String val and checks to see if string 		\\
//					represents zero												\\
// Precondition:																\\
// Postcondition:																\\
// Exception:																	\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

	// parse it and create an int array
	private int[] parseString(String val) 
	{
		int valLength=val.length();

		// check if this string represent zero
		boolean allZeroes=true;
		for(int i=0; i<valLength; ++i)
		{
			char character=val.charAt(i);
			if(character!='0')
			{
				allZeroes=false;
				break;
			}
		}

		if(allZeroes)
		{
			int[] digit=new int[1];
			digit[0]=0;
			return digit;
		}

		// remove leading zeroes from the string
		for(int i=0; i<val.length(); ++i)
		{
			char character=val.charAt(i);
		// if zero found trim the string by one at beginnng
		// i.e. if string is 0456 then after taking substring it is 456
			if(character=='0')
			{
				val=val.substring(1);
			}
			else
			{
				break;
			}
		}  // end for

	// create an array to hold the digits
		int[] tempDigits=new int[val.length()];
		
	// check each digit in string & convert to an int & store in array
		for(int i=0; i<val.length(); ++i)
		{
			char character=val.charAt(i);
			tempDigits[i]=Integer.parseInt(""+character);
		}  // end for

		return tempDigits;

	}  // end method
	
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		display()													\\
// Description:		Do not write leading zeros, but if number consists of 		\\
//					all zeros, write a single zero.								\\
// Precondition:	None														\\
// Postcondition:	Removal of leading 0's.  Display a single 0 if all are 0	\\
// Exception:		None														\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

	public void display()
	{
		for(int i=0; i<digits.length; ++i)
		{
			System.out.print(digits[i]);
		}
	}  // end method

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		BigInt add(BigInt)											\\
// Description:		This method takes two object of BigInt type and adds 		\\
//					them together.  Other operations are performed here 		\\
//					such as appending 0's onto smallest # to match length 		\\
//					with larger #. The possibility of "carry" is considered 	\\
//					and accounted for.											\\
// Precondition:	........................									\\
// Postcondition:	........................									\\
// Exception:		None														\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

// method that returns sum of val and instance of BigInt that invokes add
	public BigInt add(BigInt val)
	{
		// find the smallest number
		BigInt large=val;
		BigInt small=this;

		// if both are not of equal sizes...
		if(large.digits.length != small.digits.length)
		{
			if(this.digits.length > val.digits.length)
			{
				large=this;
				small=val;
			}
			else{
				large=val;
				small=this;
			}

// append 0's to beginning of smallest number to make its length equal to largest 
			int diff=large.digits.length - small.digits.length;
			int[] tempDigits=new int[large.digits.length];

			for(int i=0;i<diff; ++i)
			{
				tempDigits[i]=0;
			}

			int j=0;
			for(int i=diff; i<tempDigits.length; ++i)
			{
				tempDigits[i]=small.digits[j++];
			}

			small.digits=tempDigits;
		}
		
		// do the addition
		String result="";
		int carryForward=0;
		int register=0;

		// add the numbers digit by digit
		for(int i=large.digits.length-1; i>=0; --i)
		{
			// System.out.println("\ni = "+i);
			register=large.digits[i] + small.digits[i] + carryForward;
			if(register>9)
			{
				carryForward=1;
				register-=10;
			}
			else
			{
				carryForward=0;
			}
			
			result= register + result;
		}

		if(carryForward>0)
		{
			result= carryForward+result;
		}

		return new BigInt(result);
	}  // end method

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		isOne()														\\
// Description:		Used to determine if BigInt is equal to 1					\\
// Precondition:	None														\\
// Postcondition:	Boolean flag of true or false is returned based on if 		\\
//					statement conditions.  Returns "true" if value is one.		\\
// Exception:		None														\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

	private boolean isOne()
	{
		if(this.digits.length==1 && this.digits[0]==1)
		{
			return true;
		}
		else
		{
			return false;
		}
	}  // end method
	
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		BigInt multiply(BigInt val)									\\
// Description:		Following method performs multiplication by addition.  		\\
//					"If" statements check for two unique inputs...				\\
//					one number = 0 or 1.										\\
// Precondition:	None														\\														
// Postcondition:	None														\\
// Exception:		None														\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

	// A method that returns product of val and the instance of BigInt that 
	// invokes multiply
	public BigInt multiply(BigInt val)
	{
		// if one of the numbers is zero return 0
		if(isZero || val.isZero)
		{
			return new BigInt("0");
		}

		// if one of the numbers is one return the other
		if( isOne() )
		{
			return val;
		}

		if( val.isOne() )
		{
			return this;
		}

		// else multiply the two numbers by adding the bigger one to itself
		// find the smallest number
		BigInt large=null;
		BigInt small=null;
		if(this.digits.length > val.digits.length)
		{
			large=this;
			small=val;
		}
		else
		{
			large=val;
			small=this;
		}

		// multiplication by repeated addition
		BigInt result=new BigInt("0");

		int multiplyBy=1;
		for(int i=small.digits.length-1; i>=0; --i )
		{
			int number=small.digits[i] * multiplyBy;  
			//System.out.println("number "+number);

			for(int j=1; j<=number; ++j)
			{
				result=result.add(large);

			}  // end inner for

			multiplyBy *= 10;
		}  // end outer for

		return result;

	}  // end method

}  // end class
import java.io.*;		// import package
import java.util.*;		// import package

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Class:  			InteractiveCalculator()											\\
// Method:			Main()															\\
// Description:		Purpose of InteractiveCalculator class is to force 				\\
//					associated classes to act.  Purpose of the Main method is 		\\
//					to create an instance of the calculator and start it.			\\
// Precondition:	None															\\
// Postcondition:	Create an instance of the calculator							\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

public class InteractiveCalculator 
{

	// main method of the application
	public static void main(String[] args)
	{
		InteractiveCalculator interactiveCal=new InteractiveCalculator();
		interactiveCal.startCalculator();

	}  // end main
	
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		StartCalculator()												\\
// Description:		Purpose of StartCalculator is to print an introduction 			\\
//                  specifing input format. A request for input data is 			\\
//					also displayed.  												\\
// Precondition:	None															\\
// Postcondition:	Accepted input from user "inputLine"							\\
// Exception:		IOException														\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\	

	private void startCalculator()
	{
		// read from the console
		BufferedReader cReader=new BufferedReader(new InputStreamReader(System.in));

		 // print introduction
		System.out.println("---------------------------------------------------");
 		System.out.println("This program demonstrates the BigInt class.");
 		System.out.println("Please enter expressions to evaluate in the format:");
 		System.out.println("\n                a + b   addition");
 		System.out.println("                      or");
 		System.out.println("                a * b   multiplication");
 		System.out.println("\nAny other input will terminate the program.");
 		System.out.println("\nType .");
 		System.out.println("---------------------------------------------------");

 		do
 		{
  			String inputLine=null;

  			System.out.print("\n\nEnter command in one of two formats shown above:");
	 	try
	  	{
			inputLine=cReader.readLine().trim();
	  	}
		catch(IOException io)
		{
          System.out.println("\nError while reading from console.");
		}

			if(inputLine.equals("quit"))
			{
				break;
			}

		// parse the input line and display output
		parseInputLineAndDisplayResult(inputLine);
		}
			while(true);

		System.out.println("\nQuitting...");
	}  // end method
 
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\
// Method:  		parseInputLineAndDisplayResults(String inputLine)			\\
// Description:		The following method breaks up the input line by 			\\
//					tokenizing it where it encounters "spaces" Three tokens 	\\
//					are created: num1, op, and num2.  If 3 tokens are not 		\\
//					read/created then user is informed of the correct 			\\
//					syntax and given a chance to re-enter data.  Operator 		\\
//					(+ or *) is validated as well. If anything other than		\\
//					+ or * is input, an error appears informing you of 			\\
//					proper operators.  Based on operator, the desired			\\
//					operation is performed and the result is displayed.			\\
// Precondition:	Some input "inputline"										\\
// Postcondition:	Displays the output (ANSWER) in the proper format as 		\\
//					requested by the client										\\
// Exception:		NumberFormatException										\\
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\

   private void parseInputLineAndDisplayResult(String inputLine)
   {
	// tokenize the string on space
   	StringTokenizer strTok=new StringTokenizer(inputLine," ");

	// there should be exactly 3 tokens, num1, op, and num2
		if(strTok.countTokens() != 3)
   		{
			System.out.println("Invalid inputline. Syntax is \' num1 op num2 \' ");
				return;
   		}

			// if string syntax is ok tokenize and get the tokens
	  		String num1=strTok.nextToken();
	 		String op=strTok.nextToken();
	  		String num2=strTok.nextToken();

		// validate the operator. it can be either + or *
		if( !op.equals("+") && !op.equals("*") )
		{
     		System.out.println("Invalid Operator. Only \'+\' and \'*\' allowed");    
	    		return;
		}

			// create BigInts
			BigInt bgInt1=null;
			BigInt bgInt2=null;
			BigInt result=null;

		try
		{
			bgInt1=new BigInt(num1);
			bgInt2=new BigInt(num2);
		}
		
		catch(NumberFormatException nx)
		{
			System.out.println("Error: "+nx.getMessage());
			return;
		}

		// now perform the operation
		

			System.out.print("  ");
			bgInt1.display();
			System.out.print("\n"+ op +" ");
			bgInt2.display();
			System.out.println("\n--------------------------");

			if(op.equals("+"))
			{
			result=bgInt1.add(bgInt2);
			}
		
			else
			{
			result=bgInt1.multiply(bgInt2);
			}

			// display the result
			System.out.print("  ");
			result.display();

	}  // end method

}  // end class

You succeed in get rid of the leading Zero in the output. That's great. But what I am trying to do is come up with a better algorithm for the muliplication method. When I entered a 10 digit number times another 8 digit number, it would take like forever to get the answer. There's a huge Big O for the efficiency of this program.

This article has been dead for over six months. Start a new discussion instead.