Syntax error on token "{", SwitchLabels expected after this token-switch (char) - java

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();
}
}

Related

How do i connect input variables from file 1 to file 2

Im trying to make a simple calculator but with 2 files. The first file is for the normal code and the 2nd file is for the switch case. What im trying to do is to use the input from num1 num2 to switch.java My issue is that num1 num2 cannot be resolved to a variable in Switch.java
week1.java
import java.util.Scanner;
public class week1
{
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Input a number:");
num1 = input.nextInt();
System.out.print("Input a Math :");
char operator1 = input.next().charAt(0);
System.out.print("Input a number:");
num2 = input.nextInt();
int operator2 = 0;
Switch swish = new Switch();
swish.switchcase();
}
}
Switch.java
import java.util.Scanner;
public class Switch
{
void switchcase()
{
switch(operator1){
case '+':
operator2 = num1 + num2;
System.out.println("Addition: " + (week1.num1) + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '-':
operator2 = num1 - num2;
System.out.println("Subtraction: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '*':
operator2 = num1 * num2;
System.out.println("Multiplication: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '/':
operator2 = num1 / num2;
System.out.println("Division: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
}
}
}
You must pass parameters to your switchcase method, and obtain a result back.
Class Week1:
import java.util.Scanner;
public class Week1
{
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Input a number:");
num1 = input.nextInt();
System.out.print("Input a Math :");
char operator1 = input.next().charAt(0);
System.out.print("Input a number:");
num2 = input.nextInt();
int result = Switch.switchcase(num1, operator1, num2);
System.out.println(num1 + " " + operator1 + " " + num2 + " = " + result);
}
}
Class Switch:
public class Switch {
public static int switchcase(int num1, char operator1, int num2) {
switch(operator1){
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
}
}
}
Try using the below classes. Local variables inside a method will only be accessible inside that method. The variables has to be passed to another method for processing.
It is a best practice to begin class with capital letter.
Visit https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html
import java.util.Scanner;
public class Week1
{
public static void main(String[] args) {
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.print("Input a number:");
num1 = input.nextInt();
System.out.print("Input a Math :");
char operator1 = input.next().charAt(0);
System.out.print("Input a number:");
num2 = input.nextInt();
int operator2 = 0;
Switch swish = new Switch();
swish.switchcase(num1, operator1, num2);
}
}
public class Switch
{
void switchcase(int num1, char operator1, int num2)
{
int operator2;
switch(operator1){
case '+':
operator2 = num1 + num2;
System.out.println("Addition: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '-':
operator2 = num1 - num2;
System.out.println("Subtraction: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '*':
operator2 = num1 * num2;
System.out.println("Multiplication: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
case '/':
operator2 = num1 / num2;
System.out.println("Division: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 );
break;
}
}
}

How do I tell my program to ignore an instruction if a certain case is true?

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

How to get calculator program to add, subtract, multiply, divide more than two numbers

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);
}
}

Making a calculator using switch case

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().

Simple Calculator Operation

I am attempting to simplify my long code of a calculator program, but I have a road block. I have a new else if statement for each calculator operator, but what I want to do is allow the user to manually type in, on one line, the entire operation they would like to perform and have the code compute it.
Here's what I have:
do {
System.out.println("What function would you like to perform?");
System.out.print("Exit Calculator (Q), Add (+), Subtract (-), Multiply (x), Divide (/): ");
maininput = in.next();
if (maininput.equals("+")) {
System.out.print("Enter the first number to add: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to add: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + answer);
System.out.println();
}
else if (maininput.equals("-")) {
System.out.print("Enter the first number to subtract: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to subtract: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("x")) {
System.out.print("Enter the first number to multiply: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to multiply: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 * num2;
System.out.println(num1 + " x " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("/")) {
System.out.print("Enter the first number to divide: ");
num1 = in.nextDouble();
do {
System.out.print("Enter the second number to divide: ");
num2 = in.nextDouble();
System.out.println();
if (num2 == 0) {
System.out.println("Cannot divide by 0! Please enter a different number.");
}
} while (num2 == 0);
answer = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("Q") || maininput.equals("q") || maininput.equals("EXIT") || maininput.equals("exit")) {
in.close();
System.exit(0);
}
else {
System.out.println(maininput + " is not a valid operand. Please try again.");
System.out.println();
}
} while (maininput != "Q" && maininput != "q");
This is what I want the output to be:
Enter operation:
4 * 6
4 * 6 = 24
Should be able to enter any operation here on one line. I am not asking you to write my calculator for me, I am asking how to allow the computer to read in the entire operation off one line and compute it, then print it.
If you use scanner readLine then you can read a whole line
e.g.
4 * 6
This line can then be split to get three tokens
String tokens [] = line.split (" ");
then you can see what operation to do based upon token[1]
if (token[1].equals ("-") {
//lets minus token[2] from token[0]
// need to convert String to Number
}
You can use String.split and store it in an array. Then it will return an array of string, parse those back to integers. the do the operation you want. The x variable will be the result.
if(maininput.contains("+")) {
String[] stringarr = string.split("\\+");
int x = Integer.parseInt(stringarr[0]) + Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " + " + stringarr[1] + " = " + x);
} else if(maininput.contains("-")) {
String[] stringarr = string.split("\\-");
int x = Integer.parseInt(stringarr[0]) - Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " - " + stringarr[1] + " = " x);
}
... And so on.
You could try parsing the line using a Pattern object, something like this:
Pattern opPattern = Pattern.compile("(\\d+) *([+-*/]) *(\\d+)");
Matcher matcher = opPattern.matcher(userLine);
if(matcher.find()) {
int op1 = Integer.toValue(matcher.group(1));
int op2 = Integer.toValue(matcher.group(3));
String op = matcher.group(2);
if(op.equals("+")) {
// do + op ...
} else ... {
// etc...
}
} else {
// error in line, not the form of an operation
}
Have a look at the javadoc, as I'm not sure if I used the correct method names and the like, just tried to illustrate the idea...

Categories