Calculator program - JAVA

Status
Not open for further replies.

laserpp

Distinguished
Nov 29, 2008
137
0
18,630
Hey everyone, need a little help. For some reason I am horrible at file I/O and always have trouble with it. Well my problem, I have a calculator class that shows a user a menu, they then pick a choice and enter 2 numbers and get the sum from w/e choice they picked. I have that all up and working. The last part of the assignment is to log every choice the user picks until he ends the program. For example the log file would look like this:

4+5=9
3-5=-2
7*7=49
ect
ect
ect

Just a file that someone can go in at the end of the program and just see a simple view of what he entered in order and the results. I get the file to be created but when I open it, it is blank... Here's the code:

Code:
import java.util.Scanner;
import java.io.*;
 
public class Calculator {
	
	public int add(int num1, int num2){
	
		int sum;
		sum = num1 + num2;
		
		return sum;
	}
	
	public int sub(int num1, int num2){
	
		int sum;
		sum = num1 - num2;
		
		return sum;
	}
	
	public int multi(int num1, int num2){
	
		int sum;
		sum = num1 * num2;
		
		return sum;
	}
	
	public int div(int num1, int num2){
	
		int sum;
		sum = num1 / num2;
		
		return sum;
	}
	
	public int mod(int num1, int num2){
	
		int sum;
		sum = num1 % num2;
		
		return sum;
	}
	
	public int pow(int base, int exp){
	
		int sum = 1;
		
		if (exp == 0)
		{
			sum = 1;
		}
		
		while (exp > 0)
		{
			sum = sum * base;
			exp--;
			
		}
	
		
		return sum;
		
	}
    
    public static void main(String[] args) {
    	
    	int choice;
    	int x;
    	int y;
    	int sum;
    	
    	
    	Calculator calc = new Calculator();
    
    	
    	do
    	{
    		System.out.println("Calculator Program");
    		System.out.println("--------------------\n");
    		System.out.println("1.  Add");
    		System.out.println("2.  Subtract");
    		System.out.println("3.  Multiply");
    		System.out.println("4.  Divide");
    		System.out.println("5.  Mod");
    		System.out.println("6.  Power");
    		System.out.println("99. End Program\n");
    		System.out.println("Enter Choice: ");
    		
    		Scanner input = new Scanner(System.in);
    		choice = input.nextInt();
    		
    		while ((choice < 1 || choice > 6) && choice != 99)
    		{
    			System.out.println("Please enter a 1, 2, 3, 4, 5, or 6: " );
    			choice = input.nextInt();
    		}
    			
    	try
    	{
    		FileWriter fstream = new FileWriter("calclog.txt");
    		BufferedWriter out = new BufferedWriter(fstream);
    	
    	
    	switch (choice)
    	{
    		case 1: 
    			System.out.println("Please enter 2 numbers only: ");
    			x = input.nextInt();
    			y = input.nextInt();
    			sum = calc.add(x,y);
    			System.out.printf("The sum is %d\n\n",sum);
    			out.write(x + "+" + y + "=" + sum);
    			break;
    			
    		case 2:
    			System.out.println("Please enter 2 numbers only: ");
    			x = input.nextInt();
    			y = input.nextInt();
    			sum = calc.sub(x,y);
    			System.out.printf("The sum is %d\n\n",sum);
    			out.write(x + "+" + y + "=" + sum);
    			break;
    			
    		case 3:
    			System.out.println("Please enter 2 numbers only: ");
    			x = input.nextInt();
    			y = input.nextInt();
    			sum = calc.multi(x,y);
    			System.out.printf("The sum is %d\n\n",sum);
    			out.write(x + "+" + y + "=" + sum);
    			break;
    			
    		case 4:
    			System.out.println("Please enter 2 numbers only: ");
    			x = input.nextInt();
    			y = input.nextInt();
    			sum = calc.div(x,y);
    			System.out.printf("The sum is %d\n\n",sum);
    			out.write(x + "+" + y + "=" + sum);
    			break;
    			
    		case 5:
    			System.out.println("Please enter 2 numbers only: ");
    			x = input.nextInt();
    			y = input.nextInt();
    			sum = calc.mod(x,y);
    			System.out.printf("The sum is %d\n\n",sum);
    			out.write(x + "+" + y + "=" + sum);
    			break;
    			
    		case 6:
    			System.out.println("Please enter 2 numbers only: ");
    			x = input.nextInt();
    			y = input.nextInt();
    			sum = calc.pow(x,y);
    			System.out.printf("The sum is %d\n\n",sum);
    			out.write(x + "+" + y + "=" + sum);
    			break;
    	}
    	out.close();
    	}
    	catch(Exception e)
    	{
    		System.out.println("ERROR: Could not open file!");
    	}
    	
    	
    	}
    	while (choice != 99);
    	System.out.println("Ending program...");
    	
    	
    
    }
}

Thank you for any help =D.
 
Solution
Actually the problem is that by default, when a file is opened, it is overwritten and since the file opening is in your do-while loop, when the user enter 99 it still opens the file, but writes nothing to it, therefore the empty file. Either open and close the file outside the loop and/or open it in "append mode" depending on the exact behavior you are looking for.

I also double-checked the PrintWriter thing and using a PrintStream would be easier since you don't need to create the FileWriter first, you can give it the "File" object or even just the file name.

mindless728

Distinguished
Jul 15, 2008
130
0
18,660
add an out.close as the last line of your program as that will flush the buffers then close the file, what probably is happening is that java is closing but the buffer is not being flushed before the file is closed losing the data
 

Zenthar

Distinguished
Dec 31, 2007
250
0
18,960
Actually the problem is that by default, when a file is opened, it is overwritten and since the file opening is in your do-while loop, when the user enter 99 it still opens the file, but writes nothing to it, therefore the empty file. Either open and close the file outside the loop and/or open it in "append mode" depending on the exact behavior you are looking for.

I also double-checked the PrintWriter thing and using a PrintStream would be easier since you don't need to create the FileWriter first, you can give it the "File" object or even just the file name.
 
Solution

Zenthar

Distinguished
Dec 31, 2007
250
0
18,960
I didn't make a career out of it for nothing ;). It would have been clearer had the OP indented his code properly; the do-while, the try-catch and the switch-case are all at the same level.

For code cleanliness, most of the stuff in the "case" sections are just duplicates and could probably be put outside.
 

mindless728

Distinguished
Jul 15, 2008
130
0
18,660


my career as well (though i have had one job and still in school for CS), though the indentation did not help at all
 

laserpp

Distinguished
Nov 29, 2008
137
0
18,630
I am going to try using the printstream, but you said do it outside the loop. But my slides on using the printstream shows that I need what ever to be written to the file inside the TRY block. So doesnt it have to be inside the loop? or do I put the whole loop inside the TRY block? I feel like writing to files is so easy, I don't understand why I have such a hard time with it.
 

laserpp

Distinguished
Nov 29, 2008
137
0
18,630
Alright changed some things around. Took the enter 2 numbers out of each CASE and put up top, but now when I hit 99 it asks for 2 numbers instead of ending. I tried doing the PrintStream but still no luck. And tried to indent it better, since professor says he will take a lot of points off for not properly indenting. Here's the new code:

Code:
import java.util.Scanner;
import java.io.*;
 
public class Calculator {
	
	public int add(int num1, int num2){
	
		int sum;
		sum = num1 + num2;
		
		return sum;
	}
	
	public int sub(int num1, int num2){
	
		int sum;
		sum = num1 - num2;
		
		return sum;
	}
	
	public int multi(int num1, int num2){
	
		int sum;
		sum = num1 * num2;
		
		return sum;
	}
	
	public int div(int num1, int num2){
	
		int sum;
		sum = num1 / num2;
		
		return sum;
	}
	
	public int mod(int num1, int num2){
	
		int sum;
		sum = num1 % num2;
		
		return sum;
	}
	
	public int pow(int base, int exp){
	
		int sum = 1;
		
		if (exp == 0)
		{
			sum = 1;
		}
		
		while (exp > 0)
		{
			sum = sum * base;
			exp--;
			
		}
	
		
		return sum;
		
	}
    
    public static void main(String[] args) {
    	
    	int choice;
    	int x;
    	int y;
    	int sum;
    	PrintStream out;
    	
    	Calculator calc = new Calculator();
    
    	
    	try
    	{
    		out = new PrintStream ("calclog.txt");
    		
    		do
    		{
    			System.out.println("Calculator Program");
    			System.out.println("--------------------\n");
    			System.out.println("1.  Add");
    			System.out.println("2.  Subtract");
    			System.out.println("3.  Multiply");
    			System.out.println("4.  Divide");
    			System.out.println("5.  Mod");
    			System.out.println("6.  Power");
    			System.out.println("99. End Program\n");
    			System.out.println("Enter Choice: ");
    		
    			Scanner input = new Scanner(System.in);
    			choice = input.nextInt();
    		
    			while ((choice < 1 || choice > 6) && choice != 99)
    			{
    				System.out.println("Please enter a 1, 2, 3, 4, 5, or 6: " );
    				choice = input.nextInt();
    			}
    			
    	
    			System.out.println("Please enter 2 numbers only: ");
    			x = input.nextInt();
    			y = input.nextInt();
    	
    				switch (choice)
    				{
    					case 1: 
    						sum = calc.add(x,y);
    						System.out.printf("The sum is %d\n\n",sum);
    						out.println(x + "+" + y + "=" + sum);
    						break;
    			
    					case 2:
    						sum = calc.sub(x,y);
    						System.out.printf("The sum is %d\n\n",sum);
    						out.println(x + "-" + y + "=" + sum);
    						break;
    			
    					case 3:
    						sum = calc.multi(x,y);
    						System.out.printf("The sum is %d\n\n",sum);
    						out.println(x + "*" + y + "=" + sum);
    						break;
    			
    					case 4:
    						sum = calc.div(x,y);
    						System.out.printf("The sum is %d\n\n",sum);
    						out.println(x + "/" + y + "=" + sum);
    						break;
    			
    					case 5:
    						sum = calc.mod(x,y);
    						System.out.printf("The sum is %d\n\n",sum);
    						out.println(x + "%" + y + "=" + sum);
    						break;
    			
    					case 6:
    						sum = calc.pow(x,y);
    						System.out.printf("The sum is %d\n\n",sum);
    						out.println(x + "^" + y + "=" + sum);
    						break;
    				}
    	
    		}
    		
    		while (choice != 99);
    		System.out.println("Ending program...");
    	
    	}
    	
    	catch(Exception e)
    	{
    		System.out.println("ERROR: Could not open file!");
    	}
    	
    	
    	
    	
    	
    	
    
    }
}
 

laserpp

Distinguished
Nov 29, 2008
137
0
18,630
Scratch that about not getting the PrintStream to work, I forgot to add the import for PrintStream. It is working great now. Just need to fix the 99 not quitting right away. I know why it is not quitting right away, because once the validation part at line 98 is checked, even if its 99 it will always run the "Pick 2 numbers." Not sure where to put it then, other then making the switch statements bulkier.


Also how can I make the file created to my desktop, not to where ever the program default is?
 

laserpp

Distinguished
Nov 29, 2008
137
0
18,630
Okay everything is working, thanks guys, just some little questions. In my div method, I am validating so that you can't divided by 0. Here is the code:

Code:
public int div(int num1, int num2){
	
		int sum = 0;
		if (num2 == 0)
		{
			System.out.println("ERROR: Can't divide by 0");
			
		}
		else
		{
			sum = num1 / num2;
			
		}
		
		return sum;
	}

When you do it you get the error message but you also get the "The sum is 0" since I have to initialize sum as 0. How can I get it to just leave the method after the error message is shown and skip the return sum statement?
 

Zenthar

Distinguished
Dec 31, 2007
250
0
18,960
The only way to leave a method without having to return anything is to throw an exception.

Alternatively, one could also return a predefined "error" value (called a sentinel), but it's not always possible; for your operation for example, any value could be valid so no sentinel possible. A way around this specific problem for you, would be to use the "wrapper" class Integer, by having an object as a return value, you could also return "null" as a value which could be your sentinel to indicate something was wrong.
 

Zenthar

Distinguished
Dec 31, 2007
250
0
18,960
Oh, just a side-note that the use of sentinels is sometimes frown upon in Object Oriented Programming, some say this is just old procedural programming practices. Personally I don't care that much as long as it's clear and documented.
 

laserpp

Distinguished
Nov 29, 2008
137
0
18,630
lol that a whole bunch of things not learned yet lol. So pretty much the way I have it there is no way around it? Unless I look up what sentinels are. I tried to make sum = null but got errors, is it because null only works with strings?
 

Zenthar

Distinguished
Dec 31, 2007
250
0
18,960
null only works on objects and all basic types (int, long, char, float, double, ...) are what is called primitives; they do not support null. You could always make the check before calling calc.div().
 

laserpp

Distinguished
Nov 29, 2008
137
0
18,630


I changed it to this. Works way better. thanks
 
Status
Not open for further replies.