Simple syntax error - java

import java.io.PrintStream;
import java.util.Scanner;
public class BasicCalculator
{
public static void main(String[] args)
{
int ADDITION = 1;
int SUBTRACTION = 2;
int MULTIPLICATION = 3;
int DIVISION = 4;
int EXIT = 5;
Scanner keyboard = new Scanner(System.in);
int choice;
do
{
System.out.println("Choose from the following:");
System.out.println("1. Add 2 integers");
System.out.println("2. Subtract 2 integers");
System.out.println("3. Multiply 2 integers");
System.out.println("4. Divide 2 integers");
System.out.println("5. Exit");
System.out.print("Enter choice: ");
choice = keyboard.nextInt();
if ((choice == 1) || (choice == 2) || (choice == 3) || (choice == 4))
{
System.out.print("Enter first integer: ");
int left = keyboard.nextInt();
System.out.print("Enter second integer: ");
int right = keyboard.nextInt();
switch (choice)
{
double Result;
case 1:
Result = left + right;
System.out.println(left + " + " + right + " = " + Result);
break;
case 2:
Result = left - right;
System.out.println(left + " - " + right + " = " + Result);
break;
case 3:
Result = left * right;
System.out.println(left + " * " + right + " = " + Result);
break;
case 4:
Result = left / right;
System.out.println(left + " / " + right + " = " + Result);
}
System.out.println();
}
} while (choice != 5);
}
}
errors:
BasicCalculator.java:34: error: case, default, or '}' expected
int Result;
^
BasicCalculator.java:34: error: case, default, or '}' expected
int Result;
^
BasicCalculator.java:34: error: case, default, or '}' expected
int Result;
the above code is my project for my intro to computer programming class,i've ran into a few errors that are stemming from formatting issues. can I get some basic help with whats causing the errors. I'm still trying to get used to reading the errors description in notepad++ and understanding what they mean.

You cannot declare a variable inside a switch statement outside of a case label. If you want Result to be shared among all cases, including the default, declare it prior to switch, like this:
double Result = 0;
switch (choice)
{
case 1:
Result = left + right;
System.out.println(left + " + " + right + " = " + Result);
break;
case 2:
Result = left - right;
System.out.println(left + " - " + right + " = " + Result);
break;
case 3:
Result = left * right;
System.out.println(left + " * " + right + " = " + Result);
break;
case 4:
Result = left / right;
System.out.println(left + " / " + right + " = " + Result);
}

(I'm not sure this is completely correct as I don't really do Java, but here goes)
I think the error is where you have double Result; inside the switch statement - Java only allows either case or default inside the switch statement. Try placing the double Result line just above your switch (... line. Also, I'd make sure that all of the lines below your case 1/2/3 statements are properly indented - it may just be the formatting on stack exchange, but the Result = ... lines look one character ahead (not sure if this would make a difference, but it's best to always have consistent code).

Related

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

How can i make a loop for my code so it runs until user gives correct input?

I am wondering how I could make this code loop whenever the user gives a number outside of what the operator variable is asking. I am open to different suggestions. I have tried and failed many times using the do while loop. I want the code to say "Choose a number between 1-4" if the user gives the wrong number and then I want the loop back to the operator variable until the user gives a correct number and after the correct answer is given I want the program to go though the rest of the code and close.
import static java.lang.System.*;
import static javax.swing.JOptionPane.*;
import static java.lang.Integer.*;
public class SimpleCalc {
public static void main(String[] args) {
do {
String operator = showInputDialog("Choose operation: " + "\n" +
"[1] = Plus" + "\n" +
"[2] = Minus" + "\n" +
"[3] = Multiply" + "\n" +
"[4] = Divide" + "\n");
int c = parseInt(operator);
if (c>4 || c<1) {
showMessageDialog(null, "Choose a number between 1 - 4.");
}
else{
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
switch(c) {
case 1:
showMessageDialog(null, a + " + " + b + " = " + (a+b));
break;
case 2:
showMessageDialog(null, a + " - " + b + " = " + (a-b));
break;
case 3:
showMessageDialog(null, a + " * " + b + " = " + (a*b));
break;
case 4:
showMessageDialog(null, a + " / " + b + " = " + (a/b));
break;
}
}
} while (c>4 || c<1);
}
}
Move the declaration of c out of do block, otherwise it is not accessible in while
int c;
do {
...
c = parseInt(operator);
...
} while (c > 4 || c < 1);
You are on the right track by using do while loop. However the value c is not seen as its within the do while block. if you add int c above the do block and make int c = parseInt(operator); to c = parseInt(operator); it will work

The program doesn't end when the timer ends until you give an input

I had some free time and I decided to make a program that could give me math questions using Java Eclipse. Whenever the timer ends during it though, the while loop doesn't end until you give one last input. I know that it is because of the while loop, but I don't know how to end it.
import java.util.Random;
import java.util.Scanner;
public class math_questioner_4 {
public static void main(String[] args) {
int firstnumber,secondnumber,operation,answer,answerinput,correctcount = 0,incorrectcount = 0, time, difficulty, max = 0, mixedop;
Scanner input;
System.out.println("What do you want the operation to be? 1 = addition 2 = subtraction 3 = multiplication 4 = division 5 = mixed");
input = new Scanner(System.in);
operation = input.nextInt();
// There is around 30 lines that don't relate to the question here
if (operation == 1) {
long endTime = System.currentTimeMillis() + (time*1000);
while (System.currentTimeMillis() < endTime) {
Random rand = new Random();
firstnumber = rand.nextInt(max) + 1;
secondnumber = rand.nextInt(max) + 1;
answer = firstnumber + secondnumber;
System.out.println("What is " + firstnumber + " + " + secondnumber + "?");
answerinput = input.nextInt();
if (answerinput == answer) {
System.out.println("Correct!");
correctcount++;
} else {
System.out.println("Sorry, " + firstnumber + " + " + secondnumber + " is " + answer + ".");
incorrectcount++;
}
}
// Another 140 lines here that don't matter either, just some operations
if (time == 1) {
System.out.println("You got " + correctcount + " questions correct and " + incorrectcount + " wrong in " + time + " second!");
} else {
System.out.println("You got " + correctcount + " questions correct and " + incorrectcount + " wrong in " + time + " seconds!");
}
}
}
I know that it's because of the while loop that it won't end, but I don't know how. Also please don't yell at me. I'm a beginner that takes classes at my Chinese school, it's only my 9th week (I've been to nine classes) and this is random extra stuff. I get most of my answers from this website and I also have only learned to do things with integers. It's also my first question here.

While loop wont repeat itself

I need to let the user input an operand, input 2 integers, display the result, and repeat. It wont repeat and when you input an integer to continue, it terminates. Any help would be appreciated, Ive been stuck for a while now! Thanks.
package lab03;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
*
*/
public class Lab03 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int n, p, q = 1;
boolean run = true;
String operator;
while (run == true) {
operator = JOptionPane.showInputDialog("Enter one of + - * / ");
String trimOperator = operator.trim();
char m = trimOperator.charAt(0);
String firstOperand = JOptionPane
.showInputDialog("Enter first integer operand: ");
n = Integer.parseInt(firstOperand);
String secondOperand = JOptionPane
.showInputDialog("Enter second integer operand: ");
p = Integer.parseInt(secondOperand);
switch (m) {
case '+':
System.out.println(n + " plus " + p + " is " + (n + p));
run = false;
break;
case '-':
System.out.println(n + " minus " + p + " is " + (n - p));
run = false;
break;
case '*':
System.out
.println(n + " multiplied by " + p + " is " + (n * p));
run = false;
break;
case '/':
System.out.println(n + " divided by " + p + " is " + (n / p)
+ " with remainder " + (n % p));
run = false;
break;
default:
System.out.println("Invalid character");
run = false;
break;
}
String lastInteger = JOptionPane
.showInputDialog("Enter 0 to quit, or any other integer to continue. ");
q = Integer.parseInt(lastInteger);
System.out.println(q);
System.exit(0);
continue;
}
}
Sorry for lack of comments.

Categories