# Basic Calculator program question

Page 1 of 1

## 3 Replies - 534 Views - Last Post: 10 April 2011 - 03:39 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=226892&amp;s=6a8fcea74f46e6509556974552e09733&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 s1ack3r07

Reputation: 0
• Posts: 21
• Joined: 16-September 09

# Basic Calculator program question

Posted 09 April 2011 - 11:54 PM

So I've got it set up where I can get an Int from a user and it will add the two numbers. I want to add more functionality to my program by allowing the user to enter a number 1-4 to determine which type of mathmatics will be applied to the two numbers entered. I was thinking If Else but wasn't sure exactly how to implement it. Any tips?

```package basiccalculator;

import javax.swing.*;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {

int x, y, sum, calc;

Scanner scn = new Scanner(System.in); //gets user's input

x = scn.nextInt();

y = scn.nextInt();

System.out.println("Enter 1 to Add, 2 to Subtract, 3 to Multiply, 4 to Divide");

calc = scn.nextInt();

//sum = x + y;

//System.out.println( x + "+" + y +"=" + sum);

}
}

```

Is This A Good Question/Topic? 0

## Replies To: Basic Calculator program question

### #2 s1ack3r07

Reputation: 0
• Posts: 21
• Joined: 16-September 09

## Re: Basic Calculator program question

Posted 10 April 2011 - 12:47 AM

Further experimenting led to this program.

```package basiccalculator;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

int x, y, sum, calc;

Scanner scn = new Scanner(System.in); //gets user's input

x = scn.nextInt();

y = scn.nextInt();

System.out.println("Enter 1 to Add, 2 to Subtract, 3 to Multiply, 4 to Divide");

calc = scn.nextInt();

if(calc == 1){
sum = x + y;
System.out.println( x +  " + " + y +" = " + sum);}
else if(calc == 2){
sum = x - y;
System.out.println(x +" - "+ y + " = "+ sum);}
else if(calc == 3){
sum = x * y;
System.out.println(x + " * "+ y + " = "+ sum);}
else if(calc ==4){
sum = x / y;
System.out.println(x + " / "+ y + " = "+ sum);}
else{
System.out.println("You didn't choose 1-4");
}
}
}

```

### #3 GregBrannon

• D.I.C Lover

Reputation: 2250
• Posts: 5,340
• Joined: 10-September 10

## Re: Basic Calculator program question

Posted 10 April 2011 - 03:02 AM

A switch statement is another common way to code this functionality, but your if/else construct (if it works) is fine.

### #4 CasiOo

• D.I.C Lover

Reputation: 1575
• Posts: 3,542
• Joined: 05-April 11

## Re: Basic Calculator program question

Posted 10 April 2011 - 03:39 AM

```switch ( calc ) {
case 1:
//Do this
break;

case 2:
//Do this
break;

case 3:
//Do this
break;

default:
System.out.println( "Wrong input!" );
break;
}

```