I am writing a calculator program that takes inputs from 0-9 and outputs the results in both numerical from and in plain english (Ex: Two plus three equals 5). I have gotten it to be able to print out the result in words but I am now stuck on how to get it to print out the original problem in numerical form. The output must include both the result in numbers and in words.
The numbers have already been converted into strings through a switch statement but is there anyway I can print out the original problem? If not would I have to completely restructure this instead? Any help would be appreciated I have been stuck on this for a while now.
Here is my code
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char operation;
int num1, num2;
//Asks for user to input first number
System.out.println("Please enter the first number (0-9)");
num1 = input.nextInt();
//Asks user for an operation
System.out.println("Please enter the type of operation that you would like to perform");
operation = input.next().charAt(0);
//Asks user to input the second number
System.out.println("Please enter the second number (0-9)");
num2 = input.nextInt();
//Limits the numbers to the range of 0-9
if(num1 > 9 || num2 > 9){
System.out.println("Invalid Digit!!");
System.exit(0);}
//An array that converts number into a string
String num[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
switch(operation){
case '-': //Subtraction conversion
System.out.println(num[num1]+" minus "+num[num2] + " is " + (num1-num2));
break;
case '+': //Addition conversion
System.out.println(num[num1]+" plus "+num[num2] + " is " + (num1+num2));
break;
case '*': //Multipication conversion
System.out.println(num[num1]+" multiplied by "+num[num2] + " is " + (num1*num2));
break;
case '/': //Division conversion
System.out.println(num[num1]+" divided by "+num[num2] + " is " + (num1/num2));
break;
case '^': //Exponentiation conversion
if(num2 == 0){ //checks to see if the second number entered is 0
System.out.println("Error: Cannot divide by Zero"); //Divide by Zero error message
break;}
System.out.println(num[num1]+" to the power of "+num[num2] + " is " + Math.pow(num1,num2));
break;
default:
System.out.println("Error: Invalid Operation Entered"); }
}
}
Its very simple, I think you are getting confused. Consider following points:
You have original numbers saved in num1 and num2, so if you want to show the original numbers in integer form, then just use num1 instead of num[num1]
You are checking for zero division when finding exponent. You should shift this check to division case.
Replace your switch like this:
switch(operation){
case '-': //Subtraction conversion
System.out.println(num[num1]+" minus "+num[num2] + " is " + (num1-num2));
System.out.println(num1+" - "+num2 + " = " + (num1-num2));
break;
case '+': //Addition conversion
System.out.println(num[num1]+" plus "+num[num2] + " is " + (num1+num2));
System.out.println(num1+" + "+num2 + " = " + (num1+num2));
break;
case '*': //Multipication conversion
System.out.println(num[num1]+" multiplied by "+num[num2] + " is " + (num1*num2));
System.out.println(num1+" * "+num2 + " = " + (num1*num2));
break;
case '/': //Division conversion
if(num2 == 0){ //checks to see if the second number entered is 0
System.out.println("Error: Cannot divide by Zero"); //Divide by Zero error message
break;
}
System.out.println(num[num1]+" divided by "+num[num2] + " is " + (num1/num2));
System.out.println(num1+" / "+num2 + " = " + (num1/num2));
break;
case '^': //Exponentiation conversion
System.out.println(num[num1]+" to the power of "+num[num2] + " is " + Math.pow(num1,num2));
System.out.println(num1+" ^ "+num2 + " = " + Math.pow(num1,num2));
break;
default:
System.out.println("Error: Invalid Operation Entered");
}
See if the below print statements helps
case '-': //Subtraction conversion
System.out.println(num[num1]+" minus "+num[num2] + " is " + (num1-num2));
System.out.println(num1+" "+operation + " "+num2+ "="+(num1 - num2));
break;
case '+': //Addition conversion
System.out.println(num[num1]+" plus "+num[num2] + " is " + (num1+num2));
System.out.println(num1+" "+operation + " "+num2+ "="+(num1 + num2));
break;
is it this what you are looking for? for example for 9 + 9 your output will be:
nine plus nine is 18 9 + 9 = 18
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char operation;
int num1, num2;
//Asks for user to input first number
System.out.println("Please enter the first number (0-9)");
num1 = input.nextInt();
//Asks user for an operation
System.out.println("Please enter the type of operation that you would like to perform");
operation = input.next().charAt(0);
//Asks user to input the second number
System.out.println("Please enter the second number (0-9)");
num2 = input.nextInt();
//Limits the numbers to the range of 0-9
if(num1 > 9 || num2 > 9){
System.out.println("Invalid Digit!!");
System.exit(0);}
//An array that converts number into a string
String num[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
switch(operation){
case '-': //Subtraction conversion
System.out.println(num[num1]+" minus "+num[num2] + " is " + (num1-num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(num1 - num2));
break;
case '+': //Addition conversion
System.out.println(num[num1]+" plus "+num[num2] + " is " + (num1+num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(num1 + num2));
break;
case '*': //Multipication conversion
System.out.println(num[num1]+" multiplied by "+num[num2] + " is " + (num1*num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(num1 * num2));
break;
case '/': //Division conversion
System.out.println(num[num1]+" divided by "+num[num2] + " is " + (num1/num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(num1 / num2));
break;
case '^': //Exponentiation conversion
if(num2 == 0){ //checks to see if the second number entered is 0
System.out.println("Error: Cannot divide by Zero"); //Divide by Zero error message
break;}
System.out.println(num[num1]+" to the power of "+num[num2] + " is " + Math.pow(num1,num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(Math.pow(num1,num2)));
break;
default:
System.out.println("Error: Invalid Operation Entered"); }
}
}
Related
I'm banging my head against the wall.... I'm new...very new to this. I'm receiving an error "Syntax error on token "{", SwitchLabels expected after this token" at the bolded line - switch (operator) {. Every time I change it something else fails.
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) {
// Prompt for 2 numbers and a symbol
Scanner scan = new Scanner(System.in);
//Prompt for input
System.out.println("Enter a number: ");
double num1 = scan.nextDouble();
System.out.println("Enter a number: ");
double num2 = scan.nextDouble();
System.out.println("Enter + - * or /");
char operator = scan.next().charAt(0);
switch (operator) {
/*previous attempt
//if (operator == "+")
// System.out.println(num1 + "+" + num2 + "=" + (num1+num2));
// else if (operator == "-")
// System.out.println(num1 - num2);
// else if (operator == "*")
// System.out.println(num1 * num2);
// else if (operator == "/")
// System.out.println(num1 / num2); */
double answer;
case "+":
answer = num1 + num2;
System.out.println(num1 + "+" +num2 + "=" + answer);
break;
case "-":
answer = num1 - num2;
System.out.println(num1 + "-" +num2 + "=" + answer);
break;
case "*":
answer = num1 * num2;
System.out.println(num1 + "*" +num2 + "=" + answer);
break;
case "/":
answer = num1 / num2;
System.out.println(num1 + "*" +num2 + "=" + answer);
break;
//reject all others
default:
System.out.println("Error: Not a valid symbol!");
break;
}
scan.close();
}
}
You were reading the operator as char and in the switch case you were using them as string. The below code should work for you.
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) { // Prompt for 2 numbers and a symbol
Scanner scan = new Scanner(System.in);
//Prompt for input
System.out.println("Enter a number: ");
double num1 = scan.nextDouble();
System.out.println("Enter a number: ");
double num2 = scan.nextDouble();
System.out.println("Enter + - * or /");
char operator = scan.next().charAt(0);
double answer;
switch (operator) {
/*previous attempt
//if (operator == "+")
// System.out.println(num1 + "+" + num2 + "=" + (num1+num2));
// else if (operator == "-")
// System.out.println(num1 - num2);
// else if (operator == "*")
// System.out.println(num1 * num2);
// else if (operator == "/")
// System.out.println(num1 / num2); */
case '+':
answer = num1 + num2;
System.out.println(num1 + "+" +num2 + "=" + answer);
break;
case '-':
answer = num1 - num2;
System.out.println(num1 + "-" +num2 + "=" + answer);
break;
case '*':
answer = num1 * num2;
System.out.println(num1 + "*" +num2 + "=" + answer);
break;
case '/':
answer = num1 / num2;
System.out.println(num1 + "*" +num2 + "=" + answer);
break;
//reject all others
default:
System.out.println("Error: Not a valid symbol!");
break;
}
scan.close();
}
}
You cant define variables there, put the line double answer; before switch (operator) {
try this
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) { // Prompt for 2 numbers and a symbol
Scanner scan = new Scanner(System.in);
//Prompt for input
System.out.println("Enter a number: ");
double num1 = scan.nextDouble();
System.out.println("Enter a number: ");
double num2 = scan.nextDouble();
System.out.println("Enter + - * or /");
char operator = scan.next().charAt(0);
double answer;
switch (operator) {
case '+':
answer = num1 + num2;
System.out.println(num1 + "+" + num2 + "=" + answer);
break;
case '-':
answer = num1 - num2;
System.out.println(num1 + "-" + num2 + "=" + answer);
break;
case '*':
answer = num1 * num2;
System.out.println(num1 + "*" + num2 + "=" + answer);
break;
case '/':
answer = num1 / num2;
System.out.println(num1 + "*" + num2 + "=" + answer);
break;
//reject all others
default:
System.out.println("Error: Not a valid symbol!");
break;
}
scan.close();
}
}
I'm a very beginner java coder and I'm coding a simple calculator using swing, and I want to implement square roots into the operators. I want it to be so that in the case that the operator is a square root, the calculator wont ask for the second number.
package swingcalculator;
import javax.swing.JOptionPane;
public class SwingCalculator {
public static void main(String[] args) {
double num1, num2, answer;
String operator;
num1 = Integer.parseInt(JOptionPane.showInputDialog("Enter your first number:"));
operator = JOptionPane.showInputDialog("Enter your operator (+ , - , * , /, ^, sqrt):");
num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second number number:"));
switch(operator) {
case "+":
answer = num1 + num2;
break;
case "-":
answer = num1 - num2;
break;
case "*":
answer = num1 * num2;
break;
case "/":
answer = num1 / num2;
break;
case "sqrt":
answer = Math.sqrt(num1);
break;
case "^":
answer = Math.pow(num1, num2);
break;
default:
System.out.println("You have entered an invalid operator");
return;
}
if (Boolean.parseBoolean(operator) == Boolean.parseBoolean("sqrt")){
JOptionPane.showMessageDialog(null, "Square root of " + num1 + " = " + answer);
}
else{
JOptionPane.showMessageDialog(null, num1 + " " + operator + " " + num2 + " = " + answer);
}
}
Any help would be appreciated!
Put everything after the operator = line inside a conditional (you can also move the JOptionPane.showMessageDialog lines inside the appropriate block of the conditional statement, because you don't need to check operator again):
operator = JOptionPane.showInputDialog("Enter your operator (+ , - , * , /, ^, sqrt):");
if (!operator.equals("sqrt")) {
num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second number number:"));
switch (...) { ... }
JOptionPane.showMessageDialog(null, num1 + " " + operator + " " + num2 + " = " + answer);
} else {
JOptionPane.showMessageDialog(null, "Square root of " + num1 + " = " + answer);
}
operator = JOptionPane.showInputDialog("Enter your operator (+ , - , * , /, ^, sqrt):");
if(!operator.equals("sqrt"){
num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second number number:"));
}
Read the second number only if operator is not 'sqrt', however your program seems to have many anomalies, as suggested to you in comments by others
I have made the basic calculator app which can add, subtract multiply or divide just two numbers. What I am trying to do improve the program to be able to '+' '-' '*' or '/' more than just two numbers. Here is the basic java calculator program I have down so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("\nEnter first number: \n");
double fnum = input.nextDouble();
System.out.println("\nEnter an operation sign such as, '+', '-', '*', or '/', '=': \n");
char operator = input.next().charAt(0);
System.out.println("\nEnter second number: \n");
double snum = input.nextDouble();
input.close();
switch(operator) {
case '+':
double answer = fnum + snum;
System.out.println("\n" + fnum + " " + operator + " " + snum + " = " + answer);
break;
case '-':
double answer1 = fnum - snum;
System.out.println("\n" + fnum + " " + operator + " " + snum + " = " + answer1);
break;
case '*':
double answer2 = fnum * snum;
System.out.println("\n" + fnum + " " + operator + " " + snum + " = " + answer2);
break;
case '/':
double answer3 = fnum / snum;
System.out.println("\n" + fnum + " " + operator + " " + snum + " = " + answer3);
break;
default:
System.out.println("Wrong choice for operator. ");
break;
}
}
}
To achieve this I was thinking that there has to be a loop probably before the sysout "Enter operator" line and I have tried to incorporate a do while loop with the while part being (operator != '=') and have had no success. Oh yeah and of coarse I need to reword the "Enter second number" sysout. Thanks in advance for any advice!
**Here's an example output of my current calculator program followed by an example of the I output of my desired calculator program.
current calculator output:
8.0 + 2.0 = 10.0
what i'm looking for calculator program to do:
8.0 - 4.0 * 10.0 = 40.0
Note: I am actively working for a solution myself when I have time to do so. If you dont feel like helping me that's perfectly fine. I think my question is clear, valid, and not necessary to delete according to the community guidelines. thanks
The code below does not implement any error checking and, more important, does not take into account the operators precedence - that's why it's better to have a parser - but can give you an idea.
the values and the operators are obtained in a loop which is valid until the user enters the = sign
the values and the operators entered are stored in the lists numbers and operators
after exiting the loop the operations are performed on the stored values
public class Calculator {
public static void main(String[] args) {
ArrayList<Double> numbers = new ArrayList<Double>();
ArrayList<Character> operators = new ArrayList<Character>();
Scanner scanner = new Scanner(System.in);
try {
do {
System.out.println("\nEnter a number: \n");
numbers.add(scanner.nextDouble());
System.out.println("\nEnter an operation sign such as, '+', '-', '*', or '/', '=': \n");
char operator = scanner.next().charAt(0);
if (operator == '=')
break;
operators.add(operator);
} while (true);
} finally {
scanner.close();
}
Double answer = numbers.remove(0);
String resultText = "" + answer;
for (int i=0; i<operators.size(); ++i) {
char operator = operators.get(i);
Double number = numbers.get(i);
switch(operator) {
case '+':
answer += number;
break;
case '-':
answer -= number;
break;
case '*':
answer *= number;
break;
case '/':
answer /= number;
break;
default:
System.out.println("Wrong choice for operator. ");
break;
}
resultText += " " + operator + " " + number;
}
System.out.println("\n" + resultText + " = " + answer);
}
}
The result i get :
Enter a number :
5
Enter another number :
4
What do you want to perform on these numbers?
You have entered a wrong action, please try again
Where did i go wrong in my code?
import java.util.Scanner;
public class App {
public static void main(String[] args) {
double num1, num2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number : ");
num1 = sc.nextDouble();
System.out.println("Enter another number : ");
num2 = sc.nextDouble();
System.out.println("What do you want to perform on these numbers? ");
String word = sc.nextLine();
sc.close();
double result = 0;
switch (word) {
case "Addition":
result = num1 + num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Subtraction":
result = num1 - num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Multiplication":
result = num1 * num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Division":
result = num1 / num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
default:
System.out.println("You have entered a wrong action, please try again ");
break;
}
}
}
Instead of using sc.nextline() on line 15 use sc.next(). The program will now wait for your input before continuing.
Can you change your code like below:
System.out.println("What do you want to perform on these numbers? ");
sc.nextLine(); // ADD THIS LINE
String word = sc.nextLine();
The problem here is with the num2 = sc.nextDouble(); the newline char is not consumed.
Below is the code I use:
public static void main(String args[]) throws Exception {
// A1Pattern.printPattern(26);
double num1, num2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number : ");
num1 = sc.nextDouble();
System.out.println("Enter another number : ");
num2 = sc.nextDouble();
System.out.println("What do you want to perform on these numbers? ");
sc.nextLine();
String word = sc.nextLine();
sc.close();
double result = 0;
switch (word) {
case "Addition":
result = num1 + num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Subtraction":
result = num1 - num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Multiplication":
result = num1 * num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Division":
result = num1 / num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
default:
System.out.println("You have entered a wrong action, please try again ");
break;
}
}
OUTPUT:
Enter a number :
1
Enter another number :
2
What do you want to perform on these numbers?
Subtraction
1.0 Subtraction 2.0 : -1.0
The java.util.Scanner.next() method finds and returns the next complete token from this scanner.
Use scanner.next() instead of scanner.nextLine().
I am new to java and programming.
Can someone suggest what can be used so that the answer must equal to +,-,*,/ ? At the moment I am trying to create an if statement but I am getting an error and I am not quite sure why. Can someone look at my code and help me complete the if statement please? If you have any other suggestions on what can be improved, please share.
import java.util.Scanner;
public class Calculator {
public static void main (String Args []) {
Scanner input = new Scanner(System.in);
double firstNumber, secondNumber;
String equationOperator;
System.out.println("Please give your first number: \t");
firstNumber = input.nextDouble();
System.out.println("Please give your second number: \t");
secondNumber = input.nextDouble();
System.out.println("Which equation would you like to perform?");
System.out.println("Please enter one of the following + - / * \t");
equationOperator = input.next();
switch (equationOperator) {
case "+":
System.out.println("Your chosen equation is: Adding");
System.out.println("Your answer is: " + (firstNumber + secondNumber));
break;
case "-":
System.out.println("Your chosen equation is: Subtracting");
System.out.println("Your answer is: " + (firstNumber - secondNumber));
break;
case "/":
System.out.println("Your chosen equation is: Dividing");
System.out.println("Your answer is: " + (firstNumber / secondNumber));
break;
case "*":
System.out.println("You chosen equation is: Multiplying");
System.out.println("Your answer is: " + (firstNumber * secondNumber));
break;
}
if (!equationOperator.equals("+ || - || / || *") {
System.out.println("Please choose one of the following:");
System.out.println("+"
+ "-"
+ "/"
+ "*");
}
System.out.println("\t Thank You for using my Calculator");
}
}
You're missing a closing parenthesis in your condition:
if (!equationOperator.equals("+ || - || / || *") {
should be
if (!equationOperator.equals("+ || - || / || *")) {
Note that this won't give you the expected result either, as you are checking for the exact string "+ || - || / || *".
You would either need several equals, e.g.
if (!equationOperator.equals("+") && !equationOperator.equals("-") ...) {
or simply use the default case in your switch statement:
switch (equationOperator) {
case "+":
System.out.println("Your chosen equation is: Adding");
System.out.println("Your answer is: " + (firstNumber + secondNumber));
break;
case "-":
System.out.println("Your chosen equation is: Subtracting");
System.out.println("Your answer is: " + (firstNumber - secondNumber));
break;
case "/":
System.out.println("Your chosen equation is: Dividing");
System.out.println("Your answer is: " + (firstNumber / secondNumber));
break;
case "*":
System.out.println("You chosen equation is: Multiplying");
System.out.println("Your answer is: " + (firstNumber * secondNumber));
break;
default:
System.out.println("Please choose one of the following:");
System.out.println("+"
+ "-"
+ "/"
+ "*");
}
The default case will be executed when none of the other matches. See the documentation for more details.
Use a default case in switch
default:
System.out.println("Please choose one of the following:");
System.out.println("+"
+ "-"
+ "/"
+ "*");
}
Also your if statement is incorrect apart from ) bracket missing from end.
if (!equationOperator.equals("+ || - || / || *")) This compares your equationOperator with string "+ || - || / || *" .
You wanted this
if (!(equationOperator.equals("+") || equationOperator.equals("-") ||
equationOperator.equals("/") || equationOperator.equals("*"))) {