While loop wont repeat itself - java

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.

Related

How do I fix my "illegal start of type" and "<identifier> expected" errors at my return statement?

I know it has something to do with my bracket placement, but I am not sure where the error is occurring. Keep in mind this is a 2nd method within my class.
import java.util.Scanner*;
import java.util.Arrays.*;
public class BasicMathTest
{
//Creates an array to store the numbers that will be used in the math
problems
int alpha[] = {4, 8, 10, 15, 25, 30};
int beta[] = {2, 4, 5, 3, 5, 10};
double Problems = alpha.length;
public static void main(String args[])
{
System.out.println("Welcome to this Math Quiz. Here you will add, subtract, multiply and divide!");
//Ask the user to choose their type of problem
Scanner kbReader = new Scanner(System.in);
System.out.println("Select Addition (1), Subtraction (2), Multiplication (3) or Division (4): ");
int Selection = kbReader.nextInt();
//Calculates the users score
double score = Selection * 100 / Problems;
System.out.println("Your score on the test: " + score + "%");
}
public static double Selection ()
{
int score = 0; //Stores the number of correct answers
int correct; //Stores the correct answer
for (int i = 0; i < Problems; i++)
{
if (Selection == 1)
{
System.out.println(alpha[i] + " + " + beta[i]);
correct = alpha[i] + beta[i];
}
else if(Selection == 2)
{
System.out.print(alpha[i] + " - " + beta[i]);
correct = alpha[i] - beta[i];
}
else if (Selection = 3)
{
System.out.print(alpha[i] + " * " + beta[i]);
correct = alpha[i] * beta[i];
}
else if(Selection == 4)
{
System.out.print(alpha[i] + " / " + beta[i]);
correct = alpha[i] / beta[i];
}
}
System.out.println(" ");
}
return score;
}
Output: E:\Xinox Software\JCreatorV4LE\MyProjects\CreateTask\BasicMathTest.java:52: illegal start of type
return score;
^
E:\Xinox Software\JCreatorV4LE\MyProjects\CreateTask\BasicMathTest.java:52: <identifier> expected
return score;
^
2 errors
Problems:
you forgot an opening braces at "Selection == 4" if.
Write "==" instead of **"=""" in "else if (Selection == 3)"
type of score is double
Could you show us how you use score var ?
Look at this and let me know if it is right :
public static double Selection ()
{
double score = 0; //change from int to double
int correct; //Stores the correct answer
for (int i = 0; i < Problems; i++)
{
if (Selection == 1)
{
System.out.println(alpha[i] + " + " + beta[i]);
correct = alpha[i] + beta[i];
}
else if(Selection == 2)
{
System.out.print(alpha[i] + " - " + beta[i]);
correct = alpha[i] - beta[i];
}
else if (Selection == 3)
{
System.out.print(alpha[i] + " * " + beta[i]);
correct = alpha[i] * beta[i];
}
else if(Selection == 4)
{ // missing brace
System.out.print(alpha[i] + " / " + beta[i]);
correct = alpha[i] / beta[i];
}
System.out.println(" ");
}
return score;
}

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

Why am I getting error calculating postfix last operator?

The project is asking to use Stack to calculate a postfix expression, this one in particular:
5.0 3.5 - 1.2 /
Now my code works fine for this postfix expression:
2 3 +
What am I missing that is giving me the following error?
Exception in thread "main" java.lang.NumberFormatException: empty
String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at
java.lang.Double.parseDouble(Double.java:538) at
java.lang.Double.(Double.java:608) at
project.Calculator.processIn(Calculator.java:55) at
project.Project_main.main(Project_main.java:25) Java Result: 1
package project;
import java.util.ArrayList;
import java.util.Stack;
public class Calculator {
Stack<Double> calcStack = new Stack<>();
ArrayList<String> operators = new ArrayList<>();
public Calculator() {
operators.add("+");
operators.add("-");
operators.add("/");
operators.add("*");
}
public double processIn(String expression){
String[] express = expression.split("");
String temp = "";
for(String j : express){
if(operators.contains(j)){
System.out.println("Operator Reached: " + j);
double operand2 = calcStack.pop();
double operand1 = calcStack.pop();
double tmp = 0.0;
if(j.compareTo("*") == 0){
tmp = operand1 * operand2;
System.out.println("Performing multiplication on " + operand1 + " and " + operand2);
calcStack.push(tmp);
}
else if(j.compareTo("/") == 0){
tmp = operand1 / operand2;
System.out.println("Performing division on " + operand1 + " and " + operand2);
calcStack.push(tmp);
}
else if(j.compareTo("-") == 0){
tmp = operand1 - operand2;
System.out.println("Performing subtraction on " + operand1 + " and " + operand2);
calcStack.push(tmp);
}
else if(j.compareTo("+") == 0){
tmp = operand1 + operand2;
System.out.println("Performing addition on " + operand1 + " and " + operand2);
calcStack.push(tmp);
}
System.out.println("Pushing result to stack: " + tmp);
}
else if(j.compareTo(" ") == 0){
double newOperand = new Double(temp);
temp = "";
System.out.println("Pushing to stack: " + newOperand);
calcStack.push(newOperand);
}
else{
temp = temp + j;
System.out.println("Current temp value: " + temp);
}
}
return calcStack.pop();
}
}
i think this will solve your problem.
split with " "(space) instead of ""
String[] express = expression.split(" ");
and change your else to bellow
else {
double newOperand = new Double(j);
System.out.println("Pushing to stack: " + newOperand);
calcStack.push(newOperand);
}
and remove else if bellow
else if(j.compareTo(" ") == 0){
double newOperand = new Double(temp);
temp = "";
System.out.println("Pushing to stack: " + newOperand);
calcStack.push(newOperand);
}
this way you directly add numbers to your stack.
your error was happening because of how you handle space after operations. when you have numbers followed by numbers else gets called first and then if for space. so you temp value has a number in it. but after finishing an operation you reach a space gain right away but you have no value in your temp so new Double(temp) throws an exception since temp is not a number.
so another way to fix your code if you want to keep it as it is, is to use try and catch like below.
else if(j.compareTo(" ") == 0){
try{
double newOperand = new Double(temp);
temp = "";
System.out.println("Pushing to stack: " + newOperand);
calcStack.push(newOperand);
}catch(NumberFormatException ex){
//skip
}
}
this way you catch your error without breaking your code. but i recommend the first solution.
Please split the string on space " " as Shawn suggested like expression.split(" ") (but this assumes that your expression would always contains spaces between operator and operands). This would give you two types of tokens/strings operands and operators. Here is more simplified implementation of your code. Please notice the expression.trim() operation to avoid any trailing spaces.
[BTW, I have tried in eclipse and it works :) ]
public double processIn(String expression)
{
expression = expression.trim();
System.out.println("Trimmed expressoin : " + expression);
String[] express = expression.split(" ");
for(String j : express){
if(operators.contains(j)){
System.out.println("Operator Reached: " + j);
double operand2 = calcStack.pop();
double operand1 = calcStack.pop();
double tmp = 0.0;
if(j.compareTo("*") == 0){
tmp = operand1 * operand2;
System.out.println("Performing multiplication on " + operand1 + " and " + operand2);
calcStack.push(tmp);
}
else if(j.compareTo("/") == 0){
tmp = operand1 / operand2;
System.out.println("Performing division on " + operand1 + " and " + operand2);
calcStack.push(tmp);
}
else if(j.compareTo("-") == 0){
tmp = operand1 - operand2;
System.out.println("Performing subtraction on " + operand1 + " and " + operand2);
calcStack.push(tmp);
}
else if(j.compareTo("+") == 0){
tmp = operand1 + operand2;
System.out.println("Performing addition on " + operand1 + " and " + operand2);
calcStack.push(tmp);
}
System.out.println("Pushing result to stack: " + tmp);
}
else {
double newOperand = new Double(j);
System.out.println("Pushing operand to stack: " + newOperand);
calcStack.push(newOperand);
}
}
return calcStack.pop();
}

Simple syntax error

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

Getting a string from a scanner when a number is entered

I am trying to write a program that ask a user for 2 numbers and then ask the user to pick a command from a menu by entering the correspond number to the command.
I can write the program if i take the input as an Int but cannot figure it out for a string, also it has to be a string.
I am having problems when it enters the while loop to validate the user input it does not stop when the statement is false it will stay in the loop I can not figure out what i am doing wrong.
Here is the code i have.
import java.util.Scanner;
public class ab {
public static void main(String[] args) {
System.out.println("-------------------------------------");
Scanner stdIn = new Scanner(System.in);
double L;
System.out.print("Enter the left operand: ");
L = stdIn.nextDouble();
double R;
System.out.print("Enter the right operand: ");
R = stdIn.nextDouble();
System.out.println("-------------------------------------");
System.out.println("1 -> Multiplication");
System.out.println("2 -> Division");
System.out.println("3 -> Addition");
System.out.println("4 -> Subraction");
System.out.println("-------------------------------------");
String input;
System.out.print("Choose one of the following commands by enterning the corresponding number: ");
input = stdIn.next();
System.out.println();
while (!input.equals(1) && !input.equals(2) && !input.equals(3) && !input.equals(4)) {
System.out.print("Invalid entry, please type a valid number (1, 2, 3 or 4): ");
input = stdIn.next();
System.out.println();
if (input.equals(1)) {
System.out.print(L + " * " + R + " = " + (L * R));
} else if (input.equals(2)) {
System.out.print(L + " / " + R + " = " + (L / R));
} else if (input.equals(3)) {
System.out.print(L + " + " + R + " = " + (L + R));
} else {
System.out.print(L + " - " + R + " = " + (L - R));
}
}
stdIn.close();
}
}
Any help would be much appreciated.
Thank you in advanced.
The line input = stdIn.next(); is taking input as String
while your comparison is against integer. So a String never equals Int
You may try changing your while loop condition to:
while (!input.equals("1") && !input.equals("2") && !input.equals("3") && !input.equals("4"))
note the double quote around the numbers
Is answered, but check this
import java.util.Scanner;
public class ab {
public static void main(String[] args) {
System.out.println("-------------------------------------");
Scanner stdIn = new Scanner(System.in);
double L;
System.out.print("Enter the left operand: ");
L = stdIn.nextDouble();
double R;
System.out.print("Enter the right operand: ");
R = stdIn.nextDouble();
System.out.println("-------------------------------------");
System.out.println("1 -> Multiplication");
System.out.println("2 -> Division");
System.out.println("3 -> Addition");
System.out.println("4 -> Subraction");
System.out.println("-------------------------------------");
String input;
System.out.print("Choose one of the following commands by enterning the corresponding number: ");
input = stdIn.next();
while (true) {
if (!input.equals("1") && !input.equals("2") && !input.equals("3") && !input.equals("4")) {
System.out.print("Invalid entry, please type a valid number (1, 2, 3 or 4): ");
input = stdIn.next();
} else {
if (input.equals("1")) {
System.out.print(L + " * " + R + " = " + (L * R));
break;
} else if (input.equals("2")) {
System.out.print(L + " / " + R + " = " + (L / R));
break;
} else if (input.equals("3")) {
System.out.print(L + " + " + R + " = " + (L + R));
break;
} else {
System.out.print(L + " - " + R + " = " + (L - R));
break;
}
}
}
stdIn.close();
}
}

Categories