Results 1 to 4 of 4
- 09-06-2012, 09:17 AM #1
New to Java
- Join Date
- Sep 2012
- Location
- University of Memphis
- Posts
- 5
- Rep Power
- 0
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.
- 09-06-2012, 10:04 AM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,438
- Rep Power
- 16
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.
- 09-07-2012, 10:12 PM #3
New to Java
- Join Date
- Sep 2012
- Location
- University of Memphis
- Posts
- 5
- Rep Power
- 0
Re: Basic Java Calculator - Division Issue
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"); } }
- 09-07-2012, 10:31 PM #4
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);Follow coding conventions: variable names start with a lowercase letter, and outdents match indents. Code Conventions for the Java Programming Language: ContentsJava Code:// }while(Retry == false); }while(!Retry);
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.
dbWhy do they call it rush hour when nothing moves? - Robin Williams
Similar Threads
-
need help with my basic java calculator code
By hashey100 in forum New To JavaReplies: 3Last Post: 11-12-2011, 04:48 PM -
Basic Calculator
By Bimz in forum New To JavaReplies: 13Last Post: 09-09-2011, 10:47 AM -
Basic Java Calculator Code Problem
By SerbianSergeant in forum New To JavaReplies: 7Last Post: 07-22-2011, 01:50 PM -
help with basic sum calculator in java
By java157 in forum New To JavaReplies: 8Last Post: 03-17-2011, 11:12 PM -
Basic Calculator
By trtoy in forum New To JavaReplies: 1Last Post: 12-25-2009, 01:06 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks