Jump to content

First time Java program check

Wtalk2

Hey LTT Forums :D

Today I became really inspired to learn to code since I am nearly positive I want to learn to get into software engineering. (I am only 13 so I have plenty of time to learn :P)

I have always been sort of interested in Java programming since my two favourite childhood games (Runescape and Minecraft) were coded in Java.

Today I went and got myself Eclipse and started trying to make a simple console calculator. After about a hour and a half of trial and error I have come up with this:

package calculator;import java.util.*;public class Calculator {		public static void main(String[] args){				//Restarts program at end.		boolean run = true;		while(run){							//Waits for 0.75 Seconds before running program.			try{				  Thread.currentThread();				Thread.sleep(750);				}				catch(InterruptedException ie){				}		//Asks user what operation they want to use.        System.out.println("Hello, If you are doing Addition Type 1.");        System.out.println("If you are doing Subtraction, Type 2.");        System.out.println("If you are doing Multiplication, Type 3");        System.out.println("If you are doing Division, Type 4");                //Scanner to make input1 the operation being used.        Scanner input1 = new Scanner(System.in);        int decision;        decision = input1.nextInt();                //Prints what operation was selected to the user.        if (decision == 1){        	System.out.println("You have chosen Addition.");        }        if (decision == 2){        	System.out.println("You have chosen Subtraction.");        }        if (decision == 3){        	System.out.println("You have chosen Multiplication.");        }        if (decision == 4){        	System.out.println("You have chosen Division.");        }                System.out.println("Please choose your first number.");                //Scanner to make input2 the users first number.        Scanner input2 = new Scanner(System.in);        int number1;        number1 = input2.nextInt();                System.out.println("Please choose your second number.");                //Scanner to make input3 the users second number.        Scanner input3 = new Scanner(System.in);        int number2;        number2 = input3.nextInt();                //Variables for the answers for each of the operations.		int answer1;		answer1 = number1 + number2;				int answer2;		answer2 = number1 - number2;				int answer3;		answer3 = number1 * number2;				int answer4;		answer4 = number1 / number2;        		//Prints the answer of their equation to the user.        if (decision == 1){        	System.out.println(number1 + " plus " + number2 + " equals " + answer1);        }        if (decision == 2){        	System.out.println(number1 + " minus " + number2 + " equals " + answer2);        }        if (decision == 3){        	System.out.println(number1 + " times " + number2 + " equals " + answer3);        }        if (decision == 4){        	System.out.println(number1 + " divided by " + number2 + " equals " + answer4);        }        	}	}}

So far it works perfectly and surprisingly has no errors in Eclipse but I would like the help of all you seasoned Java dev's to help me clean up my code and give me some tips for the future.

 

Cheers  ;)

My Current Build: 

Intel i5 3570K @ 4.4GHz 1.11V, Cooler Master Hyper 212 EVO, Asrock Z77 Extreme4, Corsair Vengeance 8GB 1600MHz, Samsung 840 EVO 250GB, Asus GTX 760 DCII Overclocked, Corsair CX600M

Link to comment
Share on other sites

Link to post
Share on other sites

//Variables for the answers for each of the operations.		int answer1;		answer1 = number1 + number2;				int answer2;		answer2 = number1 - number2;				int answer3;		answer3 = number1 * number2;				int answer4;		answer4 = number1 / number2;        		//Prints the answer of their equation to the user.        if (decision == 1){        	System.out.println(number1 + " plus " + number2 + " equals " + answer1);        }        if (decision == 2){        	System.out.println(number1 + " minus " + number2 + " equals " + answer2);        }        if (decision == 3){        	System.out.println(number1 + " times " + number2 + " equals " + answer3);        }        if (decision == 4){        	System.out.println(number1 + " divided by " + number2 + " equals " + answer4);

Look at this snippet of code. Can you think of the way to merge the two parts?

//Prints what operation was selected to the user.        if (decision == 1){        	System.out.println("You have chosen Addition.");        }        if (decision == 2){        	System.out.println("You have chosen Subtraction.");        }        if (decision == 3){        	System.out.println("You have chosen Multiplication.");        }        if (decision == 4){        	System.out.println("You have chosen Division.");        }

I find that whenever I need to make one decision from several options, a Switch statement is often a good choice.

 

Fyi. I'm as much of an amateur as you are. These are just things I ran into myself. Also attempt to put the answer part into a seperate class.

 

Otherwise, it's looking pretty nice.

Desktop: CPU: i7 3770k OC: 4.0 GHZ | CPUCooler: Corsair H100i | GPU: Asus GTX 670 DirectCU2 | Motherboard: Gigabyte z77x-ud5h | RAM: Corsair Vengeance 16 gig, 1600 mhz | PSU: Corsair AX860 | Soundcard: Asus Xonar Essence STX | Storage: Corsair Force 3 120 gb, Western Digital Caviar Black 2 TB | OS: Windows 8.1 Pro

Periphirals: Keyboard: Logitech g710+ | Mice: Desktop: Razer Imperator Battlefield 3 Edition. Laptop: Razer Deathadder 3.5g edition | Mousepads: Desktop: Razer Goliathus Control Extended edition Laptop: Razer Goliathus Control edition | Sound stuff: Bose Companion 2 speakers (Free yay), Beyerdynamic DT-770 250 Ohm.

Laptop: Lenovo Thinkpad Edge e540: CPU: i7 4702mq | GPU: Nvidia Geforce gt740 | RAM: 8 gig of some brand | Storage: 1 TB of some brand 5400 rpm | OS: Windows 8.1 Pro

Link to comment
Share on other sites

Link to post
Share on other sites

If there is only one decision to be made then I'd recommend using else if() since this would only allow one of the algorithms to be activated unlike in if() you'd be able to have them all activated which could cause some possible problems in bigger programs. Just a heads up ;)

 

Also instead of manually typing in "You've chosen subtract", "you've chosen divide etc...." you can have these responses in a array like so

 String[] choiceResponse = {"You have chosen Addition.", "You have chosen Subtraction.", "You have chosen Multiplication.", "You have chosen Division" };

And then you'd just do the following instead of manually checking if they chose 1 type this, if they chose 2 type this etc....  

System.out.println(choiceResponse[decision-1]);

The reason to why we'd subtract 1 from the list is mainly because an array starts from 0 and not 1 so option 1 is 0 and since you'd have them enter a option from 1 to 4 you'd want to subtract 1

Link to comment
Share on other sites

Link to post
Share on other sites

package calculator;import java.util.*;public class Calculator {	public static void main(String[] args) {		while(true) {			System.out.println("Hello, If you are doing Addition Type 1.");			System.out.println("If you are doing Subtraction, Type 2.");			System.out.println("If you are doing Multiplication, Type 3");			System.out.println("If you are doing Division, Type 4");			Scanner input = new Scanner(System.in);						int decision = Integer.parseInt(input.nextLine());			if(decision == 1) {				System.out.println("You have chosen Addition.");			} else if(decision == 2) {				System.out.println("You have chosen Subtraction.");			} else if(decision == 3) {				System.out.println("You have chosen Multiplication.");			} else if(decision == 4) {				System.out.println("You have chosen Division.");			} else {				System.out.println("Wrong operation!");				continue;			}						System.out.println("Please choose your first number.");			double number1 = Double.parseDouble(input.nextLine());						System.out.println("Please choose your second number.");			double number2 = Double.parseDouble(input.nextLine());			if(decision == 1) {				System.out.println(number1 + " plus " + number2 + " equals " + (number1 + number2));			} else if(decision == 2) {				System.out.println(number1 + " minus " + number2 + " equals " + (number1 - number2);			} else if(decision == 3) {				System.out.println(number1 + " times " + number2 + " equals " + (number1 * number2));			} else if(decision == 4) {				System.out.println(number1 + " divided by " + number2 + " equals " + (number1 / number2);			}		}	}}

1. Indent correctly

2. Use else if: Reduces execution times in large applications, because it doesn't need to check the other conditions when one already matches.

3. Don't use multiple Scanners. You are fine with one. 

4. Don't calculate every possibility at once. Just execute code that is relevant.

 

I also changed your nextInt methods to nextLine methods and wrapped them in Double.parseDouble. This way you

 

a. Get decimal numbers, so you can execute calculations that result into fractions. Also, if you didn't already notice, your current solution will give 1 as answer when you try 3 / 2. Even though 3 / 2 = 1,5 when you cast it to integer, the decimal part will be lost. With doubles you always have decimals.

b. When you hit enter, nextInt won't read the line break character. This might cause problems in some cases.

Link to comment
Share on other sites

Link to post
Share on other sites

And then you'd just do the following instead of manually checking if they chose 1 type this, if they chose 2 type this etc....  

System.out.println(choiceResponse[decision+1]);

 

You probably want to subtract instead.

Link to comment
Share on other sites

Link to post
Share on other sites

You probably want to subtract instead.

Woops yerp that's correct sorry ^-^ Wrote this post as soon as I woke up so what do you expect lol

Link to comment
Share on other sites

Link to post
Share on other sites

the bad thing that still wasn't pointed out is the "bug"

your program doesn't allow the user to calculate, for example

1 + 0

3 - 0

8 * 0

because it will anyway try to calculate the division too, the division will be by zero, therefore god will get angry and the world will collapse

so this is related to a couple of things that you may want to correct

  1. check every input: you must assume that the user is a douchebag and will input the wrong things, also when you execute something, make sure that that instruction can be executed, so when you divide you must be sure that you're not dividing by zero
  2. the first point is spread all over the 4 operations, because all the calcolations are done even when not necessary. try to make programs so that only the necessary steps are executed
Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×