I visited other questions similar to mine but did not find the one that is applicable to me.
To lessen my line of codes instead of copy pasting that input process to my if else statement. I created a UInputs(); method that will get user inputs. So I can just call it whenever it is needed but i cant use the user inputted values inside UInputs().
import java.util.Scanner;
public class Calculator {
public static void UInputs(){
double num1, num2, num3, num4, num5;
Scanner scan = new Scanner(System.in);
System.out.print("1st Number: ");
num1 = scan.nextDouble();
System.out.print("2nd Number: ");
num2 = scan.nextDouble();
System.out.print("3rd Number: ");
num3 = scan.nextDouble();
System.out.print("4th Number: ");
num4 = scan.nextDouble();
System.out.print("5th Number: ");
num5 = scan.nextDouble();
}
public static void main (String[] args){
char Choice;
double num1, num2, num3, num4, num5;
System.out.println("\t_________________________________\n");
System.out.println("\t|\tMATH OPERATIONS\t\t|\n\t|\t[+]\tAddition\t|\n\t|\t[-]\tSubtraction\t|\n\t|\t[*]\tMultiplication\t|\n\t|\t[/]\tDivision\t|\n");
System.out.println("\t|_______________________________|\n");
System.out.print("\nEnter you Choice: ");
Scanner scan = new Scanner(System.in);
Choice = scan.nextLine().charAt(0);
if ( Choice == '+') {//ADDITION
System.out.println("================================\nAddition\n");
UInputs();
double answer = num1 + num2 + num3 + num4 + num5;
System.out.println("\nSum : " + answer );
System.out.println("================================\n");
}
else if (Choice == '-') {//SUBTRACTION
System.out.println("================================\nSubtraction\n");
System.out.print("1st Number: ");
num1 = scan.nextDouble();
System.out.print("2nd Number: ");
num2 = scan.nextDouble();
System.out.print("3rd Number: ");
num3 = scan.nextDouble();
System.out.print("4th Number: ");
num4 = scan.nextDouble();
System.out.print("5th Number: ");
num5 = scan.nextDouble();
double answer = num1 - num2 - num3 - num4 - num5;
System.out.println("\nDifference : " + answer );
System.out.println("================================\n");
}
Not the best answer I could have come up with but certainly some improvements to make the code easier to digest...
I changed UInputs to a method called calculate(). It now takes the function selected as input and then asks the user for 5 numbers. The function is then applied to the 5 numbers. Another way to perform this calculation would be to request a number from the user, return it, and sequentially apply the function to the returned number(s) to get a result... this would be nicer.
import java.util.Scanner;
public class Calculator {
private static final Scanner scan = new Scanner(System.in);
/**
* My initial thought here was that UInputs should return values
* and these should be cumulatively totalled.
* There's no need to hold the inputs in memory since
* once they're consumed, they're not longer needed.
*/
public static double calculate(char functionToApply) {
double[] inputs = new double[5];
// works for number of inputs up to 20 - could just print "number i: " here for simplicity.
for (int i=0; i<inputs.length; i++) {
String promptMessage = (i+1) + ""; // number
// postfixture (st, nd, rd, th)
switch (i+1) {
case 1: promptMessage = promptMessage+"st"; break;
case 2: promptMessage = promptMessage+"nd"; break;
case 3: promptMessage = promptMessage+"rd"; break;
default: promptMessage = promptMessage+"th"; break;
}
System.out.print(promptMessage + " Number: ");
inputs[i] = scan.nextDouble();
}
double result = 0;
for (int i=0; i<inputs.length; i++) {
switch (functionToApply) {
case '+': result = result + inputs[i]; break;
case '-': result = result - inputs[i]; break;
}
}
return result;
}
public static void main(String[] args) {
displayMenu();
char function;
System.out.print("\nEnter your Choice: ");
function = scan.nextLine().charAt(0);
String heading = "";
String lineLabel = "";
switch (function) {
case '+':
heading = "Addition";
lineLabel = "Sum";
break;
case '-':
heading = "Subtraction";
lineLabel = "Difference";
break;
}
System.out.println("================================\n" + heading + "\n");
System.out.println("\n" + lineLabel + " : " + calculate(function));
System.out.println("================================\n");
}
private static void displayMenu() {
System.out.println("\t_________________________");
System.out.println("\t|\tMATH OPERATIONS\t\t|");
System.out.println("\t|\t[+]\tAddition\t\t|");
System.out.println("\t|\t[-]\tSubtraction\t\t|");
System.out.println("\t|\t[*]\tMultiplication\t|");
System.out.println("\t|\t[/]\tDivision\t\t|");
System.out.println("\t|_______________________|\n");
}
}
This should be easier for you to extend/edit though.
Output:
_________________________
| MATH OPERATIONS |
| [+] Addition |
| [-] Subtraction |
| [*] Multiplication |
| [/] Division |
|_______________________|
Enter your Choice: +
================================
Addition
1st Number: 1
2nd Number: 2
3rd Number: 3
4th Number: 4
5th Number: 5
Sum : 15.0
================================
Process finished with exit code 0
Similarly for subtraction:
Enter your Choice: -
================================
Subtraction
1st Number: 10
2nd Number: 9
3rd Number: 1
4th Number: 0
5th Number: 0
Difference : -20.0
================================
you can create some kind of wrapper class
class MyNumberWrapper {
double num1;
double num2;
}
then UInput will look like this
public static MyNumberWrapper UInputs(){
MyNumberWrapper wrapper = new MyNumberWrapper();
Scanner scan = new Scanner(System.in);
System.out.print("1st Number: ");
wrapper.num1 = scan.nextDouble();
System.out.print("2nd Number: ");
wrapper.num2 = scan.nextDouble();
return wrapper;
}
then in your main function you can just use MyNumberWrapper wrapper = UInput() and access all variables with wrapper.num1, wrapper.num2 etc
Related
The goal is if the user puts an invalid option in three times, the program will tell the user to try again later and end the program. The code I have is below, I hope this makes sense, I am sorry if it doesn't. If you have any questions please let me know. I've also never asked a question here before so it may not be uploaded correctly.
public static void main(String[] args) {
int num1 = 0, num2 = 0, total = 0, option = 0, ex; // Creates integer variables
do {
Scanner sc = new Scanner(System.in);
System.out.println("\tBasic Math Calculator");// Title
System.out.println("\t---------------------");
System.out.println("\tEnter your choice from the following menu:");
System.out.println("\t------------------------------------------");
System.out.println("1.\tAddition");// All the menu options
System.out.println("2.\tSubtraction");
System.out.println("3.\tMultiplication");
System.out.println("4.\tDivision");
System.out.println("5.\tGenerate Random number");
System.out.println("6.\tQuit");
boolean valid;
do {
valid = true;
try {
option = Integer.parseInt(sc.nextLine());// Stores the users answers
if (option < 1 || option > 6) {
System.out.println("Invalid input. Please try again.");
valid = false;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please try again.");
valid = false;
}
} while (!valid);
switch (option) {// The math and titles for every option
case 1:
System.out.println("You chose to add two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 + num2;
System.out.println("The two numbers you chose added together is " + total);
break;
case 2:
System.out.println("You chose to subtract two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 - num2;
System.out.println("The two numbers you chose subtracted together is " + total);
break;
case 3:
System.out.println("You chose to multiply two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 * num2;
System.out.println("The two numbers you chose multiplied together is " + total);
break;
case 4:
System.out.println("You chose to divide two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 / num2;
if (num2 == 0) {
System.out.println("You can't divide by 0");
} else {
System.out.println("The two numbers you chose divided together is " + total + "with a quotient of "
+ (num1 % num2));
}
break;
case 5:
System.out.println("You chose to get two random numbers: ");
System.out.println("Enter your lower limit:");
num1 = sc.nextInt();
System.out.println("Enter your upper limit:");
num2 = sc.nextInt();
total = num1 + num2;
Random rand = new Random();
int rand_int1 = rand.nextInt(num1 + num2);
System.out.println("The random intigers is: " + rand_int1);
break;
case 6:// If the user wants to quit
ex = 2;
break;
default:// Tells their option was incorrect
System.out.println("Invalid choice, choice " + option + " was not an option");
}
System.out.println("Do you want to continue?1.Yes 2.No");// Asks the user if they want to proceed
ex = sc.nextInt(); // A thank you message for the user for running the program
} while (ex == 1);
System.out.println("-----------------------------------------");
System.out.println("Thank you for using the basic calculator!");
}
You can do so by creating a nested loop before the start if switch statement:
//...
System.out.println("6.\tQuit");
boolean valid;
do {
valid = true;
try {
option = Integer.parseInt(sc.nextLine());// Stores the users answers
if (option < 1 || option > 6) {
System.out.println("Invalid input. Please try again.");
valid = false;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please try again.");
valid = false;
}
} while (!valid);
switch (option) {// The math and titles for every option
//...
A sample run after this change:
Basic Math Calculator
---------------------
Enter your choice from the following menu:
------------------------------------------
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Generate Random number
6. Quit
a
Invalid input. Please try again.
9
Invalid input. Please try again.
4
You chose to divide two numbers:
Enter your first number:
Check the full code at ideone.
You don't have to use the valid and do-while for checking times of invalid input
If you want to quit the program after 3 invalid option entered by user , you have to increment the count of ex and change the condition at while loop.
Initialize ex=1
Change case 6 and default as below
case 6:// If the user wants to quit
System.exit(0);
break;
default:
ex = ex+1;
break;
and
while condition as below
while (ex <4); //
Following is the full code
public static void main(String[] args) {
int num1 = 0, num2 = 0, total = 0, ex= 1; // Creates integer variables
do {
Scanner sc = new Scanner(System.in);
System.out.println("\tBasic Math Calculator");// Title
System.out.println("\t---------------------");
System.out.println("\tEnter your choice from the following menu:");
System.out.println("\t------------------------------------------");
System.out.println("1.\tAddition");// All the menu options
System.out.println("2.\tSubtraction");
System.out.println("3.\tMultiplication");
System.out.println("4.\tDivision");
System.out.println("5.\tGenerate Random number");
System.out.println("6.\tQuit");
switch (option) {// The math and titles for every option
case 1:
System.out.println("You chose to add two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 + num2;
System.out.println("The two numbers you chose added together is " + total);
break;
case 2:
System.out.println("You chose to subtract two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 - num2;
System.out.println("The two numbers you chose subtracted together is " + total);
break;
case 3:
System.out.println("You chose to multiply two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 * num2;
System.out.println("The two numbers you chose multiplied together is " + total);
break;
case 4:
System.out.println("You chose to divide two numbers: ");
System.out.println("Enter your first number:");
num1 = sc.nextInt();
System.out.println("Enter your second number:");
num2 = sc.nextInt();
total = num1 / num2;
if (num2 == 0) {
System.out.println("You can't divide by 0");
} else {
System.out.println("The two numbers you chose divided together is " + total + "with a quotient of "
+ (num1 % num2));
}
break;
case 5:
System.out.println("You chose to get two random numbers: ");
System.out.println("Enter your lower limit:");
num1 = sc.nextInt();
System.out.println("Enter your upper limit:");
num2 = sc.nextInt();
total = num1 + num2;
Random rand = new Random();
int rand_int1 = rand.nextInt(num1 + num2);
System.out.println("The random intigers is: " + rand_int1);
break;
case 6:// If the user wants to quit
System.out.println("Thank you for using the basic calculator!");
System.exit(0);
break;
default:// Tells their option was incorrect
ex=ex+1;
System.out.println("Invalid choice, choice " + option + " was not an option");
}
System.out.println("Do you want to continue?1.Yes 2.No");// Asks the user if they want to proceed
//ex = sc.nextInt(); // A thank you message for the user for running the program
} while (ex<4);
System.out.println("-----------------------------------------");
System.out.println("Thank you for using the basic calculator!");
}
Edited
Below is the sample output
Basic Math Calculator
---------------------
Enter your choice from the following menu:
------------------------------------------
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Generate Random number
6. Quit
7
Invalid choice, choice 7 was not an option
Please try again
Basic Math Calculator
---------------------
Enter your choice from the following menu:
------------------------------------------
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Generate Random number
6. Quit
7
Invalid choice, choice 7 was not an option
Please try again
Basic Math Calculator
---------------------
Enter your choice from the following menu:
------------------------------------------
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Generate Random number
6. Quit
7
Invalid choice, choice 7 was not an option
Please try again
-----------------------------------------
Thank you for using the basic calculator!
Bear with me.
After creating the if-else statement, every time I check to see the else statement if it can go back to the menu if the string isn't true it always ends up in an error like:Exception in thread "main" java.lang.NumberFormatException: For input string: ""
public class geo {
public static void main(String[] args){
byte choice = 0;
int num1 = 0;
int num2 = 0;
int num3 = 0;
float num4 ;
double result1 = 0;
boolean quit;
String UnitofMeasurement;
String feet = "feet";
String inches = "inches";
DecimalFormat format = new DecimalFormat("0.00");
Scanner key = new Scanner(System.in);
while (choice != 1) {
System.out.println("\t1. Determine the perimeter of a square");
switch (choice){
case 1:
System.out.println("The perimeter of a square is computed
by multiplying the measure of one side by 4.");
System.out.println("Enter the unit of measurement(i.e. inches/feet):");
UnitofMeasurement = key.next();// gets the unit of measurement
if(UnitofMeasurement.equals(feet)||UnitofMeasurement.equals(inches)){
System.out.println("You have chosen " + UnitofMeasurement + " as the unit of measurement.");
System.out.println("Enter the measurement of one side: ");
num1 = key.nextInt();
System.out.println("Side of the square: "+ format.format(num1));
key.nextLine();
result1 = num1 * 4;
System.out.println("Perimeter of the square = "+ format.format(result1) +" "+ UnitofMeasurement);
}
else
{
System.out.println("Please only enter feet/inches");
}
enter();
break;
default;
If that is all the code you write your compilation errors are in enter(); and default;
I think you have to implement enter() method in your class, and change the last error to default:
See this code below, without compilation errors:
public class geo {
public static void main(String[] args) {
byte choice = 0;
int num1 = 0;
int num2 = 0;
int num3 = 0;
float num4;
double result1 = 0;
boolean quit;
String UnitofMeasurement;
String feet = "feet";
String inches = "inches";
DecimalFormat format = new DecimalFormat("0.00");
Scanner key = new Scanner(System.in);
while (choice != 1) {
System.out.println("\t1. Determine the perimeter of a square");
switch (choice) {
case 1:
System.out.println("The perimeter of a square is computed by multiplying the measure of one side by 4.");
System.out.println("Enter the unit of measurement(i.e. inches/feet):");
UnitofMeasurement = key.next();// gets the unit of measurement
if (UnitofMeasurement.equals(feet) || UnitofMeasurement.equals(inches)) {
System.out.println("You have chosen " + UnitofMeasurement + " as the unit of measurement.");
System.out.println("Enter the measurement of one side: ");
num1 = key.nextInt();
System.out.println("Side of the square: " + format.format(num1));
key.nextLine();
result1 = num1 * 4;
System.out.println("Perimeter of the square = " + format.format(result1) + " " + UnitofMeasurement);
} else {
System.out.println("Please only enter feet/inches");
}
break;
default:
}
}
}
}
Trying to call the total value from the operatorSelection class while that class references what the user enters as the operator.
I want it to end up coming out as number1 (operator chosen) number2...= total.
Not sure how to call class so that it prints the " System.out.println(number1+" "+operator+" "+number2+" "+operator+" "+number2+ " = "+ total); " correctly.
Any knowledge would be greatly appreciated on the subject.
Thanks.
import java.util.Scanner;
class NumbersEntered
{
public void operatorSeletion(double number1, double number2, double number3, char operator)
{
double total = 0;
switch(operator)
{
case '+':
total = number1 + number2 + number3;
break;
case '-':
total = number1 - number2 - number3;
break;
case '*':
total = number1 * number2 * number3;
break;
case '/':
total = number1 / number2 / number3;
break;
default:
System.out.println("You have entered incorrectly. Please try again.");
return;
}
}
}
public class JavaPresentation_KS {
public static void main(String[] args) {
NumbersEntered nums = new NumbersEntered();
Scanner equation = new Scanner(System.in);
System.out.println("Enter first number: ");
double number1 = equation.nextDouble();
System.out.println("Enter second number: ");
double number2 = equation.nextDouble();
System.out.println("Enter third number: ");
double number3 = equation.nextDouble();
System.out.println("Enter an operator (+, -, *, /): ");
char operator = equation.next().charAt(0);
System.out.println(number1+" "+operator+" "+number2+" "+operator+" "+number2+ " = "+ total);
}
}
Your problem is that you declare the total variable within the operatorSeletion method, and you try to access it without specifying it's location. You need to declare the total variable as a field, and then access it at its location (new NumbersEntered().total). Also, you never invoke operatorSeletion, which might help ;)
class NumbersEntered {
public double total = 0; //declare as accessable field
public void operatorSeletion(double number1, double number2, double number3, char operator)
{
switch(operator)
{
case '+':
total = number1 + number2 + number3;
break;
case '-':
total = number1 - number2 - number3;
break;
case '*':
total = number1 * number2 * number3;
break;
case '/':
total = number1 / number2 / number3;
break;
default:
System.out.println("You have entered incorrectly. Please try again.");
return;
}
}
}
public class JavaPresentation_KS {
public static void main(String[] args) {
NumbersEntered nums = new NumbersEntered();
Scanner equation = new Scanner(System.in);
System.out.println("Enter first number: ");
double number1 = equation.nextDouble();
System.out.println("Enter second number: ");
double number2 = equation.nextDouble();
System.out.println("Enter third number: ");
double number3 = equation.nextDouble();
System.out.println("Enter an operator (+, -, *, /): ");
char operator = equation.next().charAt(0);
nums.operatorSeletion(number1, number2, number3, operator);
//invoke the method
System.out.println(number1 + " " + operator + " " + number2 + " " + operator + " " + number2 + " = " + nums.total);
//Access at location (nums.total)
}
I've writter a calculator program in Java, after a user is done with work,
I want this to happen:
i'll ask if he wants to do more operations, if yes, the program should return to choice input. If no, break the program.
What lines should I add to the code? This is my calc program:
import java.util.*;
class calc
{
public static void main(String ar[])
{
char choice;
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO SHREYDAN'S CALC 1.0");
System.out.println(" ");
System.out.println("YOU CAN DO THE FOLLOWING:");
System.out.println("+: ADDITION");
System.out.println("-: SUBTRACTION");
System.out.println("*: PRODUCT");
System.out.println("/: QUOTIENT");
System.out.println("#: SQUARE ROOT");
System.out.println("^: POWER");
System.out.println("$: ROUND OFF");
System.out.println("!: FACTORIAL");
System.out.println(" ");
System.out.println("ENTER CHOICE");
choice=in.next().charAt(0);
switch(choice)
{
case '+':
System.out.println("ENTER 2 NUMBERS, USER");
double a=in.nextDouble();
double b=in.nextDouble();
System.out.println("SUM = "+(a+b));
break;
case '-':
System.out.println("ENTER 2 NUMBERS, USER");
double c=in.nextDouble();
double d=in.nextDouble();
System.out.println("SUBTRACTING "+d+" FROM "+c+" ... DIFFERENCE = "+(c-d));
break;
case '*':
System.out.println("ENTER 2 NUMBERS, USER");
double e=in.nextDouble();
double f=in.nextDouble();
System.out.println("PRODUCT = "+(e*f));
break;
case '/':
System.out.println("ENTER 2 NUMBERS, USER");
double g=in.nextDouble();
double h=in.nextDouble();
System.out.println("DIVIDING "+g+" BY "+h+" = "+(g/h));
break;
case '#':
System.out.println("ENTER NO. FOR SQAURE ROOT:");
double sqrt=in.nextDouble();
System.out.println("SQUARE ROOT OF "+sqrt+" = "+Math.sqrt(sqrt));
break;
case '^':
System.out.println("ENTER BASE, USER");
double base=in.nextDouble();
System.out.println("ENTER POWER, USER");
double power=in.nextDouble();
System.out.println(base+" RAISED TO POWER "+power+" = "+Math.pow(base,power));
break;
case '$':
System.out.println("ENTER DECIMAL VALUES TO ROUND OFF");
double deci=in.nextDouble();
System.out.println("THE NEAREST ROUND OFF = "+Math.round(deci));
break;
case '!':
System.out.println("ENTER A NO. FOR FACTORIAL:");
int fact=in.nextInt();
int factorial=1;
for(int i=fact; i>=1;i--)
factorial=factorial*i;
System.out.println(fact+"! = "+factorial);
break;
default:
System.out.println("WRONG CHOICE USER");
}
}
}
while loops are your best bet for this type of problem, just think of a condition which the user can choose to toggle the boolean condition.
for example if the user chooses no on the "continuing of operations" choice, then toggle the boolean to false and exit the while loop to end the program.
You need to wrap the program logic in a loop.
Try using a while loop
public static void main(String args[])
{
boolean doContinue = true;
while(doContinue){
char choice;
Scanner in = new Scanner(System.in);
//program logic
//when the user enters a command to end
// set continue=false
}
}
Maybe put the entire program inside a while loop with a continue to run bool condition which could be set false when they want to quit
You can try the following:
import java.util.*;
class calc {
public static void main(String ar[]) {
char choice;
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO SHREYDAN'S CALC 1.0");
System.out.println(" ");
boolean loop = true;
while (loop) {
System.out.println("YOU CAN DO THE FOLLOWING:");
System.out.println("+: ADDITION");
System.out.println("-: SUBTRACTION");
System.out.println("*: PRODUCT");
System.out.println("/: QUOTIENT");
System.out.println("#: SQUARE ROOT");
System.out.println("^: POWER");
System.out.println("$: ROUND OFF");
System.out.println("!: FACTORIAL");
System.out.println(" ");
System.out.println("ENTER CHOICE");
choice = in.next().charAt(0);
switch (choice) {
case '+':
System.out.println("ENTER 2 NUMBERS, USER");
double a = in.nextDouble();
double b = in.nextDouble();
System.out.println("SUM = " + (a + b));
break;
case '-':
System.out.println("ENTER 2 NUMBERS, USER");
double c = in.nextDouble();
double d = in.nextDouble();
System.out.println("SUBTRACTING " + d + " FROM " + c + " ... DIFFERENCE = " + (c - d));
break;
case '*':
System.out.println("ENTER 2 NUMBERS, USER");
double e = in.nextDouble();
double f = in.nextDouble();
System.out.println("PRODUCT = " + (e * f));
break;
case '/':
System.out.println("ENTER 2 NUMBERS, USER");
double g = in.nextDouble();
double h = in.nextDouble();
System.out.println("DIVIDING " + g + " BY " + h + " = " + (g / h));
break;
case '#':
System.out.println("ENTER NO. FOR SQAURE ROOT:");
double sqrt = in.nextDouble();
System.out.println("SQUARE ROOT OF " + sqrt + " = " + Math.sqrt(sqrt));
break;
case '^':
System.out.println("ENTER BASE, USER");
double base = in.nextDouble();
System.out.println("ENTER POWER, USER");
double power = in.nextDouble();
System.out.println(base + " RAISED TO POWER " + power + " = " + Math.pow(base, power));
break;
case '$':
System.out.println("ENTER DECIMAL VALUES TO ROUND OFF");
double deci = in.nextDouble();
System.out.println("THE NEAREST ROUND OFF = " + Math.round(deci));
break;
case '!':
System.out.println("ENTER A NO. FOR FACTORIAL:");
int fact = in.nextInt();
int factorial = 1;
for (int i = fact; i >= 1; i--)
factorial = factorial * i;
System.out.println(fact + "! = " + factorial);
break;
default:
System.out.println("WRONG CHOICE USER");
}
System.out.println("Want to calculate more?Y/N");
loop = in.next().charAt(0) == 'Y';
}
}
}
So this is my code for a simple calculator. It works for the most part, and I'm trying to create a loop at the end of the operation to allow a user the chance to choose to do another operation or exit. So far I've tried adding a nested if loop but I keep getting an error. Any help would be helpful. I'm fairly new.
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
// Introduction to Calculator providing instructions to user
Scanner input = new Scanner(System.in);
int num1, num2, ans, Y, N;
System.out.println("Welcome to Simple Calculator: Please enter \n" +
"which mathimatical operation you would like to \n "
+ "accomplish by imputing 1-addition, 2-subtraction \n"
+ "3-multiplication, 4-division, 5-modulo");
int Operation = input.nextInt();
//Operation sequence for user to input which operation they would like to accomplish
if (Operation == 1) {
System.out.println("You have Choosen Addition");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 + num2;
System.out.print("Answer is: " + ans);
/*
* Right here in the following I want to put something in to make this loop
* so the user can make multiple calculation.
* So far nothing has worked.
*/
System.out.println("Would you like to do another calculation?\n " +
"Enter Y for Yes or N to Exit");
}else if (Operation == 2){
System.out.println("You have Choosen Subtraction");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 - num2;
System.out.print("Answer is: " + ans);
}else if (Operation == 3){
System.out.println("You have Choosen Multiplication");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 * num2;
System.out.print("Answer is: " + ans);
}else if (Operation == 4){
System.out.println("You have Choosen Division");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 / num2;
System.out.print("Answer is: " + ans);
}else if (Operation == 5){
System.out.println("You have Choosen Modulo");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 % num2;
System.out.print("Answer is: " + ans);
}else{
System.out.print("Invalid Operation, please try again.");
}
}
}
You're on the right track here. I would suggest using a do-while loop. So encase the entire part beginning with if (Operation == 1) { all the way down to your final else statement like this:
do {
/*
if (Operation == 1) {
...
...
...
else {
...
}
*/
System.out.print("Would you like to do another calculation? [Y/n] ");
} while (input.nextLine().toUpperCase().charAt(0) == 'Y');
I would put the entire thing in a while loop and at the end ask if they want to continue
yes - it goes back through the loop
no - you have it break out of the loop