Desired output: Hello, I am trying to make a program that does addition, subtraction, multiplication, and division and loops until you press 'e' to exit the loop.
So, I want it to look something like this:
A. Addition
B. Subtraction
C. Multiplication
D. Division
E. Exit
Please enter your selection, enter E to end:
//let's say they enter a, and want to add 5 plus 5
Enter your first number:
Enter your second number:
5 + 5 = 10.0
Please enter your selection, enter E to end:
//This looping part is what I want to happen! But my program just ends, and I'm not
sure how to fix it
Issue: My problem is that once you enter what operation you want, it only does the arithmetic once and then it displays my exit message and ends, but that is only supposed to happen when the user enters 'e' but the rest works, I think!
Here is my code
import java.util.Scanner;
public class Calculator_Loop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
char selection;
char choice = 'E';
double num_1;
double num_2;
double result;
System.out.println("A. Addition\nB. Subtraction\nC. Multiplication\nD. Division \n\nE. Exit");
//System.out.println("\nPlease enter your selection, enter E to end:");
//selection = input.next().charAt(0);
//choice = Character.toUpperCase(selection);
while(choice != 'E')
System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = Character.toUpperCase(selection);
if(choice == 'A') {
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
}
if(choice == 'B'){
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 - num_2;
System.out.println(result);
}
if(choice == 'C'){
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 * num_2;
System.out.println(result);
}
if(choice == 'D'){
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 / num_2;
System.out.println(result);
}
System.out.println("Thank you, have a nice day!");
}
}
Am I doing something wrong with the brackets? Or is there something I'm missing for the loop to work? Any help is appreciated, thanks!
Welcome to SO.
Problem is (as far as I can see) that you have nothing/only the print line in your while loop.
while(true) {
do things
}
Java allows while loops without brackets, but at maximum one line (and I recommend doing them for one line too, but that is debattable), as soon as you need several lines, you need brackets and should have according indentation.
You need to surround your intended while loop with brackets to make it work the way you want:
while (choice != 'E') {
System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = Character.toUpperCase(selection);
switch (choice) {
case 'A':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
break;
case 'B':
// ...
}
}
System.out.println("Thank you, have a nice day!");
Currently, your while loop will spin forever (I think), because the seed value for choice is being set to E.
Side note: Consider using a switch statement to handle the various case values for the choice.
Instead of using the if conditions, please use the while loop and switch condition. if the input value is other than the A, B, C or D then exit from the code.
Code takes only the first character of your input and enters into switch case, where it will compare the input with the required conditions.
public class Calculator_Loop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String choice = "";
double num_1;
double num_2;
double result;
System.out.println("A. Addition\nB. Subtraction\nC. Multiplication\nD. Division \n\nE. Exit");
/*System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = input.next().substring(0, 1).toUpperCase();*/
outer: while (true) {
System.out.println("\nPlease enter your selection, enter E to end:");
choice = input.next();
choice = choice.substring(0, 1).toUpperCase();
switch (choice) {
case "A":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
break;
case "B":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 - num_2;
System.out.println(result);
break;
case "C":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 * num_2;
System.out.println(result);
break;
case "D":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 / num_2;
System.out.println(result);
break;
default:
System.out.println("Thank you, have a nice day!");
break outer;
}
}
}
}
You class has two problems.
One is the missing brace that others metioned.
The other is that it will never enter the loop as the condition is allways false.
So to make sure that the loop is entered at least once you need an endcondition. a do-while construct instead of your startcondition.
So I changed your while loop into a do-while. By that I added the missing curly.
I also changed your if's to a switch as a choice calls for it.
And I moved the question into the loop, so the user gets the information in every iteration.
import java.util.Scanner;
public class Calculator_Loop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
char selection;
char choice = 'E';
double num_1;
double num_2;
double result;
do {
System.out.println("A. Addition\nB. Subtraction\nC. Multiplication\nD. Division \n\nE. Exit");
//System.out.println("\nPlease enter your selection, enter E to end:");
//selection = input.next().charAt(0);
//choice = Character.toUpperCase(selection);
System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = Character.toUpperCase(selection);
switch (choice) {
case 'A':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
break;
case 'B':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 - num_2;
System.out.println(result);
break;
case 'C':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 * num_2;
System.out.println(result);
break;
case 'D':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 / num_2;
System.out.println(result);
break;
}
} while (choice != 'E');
System.out.println("Thank you, have a nice day!");
}
}
Related
Somehow I got operator looping till I get correct input. When i try to put num1 or num2 in "if" statement, It says that I cannot convert "int" to "boolean". Please help
public class main {
public static void main(String[] args) {
int num1;
int num2;
String operator;
Scanner scan = new Scanner(System.in);
System.out.print("tell me first number: ");
num1 = scan.nextInt(); //<--input only numbers, loop if not
System.out.print("tell me second number: ");
num2 = scan.nextInt(); //<--input only numbers, loop if not
//////////////////operator////////////////////////
System.out.print("tell me operator: ");
operator = scan.next();
while(true) {
if(operator.equals("+")) {
System.out.println("answer is: " +(num1 + num2));
break;
}
else if(operator.equals("-")) {
System.out.println("answer is: " +(num1 - num2));
break;
}
else if(operator.equals("*")) {
System.out.println("answer is: " +(num1 * num2));
break;
}
else if(operator.equals("/")) {
System.out.println("answer is: " +(num1 / num2));
break;
}
else {
System.out.print("wrong input! try again!: ");
operator = scan.next();
}
}
}
}
Try this.
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
With this, wrong answer was looping till i got correct input, but I could not get it to print me "Wrong Input! Try again!: " with wrong input without starting to loop infinitely, so i tried to edit and came up with this.
//////////////////first number////////////////////
System.out.print("tell me first number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong Input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num1 = scan.nextInt();
//////////////////second number///////////////////
System.out.print("tell me second number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num2 = scan.nextInt();
Somehow it helped lol.
Thanks #英語は苦手 for help.
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!
I am new to Java, and I'm doing a calculator APP.
I'm trying to get my calculator to keep prompting the user for the correct answer (typing Y or N) after the else statement following 'Invalid Input'.
I want the program to continue with the calculations after the correct input is finally entered.
I have played around with an embedded while loop, but ended up with an infinite loop or a loop that terminates with no resolution. The code is below.
import java.util.Scanner;
class Calculate {
public static void.main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
double num1, num2;
String choice;
boolean youDecide = true;
while(youDecide == true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
char operator = userinput.next().charAt(0);
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch(operator)
{
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
if(num2 == 0)
System.out.println("Math error! A number cannot be divided by zero.");
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
return;
}
System.out.println("*************************************************************************");
System.out.println("The answer is: " + "\n" + output);
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
youDecide = true;
}
else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
}
else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
youDecide = false;
}
}
}
}
I've made some changes and comments to your code
import java.util.Scanner;
class Calculator {
public static void main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
double num1, num2;
String choice;
//the "youDecide" variable is not needed at all
while (true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
char operator = userinput.next().charAt(0);
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch (operator) {
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
if (num2 == 0) {
System.out.println("Math error! A number cannot be divided by zero.");
}
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
continue; //changed from "return" you don't want to exit, just to skip to the next execution of the loop
}
System.out.println("*************************************************************************");
System.out.println("The answer is: " + "\n" + output);
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if (choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
} else if (choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
} else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
}
}
}
}
You need a while loop to ensure the value is correct.
Due the logic into your code you need to do when the user type the char, otherwise you have to change many lines of code, or ask for all values again.
I think for a begginer the easiest way is using this loop:
char operator;
while(true) {
operator = userinput.next().charAt(0);
if(operator=='+' || operator == '-' || operator == '*' || operator == '/') {
break;
}else {
System.out.println("Please enter a valid operator: ");
}
}
Exists many ways more elegant to do this. But I think for a begginer is the easiest way to understand and implement the code.
This loop is only to ensure the user type a valid character. While the character is not one of them, the loop will be iterating.
You have to place this code just below this line where you ask for a valid operator.
After adding the edits suggested by J.F. and Javaman along with some research, I was able to solve the problem by adding the following lines to my code:
import java.util.InputMismatchException;
import java.util.Scanner;
class Calculator {
public static void main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
char operator;
double num1, num2;
String choice;
while(true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
while(true) {
operator = userinput.next().charAt(0);
if(operator == '+' || operator == '-' || operator == '*' || operator == '/') {
break;
}else {
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
}
}
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch(operator) {
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
continue;
}
System.out.println("*************************************************************************");
if(num2 == 0) {
System.out.println("Math error! A number cannot be divided by zero.");
}else {
System.out.println("The answer is: " + "\n" + output);
}
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
}else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
}else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
**while (!("Y").equalsIgnoreCase(choice) && !("N").equalsIgnoreCase(choice)) {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
}else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);**
}
}
}
}
}
}
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
The code will compile, but there seems to be an error with my menu. The user will select one of the choices and the program should execute, but When choosing a selection nothing happens. Here is the code:
import java.util.Scanner;
class Tutorial{
public static void main(String args[]){
Geek myGeek = new Geek("Geek");
System.out.println("Command Options: ");
System.out.println("a: Geek's Name");
System.out.println("b: Num Questions Asked");
System.out.println("c: All Numbers Are the Same");
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("?: Display");
System.out.println("q: Quit");
Scanner scan = new Scanner(System.in);
String choice = scan.nextLine();
do {
switch (choice){
case "a":
myGeek.getName();
break;
case "b":
myGeek.getnumberofQuestions();
break;
case "c":
System.out.println("Enter the first number");
int input1 = scan.nextInt();
System.out.println("Enter the second number");
int input2 = scan.nextInt();
System.out.println("Enter the third number");
int input3 = scan.nextInt();
myGeek.allTheSame(input1, input2, input3);
break;
case "d":
System.out.println("Enter the first number");
int num1 = scan.nextInt();
System.out.println("Enter the second number");
int num2 = scan.nextInt();
myGeek.sum(num1, num2);
break;
case "e":
System.out.println("Enter a string: ");
String word1 = scan.nextLine();
System.out.println("Enter an integer: ");
int numberOfTimes = scan.nextInt();
System.out.println("Enter the third number");
myGeek.repeat(word1, numberOfTimes);
break;
case "f":
System.out.println("Enter a string: ");
String word2 = scan.nextLine();
myGeek.isPalindrome(word2);
break;
case "?":
System.out.println("Command Options: ");
System.out.println("a: Geek's Name");
System.out.println("b: Num Questions Asked");
System.out.println("c: All Numbers Are the Same");
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("?: Display");
System.out.println("q: Quit");
break;
} }while (choice != "q");
}
}
Here is the what it looks like when run:
http://i.imgur.com/O6SgyH1.png
Well, you definitely need to move code which gets input inside the loop :
String choice = null;
Scanner scan = new Scanner(System.in);
do {
choice = scan.nextLine();
switch (choice) {
case "a":
.........
} // end of switch
} while (!choice.equals("q")); // end of loop
Otherwise, you input once and switch on that input indefinitely (unless it is "q")
Edit :
You also need to change terminating condition to while (!choice.equals("q"));
for it to work.
This also depends on which version of the JDK they're using.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
http://java.dzone.com/articles/new-java-7-feature-string
Few things:
You read input only once - outside of do..while - probably not what you want (otherwise you'd be stuck in infinite loop).
most likely the intent was this: while ((choice = scan.nextLine()) != "q");
As far as why you don't see anything when running, it depends on what myGeek.getName() does.
As name suggests its a simple getter, if this is a case then it returns the name but it does not print anything on the screen.
i think you want something like this:
....
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("?: Display");
System.out.println("q: Quit");
String choice;
do {
System.out.println("Select something: ");
Scanner scan = new Scanner(System.in);
choice = scan.nextLine();
switch (choice){
case "a":
myGeek.getName();
break;
case "b":
myGeek.getnumberofQuestions();
break;
case "c":
System.out.println("Enter the first number");
int input1 = scan.nextInt();
System.out.println("Enter the second number");
....
if not --->>>> for what you need do -> while??
and check, if your java is 7 or heighter, and check your getMethods() -> if thay return anything
One issue you have, as mentioned by #rgettman, is that comparing Strings in Java using == or != will compare the Object reference of the String not the value; basically are the two Strings the same Object? In this case (and most cases) you want to compare the value.
Change while (choice != "q"); to while (!choice.equals("q")); to compare the values.
A slightly different explanation:
Right now you are entering a character, say "a", matching your case for "a" and breaking from the switch/case. However when your program gets to the while it basically checks whether choice is "q" so your program goes back into the do/while loop.
Your loop (do {} while(condition)) will loop infinite when you enter some string different "q" because condition always is true.
try with :
while (!choice.equals("q")) {
switch (choice) {
case "a":
myGeek.getName();
break;
case "b":
myGeek.getnumberofQuestions();
break;
case "c":
System.out.println("Enter the first number");
int input1 = scan.nextInt();
System.out.println("Enter the second number");
int input2 = scan.nextInt();
System.out.println("Enter the third number");
int input3 = scan.nextInt();
myGeek.allTheSame(input1, input2, input3);
break;
case "d":
System.out.println("Enter the first number");
int num1 = scan.nextInt();
System.out.println("Enter the second number");
int num2 = scan.nextInt();
myGeek.sum(num1, num2);
break;
case "e":
System.out.println("Enter a string: ");
String word1 = scan.nextLine();
System.out.println("Enter an integer: ");
int numberOfTimes = scan.nextInt();
System.out.println("Enter the third number");
myGeek.repeat(word1, numberOfTimes);
break;
case "f":
System.out.println("Enter a string: ");
String word2 = scan.nextLine();
myGeek.isPalindrome(word2);
break;
case "?":
System.out.println("Command Options: ");
System.out.println("a: Geek's Name");
System.out.println("b: Num Questions Asked");
System.out.println("c: All Numbers Are the Same");
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("?: Display");
System.out.println("q: Quit");
break;
}
}