Results 1 to 4 of 4
  1. #1
    Alpinstang is offline New to Java
    Join Date
    Sep 2012
    Location
    University of Memphis
    Posts
    5
    Rep Power
    0

    Question Basic Java Calculator - Division Issue

    First off hello to all on the forum. I'm taking a class in Java at my University this semester and our first programming assignment is a basic calculator. It needs to add, subtract, multiply and divide. I have the first three arithmetic functions working fine, but division is causing me problems. It continuously puts out 0 as the result. Here is my code:

    Java Code:
    import java.io.*;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    
    public class BasicCalculator
    {
    	public static void main(String[] args)
    	{
    		//	Declare all datatypes and variables and set the values to 0...
    		String FirstNumber = "";
    		String SecondNumber = "";
    
    		int FirstNumberInt = 0;
    		int SecondNumberInt = 0;
    
    		int AdditionResult = 0;
    		int SubtractionResult = 0;
    		int MultiplicationResult = 0;
    		int DivisionResult = 0;
    
    		//	create object of input stream reader...
    		InputStreamReader istream = new InputStreamReader(System.in);
    		//	create object of bufferedReader using istream...
    		BufferedReader bufRead = new BufferedReader(istream);
    
    		//describe program to user
    		ProgramDescription();
    
    		//	Ask User for the First Number...
    		System.out.print("Enter your First Number: ");
    		try
    		{
    		//	Store user input number...
    		FirstNumber = bufRead.readLine();
    			//	convert to int data type...
    			FirstNumberInt = Integer.parseInt(FirstNumber);
    		}
    		catch (Exception e)
    		{
    			//user entered an invalid value
    			//such as a letter or a symbol
    			System.out.println("Oops... Invalid Entry!!!");
    		}
    
    		//	Ask User for the Second Number...	
    		System.out.print("Enter your Second Number: ");
    		try
    		{
    		//	Store user input number...
    		SecondNumber = bufRead.readLine();
    			//	convert to int data type...
    			SecondNumberInt = Integer.parseInt(SecondNumber);
    		}
    		catch (Exception e)
    		{
    			//user entered an invalid value
    			//such as a letter or a symbol
    			System.out.println("Oops... Invalid Entry!!!");
    		}
    
    		//	Add the two numbers and store it...
    		AdditionResult = FirstNumberInt + SecondNumberInt;
    
    		//	Subtract the two numbers and store it...
    		SubtractionResult = FirstNumberInt - SecondNumberInt;
    
    		//	Multiply the two numbers and store it...
    		MultiplicationResult = FirstNumberInt * SecondNumberInt;
    
    		//	Divide the two numbers and store it...
    		DivisionResult = FirstNumberInt / SecondNumberInt;
    			
    		//create an object of NumberFormat for accuracy
    		NumberFormat formatter = new DecimalFormat("#0.0");
    
    		//	Print Addition Result...
    		System.out.println("\nThe result of both numbers added.");
    		System.out.print("Addition: " + FirstNumber + " + " + SecondNumber + " = " + formatter.format(AdditionResult) + "\n\n");
    		
    		//	Print Subtraction Result...
    		System.out.println("The result of both numbers subtracted.");
    		System.out.print("Subtraction: " + FirstNumber + " - " + SecondNumber + " = " + formatter.format(SubtractionResult) + "\n\n");
    
    		//	Print Multiplication Result...
    		System.out.println("The result of both numbers multiplied.");
    		System.out.print("Mutliplication: " + FirstNumber + " x " + SecondNumber + " = " + formatter.format(MultiplicationResult) + "\n\n");
    
    		//	Print Division Result...
    		System.out.println("The result of both numbers divided.");
    		System.out.print("Division: " + FirstNumber + " / " + SecondNumber + " = " + formatter.format(DivisionResult) + "\n\n");	
    }
    	static void ProgramDescription()
    	{
    		System.out.println("\n\n");
    		System.out.println("		Basic Calculator		");
    		System.out.println("This program will calculate addition, subtraction");
    		System.out.println("multiplication, and division of two numbers.\n");
    		System.out.println("Enter a numerical value when prompted below...");
    		System.out.println("-------------------------------------------------\n");
    	}
    }
    Last edited by Alpinstang; 09-06-2012 at 09:21 AM.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,863
    Rep Power
    19

    Default Re: Basic Java Calculator - Division Issue

    You need to look up integer division.
    If FirstNumber is less than SecondNumber then the result will always be zero.
    You would need to cast one or the other to a double, and the result should also be a double.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    Alpinstang is offline New to Java
    Join Date
    Sep 2012
    Location
    University of Memphis
    Posts
    5
    Rep Power
    0

    Post Re: Basic Java Calculator - Division Issue

    Quote Originally Posted by Tolls View Post
    You need to look up integer division.
    If FirstNumber is less than SecondNumber then the result will always be zero.
    You would need to cast one or the other to a double, and the result should also be a double.
    Thanks, here is the working code.
    Java Code:
    import java.io.*;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    
    public class Calc
    {
        public static void main(String[] args)
        {
            //  Declare all datatypes and variables and set the values to 0...
            String FirstNumber = "";
            String SecondNumber = "";
            double FirstNumberDouble = 0;	//	double used because integer division properties will automatically discard fractions. (Round Down) 
            double SecondNumberDouble = 0;	//	If the second number is larger than the first the result would always be zero. Double fixes this.
    	boolean Retry = false;
            //  create object of input stream reader...
            InputStreamReader istream = new InputStreamReader(System.in);
            //  create object of bufferedReader using istream...
            BufferedReader bufRead = new BufferedReader(istream);
     
            ProgramDescription();	//describe program to user
    	do
    	{		
    		try
    		{
    			//  Ask User for the First Number...
    			System.out.print(" Enter your First Number: ");
    			//  Store user input number...
    			FirstNumber = bufRead.readLine();
    			FirstNumberDouble = Double.parseDouble(FirstNumber);	//parse string to double data type...			
    		
    			//  Ask User for the Second Number...  
    			System.out.print(" Enter your Second Number: ");
    			//  Store user input number...
    			SecondNumber = bufRead.readLine();
                SecondNumberDouble = Double.parseDouble(SecondNumber);	//parse string to double data type...
    			
    			if( SecondNumberDouble == 0.0 )	//	if the denominator is 0...
    			{
    				throw new ArithmeticException();	//	throw an exception
    			}
    
    			NumberFormat formatter = new DecimalFormat("#0.0");	//create an object of NumberFormat for accuracy
    		    //  Print Addition Result...
    			System.out.println("\n The result of both numbers added.");
    			System.out.println(" Addition: " + FirstNumber + " + " + SecondNumber + " = " + formatter.format(FirstNumberDouble+SecondNumberDouble));
    			System.out.println("");
    			//  Print Subtraction Result...
    			System.out.println(" The result of both numbers subtracted.");
    			System.out.println(" Subtraction: " + FirstNumber + " - " + SecondNumber + " = " + formatter.format(FirstNumberDouble-SecondNumberDouble));
    			System.out.println("");
    			//  Print Multiplication Result...
    			System.out.println(" The result of both numbers multiplied.");
    			System.out.println(" Mutliplication: " + FirstNumber + " x " + SecondNumber + " = " + formatter.format(FirstNumberDouble*SecondNumberDouble));
    			System.out.println("");
    			//  Print Division Result...
    			System.out.println(" The result of both numbers divided.");
    			System.out.println(" " + FirstNumberDouble + " / " + SecondNumberDouble + " = " + FirstNumberDouble/SecondNumberDouble ); //unformatted for accuracy
    			System.out.println("");
    			Retry = false;
    			ShowDeveloperInfo(); // Developer Information printed after results.
    		}
    		catch (NumberFormatException exc)	// non-number catch subclass
    		{
    			System.err.println( "\n Incorrect Entry. Make sure you use an integer value.\n DETAILS: " + exc );
    			Retry = true;
    			System.out.println(" Please try again.\n\n");
    		}
    		catch (ArithmeticException exc)	// divide by zero catch subclass
    		{
    			System.err.println( "\n Sorry, can't divide by zero!\n DETAILS: " + exc ); //	Dvide by zero exception handling
    			Retry = true;
    			System.out.println(" Please try again.\n\n");
    		}
    		catch (Throwable exc)	//	catch superclass to catch all exceptions
    		{
    			System.err.println( "\n An Exception has Occurred.\n DETAILS: " + exc );
    			Retry = true;
    			System.out.println(" Please try again.\n\n");
    		}
    	}while(Retry == true);
    }
    	static void ProgramDescription()	//	Describes the program to the user
        {
        System.out.println("\n\n");
        System.out.println("        	Basic Calculator        ");
        System.out.println(" This program will calculate addition, subtraction");
        System.out.println(" multiplication, and division of two numbers.");
        System.out.println(" Enter a numerical value when prompted below...");
        System.out.println(" ----------------------------------------------\n");
        }
    }

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

    Default Re: Basic Java Calculator - Division Issue

    Comments:

    Never test a boolean variable's equality to a boolean literal.
    Java Code:
    //    }while(Retry == true);
        }while(Retry);
    Java Code:
    //    }while(Retry == false);
        }while(!Retry);
    Follow coding conventions: variable names start with a lowercase letter, and outdents match indents. Code Conventions for the Java Programming Language: Contents

    Java is an object oriented language. The job of the main(...) method is normally to create one or more instances of a class or classes and kick off the program. Not to be the program.

    Don't catch Throwable or Exception. Catch only specific Exception subclasses that are of interest (normally, only checked exceptions).

    Do print the stack trace in a catch(...) block.

    Close resources in a finally block, or use the new Java 7 try-with-resources.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. need help with my basic java calculator code
    By hashey100 in forum New To Java
    Replies: 3
    Last Post: 11-12-2011, 04:48 PM
  2. Basic Calculator
    By Bimz in forum New To Java
    Replies: 13
    Last Post: 09-09-2011, 10:47 AM
  3. Basic Java Calculator Code Problem
    By SerbianSergeant in forum New To Java
    Replies: 7
    Last Post: 07-22-2011, 01:50 PM
  4. help with basic sum calculator in java
    By java157 in forum New To Java
    Replies: 8
    Last Post: 03-17-2011, 11:12 PM
  5. Basic Calculator
    By trtoy in forum New To Java
    Replies: 1
    Last Post: 12-25-2009, 01:06 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •