I need help with my coding. I am practicing again with my java programming and today I am creating a calculator that has the same function as the real calculator but again I run into errors and unable to figure out again.
Okay, the way I wanted my calculator to works is instead of getting line by line input from the user like this:-
In code output
Enter Number: 1
Enter Operator (+,-, /, *, ^ (Power) or s (Square): +
Enter Number: 2
Ans: 3
I wanted it to calculate when the user press enter like this:-
The Output that I want
enter number: 1+2*4
Ans: 12
So they can add as many long numbers as they want before they hit enter calculate. The users are supposed to be able to reset the number to when using the calculator while in the loop of the calculation.
at the beginning of the code, it will ask the user for an input to continue or exit the calculator. Then if continue it will run the calculation. The calculator will be looping until the users press E to exit the calculator and if exit it will exit the code.
This is where I have errors. First, I can't figure out how to break from the loop inside the looping calculator and second at the beginning of the code when the user press E it was supposed to exit the calculator but it didn't. The third error is when the user using the square to calculate I want it to get straight to show the answer instead of asking another number.
and I want to simplify the code in public static void main(String[] args)for the calculation part. Is it possible to put the switch case in method and call it inside the main? or do you have a suggestion on how to simplify the calculation part?
Please help me:(
public class TestingCalculator {
public static void main(String[] args){
double answer = 0;
double numA, numB;
char operator;
char activateCalc;
boolean calculator = false;
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
Scanner ans = new Scanner(System.in);
String a = ans.next();
activateCalc = a.charAt(0);
while (activateCalc != 'E' || activateCalc != 'e') {
Scanner input = new Scanner(System.in);
System.out.print("Enter number: ");
String n =input.next();
numA = Double.parseDouble(n);
while (calculator = true) {
//User enter their operator.
System.out.print("Enter Operator (+,-, /, *, ^ (Power) or s (Square): ");
operator = input.next().charAt(0);
System.out.print("Enter number: "); //User enter the continues number
numB = input.nextDouble();
switch (operator) {
case '=':
System.out.print(answer);
break;
case '+':
answer = add(numA,numB);
break;
case '-':
answer =subtract(numA,numB);
break;
case '*':
answer = multiply(numA,numB);
break;
case '/':
answer = divide(numA,numB);
break;
case '^':
answer = power(numA, numB);
break;
case 's':
case 'S':
answer = Math.pow(numA, 2);
break;
}
//The calculation answer of the user input
System.out.println("Answer: " + answer);
numA = answer;
// to exit calculator.
System.out.println("Press E to Exit the calculator: ");
if (activateCalc = 'E' || activateCalc = 'e') {
break;
}
}
}
ans.close();
}
//Method for the operators.
static double add(double numA, double numB) {
double answer = numA + numB;
return answer;
}
static double subtract(double numA, double numB) {
double answer = numA - numB;
return answer;
}
static double multiply(double numA, double numB) {
double answer = numA * numB;
return answer;
}
static double divide(double numA, double numB) {
double answer = numA / numB;
return answer;
}
static double power(double numA, double numB) {
int answer = (int) Math.pow(numA, numB);
return answer;
}
static double Square(double numA, double numB) {
int answer = (int) Math.pow(numA, 2);
return answer;
}
}
Instead of trying to identify the problems with your application, I decided to focus on producing a program that works the way you want (with the input you specified). The code was a little big, but I tried to leave it well commented for you to understand what I did. I know that some things may still be a little confusing, so I will simulate running the program to try to make it clearer how it works.
Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestingCalculator
{
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Evaluates a mathematical expression.
*
* #param line Mathematical expression. This line cannot have blank
* spaces
* #return Result of this mathematical expression
*/
public static String calc(String line)
{
while (!hasOnlyNumbers(line)) {
// Checks if line has parentheses
if (line.contains("(")) {
// Get index of the most nested parentheses
int parentheses_begin = line.lastIndexOf("(");
int parentheses_end = line.substring(parentheses_begin).indexOf(")");
String ans = calc(line.substring(parentheses_begin+1, parentheses_end));
// Replaces content of parentheses with the result obtained
if (line.length()-1 >= parentheses_end+1)
line = line.substring(0,parentheses_begin)+ans+line.substring(parentheses_end+1);
else
line = line.substring(0,parentheses_begin)+ans;
}
// Checks if line has potentiation operator
else if (line.contains("^")) {
int opIndex = line.indexOf("^");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = power(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has square operator
else if (line.contains("s")) {
int opIndex = line.indexOf("s");
String n1 = extractFirstNumber(line, opIndex);
double ans = square(Double.valueOf(n1));
line = calc(parseLine(line, n1, opIndex, ans));
}
// Checks if line has multiplication operator
else if (line.contains("*")) {
int opIndex = line.indexOf("*");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = multiply(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has division operator
else if (line.contains("/")) {
int opIndex = line.indexOf("/");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = divide(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has sum operator
else if (line.contains("+")) {
int opIndex = line.indexOf("+");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = add(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has subtraction operator
else if (line.contains("-")) {
int opIndex = line.indexOf("-");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = subtract(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
}
// Returns line only when it has only numbers
return line;
}
/**
* Checks if a line contains only numbers.
*
* #param line Line to be analyzed
* #return If a line contains only numbers
*/
private static boolean hasOnlyNumbers(String line)
{
return line.matches("^[0-9.]+$");
}
/**
* Given a mathematical expression, replaces a subexpression for a value.
*
* #param line Mathematical expression
* #param n1 Number to the left of the subexpression operator
* #param n2 Number to the right of the subexpression operator
* #param opIndex Operator index of the subexpression
* #param ans Value that will replace the subexpression
* #return New mathematical expression with the subexpression replaced
* by the value
*/
private static String parseLine(String line, String n1, String n2, int opIndex, double ans)
{
int lenFirstNumber = n1.length();
int lenSecondNumber = n2.length();
if (line.length()-1 >= opIndex+lenSecondNumber+1)
return line.substring(0, opIndex-lenFirstNumber)+ans+line.substring(opIndex+lenSecondNumber+1);
return line.substring(0, opIndex-lenFirstNumber)+ans;
}
/**
* Given a mathematical expression, replaces a subexpression for a value.
*
* #param line Mathematical expression
* #param n1 Number to the left of the subexpression operator
* #param opIndex Operator index of the subexpression
* #param ans Value that will replace the subexpression
* #return New mathematical expression with the subexpression replaced
* by the value
*/
private static String parseLine(String line, String n1, int opIndex, double ans)
{
int lenFirstNumber = n1.length();
if (line.length()-1 >= opIndex+2)
return line.substring(0, opIndex-lenFirstNumber)+ans+line.substring(opIndex+2);
return line.substring(0, opIndex-lenFirstNumber)+ans;
}
/**
* Extracts the first number from an operation. <br />
* <h1>Example:<h1> <br />
* <b>Line:</b> 1+2*3 <br />
* <b>opIndex:</b> 3 <br />
* <b>Return:</b> 2 <br />
*
* #param line Mathematical expression
* #param opIndex Index of the operator to which the number to be
* extracted belongs to
* #return Number to the left of the operator
*/
private static String extractFirstNumber(String line, int opIndex)
{
StringBuilder num = new StringBuilder();
int i = opIndex-1;
while (i>=0 && (Character.isDigit(line.charAt(i)) || line.charAt(i) == '.')) {
num.append(line.charAt(i));
i--;
}
// Reverses the result, since the number is taken from the end to the
// beginning
num = num.reverse();
return num.toString();
}
/**
* Extracts the second number from a math operation. <br />
* <h1>Example:<h1> <br />
* <b>Line:</b> 1+2*3 <br />
* <b>opIndex:</b> 3 <br />
* <b>Return:</b> 3 <br />
*
* #param line Mathematical expression
* #param opIndex Index of the operator to which the number to be
* extracted belongs to
* #return Number to the right of the operator
*/
private static String extractSecondNumber(String line, int opIndex)
{
StringBuilder num = new StringBuilder();
int i = opIndex+1;
while (i<line.length() && (Character.isDigit(line.charAt(i)) || line.charAt(i) == '.')) {
num.append(line.charAt(i));
i++;
}
return num.toString();
}
// Method for the operators.
private static double add(double numA, double numB)
{
double answer = numA + numB;
return answer;
}
private static double subtract(double numA, double numB)
{
double answer = numA - numB;
return answer;
}
private static double multiply(double numA, double numB)
{
double answer = numA * numB;
return answer;
}
private static double divide(double numA, double numB)
{
double answer = numA / numB;
return answer;
}
private static double power(double numA, double numB)
{
int answer = (int) Math.pow(numA, numB);
return answer;
}
private static double square(double num)
{
int answer = (int) Math.pow(num, 2);
return answer;
}
//-------------------------------------------------------------------------
// Main
//-------------------------------------------------------------------------
public static void main(String[] args) throws IOException
{
char option;
String inputLine = "";
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
option = input.readLine().charAt(0);
while (option != 'E' && option != 'e') {
// Gets user input
System.out.print("Enter mathematical expression: ");
inputLine += input.readLine();
// Processes input
inputLine = inputLine.replaceAll(" ", "");
inputLine = inputLine.replaceAll("S", "s");
// Evaluates input
System.out.println("Evaluating...");
String ans = TestingCalculator.calc(inputLine);
// Displays answer
System.out.println("Ans: "+ans);
// Checks if the user wants to continue running the program
System.out.print("Press E to Exit the calculator: ");
inputLine = input.readLine();
if (inputLine.length() > 0)
option = inputLine.charAt(0);
}
input.close();
}
}
Output
Enter mathematical expression: (1+2*4)/3
Evaluating...
Ans: 3.0
Output 2
Enter mathematical expression: 1+2*9/3
Evaluating...
Ans: 7.0
Desk checking
Input: (1+2*4)/3
calc( (1+2*4)/3 )
not hasOnlyNumbers( (1+2*4)/3) ) ? true
( (1+2*4)/3) ) contains '(' ? true
int parentheses_begin = 0
int parentheses_end = 6
String ans = calc( 1+2*4 )
calc( 1+2*4 )
not hasOnlyNumbers( 1+2*4 ) ? true
( 1+2*4 ) contains '(' ? false
( 1+2*4 ) contains '^' ? false
( 1+2*4 ) contains 's' ? false
( 1+2*4 ) contains '*' ? true
int opIndex = 3
int n1 = 2
int n2 = 4
String ans = n1 * n2 = 2 * 4 = 8
line = calc( 1+8 )
calc( 1+8 )
not hasOnlyNumbers( 1+8 ) ? true
( 1+8 ) contains '(' ? false
( 1+8 ) contains '^' ? false
( 1+8 ) contains 's' ? false
( 1+8 ) contains '*' ? false
( 1+8 ) contains '/' ? false
( 1+8 ) contains '+' ? true
int opIndex = 1
int n1 = 1
int n2 = 8
String ans = n1 + n2 = 1 + 8 = 9
line = calc( 9 )
calc( 9 )
not hasOnlyNumbers( 9 ) ? false
return 9
line = 9
not hasOnlyNumbers( 9 ) ? false
return 9
line = 9
not hasOnlyNumbers( 9 ) ? false
return 9
ans = 9
(9-1 >= 6+1) ? true
line = 9/3
not hasOnlyNumbers( 9/3 ) ? true
( 9/3 ) contains '(' ? false
( 9/3 ) contains '^' ? false
( 9/3 ) contains 's' ? false
( 9/3 ) contains '*' ? false
( 9/3 ) contains '/' ? true
int opIndex = 1
String n1 = 9
String n2 = 3
double ans = 9 / 3 = 3
line = calc( 3 )
calc( 3 )
not hasOnlyNumbers( 3 ) ? false
return 3
line = 3
not hasOnlyNumbers( 3 ) ? false
return 3
Some observations
No checks are made to see if the user-provided input is valid
It is important to maintain the order of operations that are verified in the calc method, in order to maintain precedence between operators (exponentiation / radication must be done first, followed by multiplication / division and finally addition / subtraction operations)
I had problems with the Scanner class, so I used BufferedReader to read the input
Square operation must be done as follows: <num>s or <num>S
Hope this helps. If you don't understand something, tell me I can explain it to you.
try below code and one suggestion try to handle the negative scenarios as well.
public static void main(String[] args) {
double answer = 0;
double numA, numB;
char operator;
char activateCalc;
boolean calculator = false;
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
Scanner ans = new Scanner(System.in);
Scanner input = new Scanner(System.in);
activateCalc = input.next().charAt(0);
while (true) {
if (activateCalc != 'E' && activateCalc != 'e') {
System.out.print("Enter number: ");
String n = input.next();
numA = Double.parseDouble(n);
// User enter their operator.
System.out.print("Enter Operator (+,-, /, *, ^ (Power) or s (Square): ");
operator = input.next().charAt(0);
System.out.print("Enter number: "); // User enter the continues number
numB = input.nextDouble();
switch (operator) {
case '=':
System.out.print(answer);
break;
case '+':
answer = add(numA, numB);
break;
case '-':
answer = subtract(numA, numB);
break;
case '*':
answer = multiply(numA, numB);
break;
case '/':
answer = divide(numA, numB);
break;
case '^':
answer = power(numA, numB);
break;
case 'S':
case 's':
answer = Math.pow(numA, 2);
break;
default:
answer = 0;
}
// The calculation answer of the user input
System.out.println("Answer: " + answer);
numA = answer;
// to exit calculator.
System.out.println("Press E to Exit the calculator or Y to continue : ");
activateCalc = input.next().charAt(0);
if(activateCalc != 'E' && activateCalc != 'e')continue;
}
System.out.println("Thank you for using the calculator. By :) ");
ans.close();
break;
}
}
// Method for the operators.
static double add(double numA, double numB) {
double answer = numA + numB;
return answer;
}
static double subtract(double numA, double numB) {
double answer = numA - numB;
return answer;
}
static double multiply(double numA, double numB) {
double answer = numA * numB;
return answer;
}
static double divide(double numA, double numB) {
double answer = numA / numB;
return answer;
}
static double power(double numA, double numB) {
int answer = (int) Math.pow(numA, numB);
return answer;
}
static double Square(double numA, double numB) {
int answer = (int) Math.pow(numA, 2);
return answer;
}
This question requires debugging details so here we go:
Your code does not seem to compile because of the error:
if (activateCalc = 'E' || activateCalc = 'e') {
break;
}
where you had to use comparison == operator instead of assignment =.
Similar issue is in your inner loop while (calculator = true) - and there's a warning that this value is never used - but this does not affect much.
You cannot exit the loop because you never check the input for exit, it should be:
System.out.println("Press E to Exit the calculator: ");
activateCalc = input.next().charAt(0);
But even if you updated activateCalc, you'd get into endless loop anyway because of the error in this condition while (activateCalc != 'E' || activateCalc != 'e') -- even if user presses 'e', or 'E' this condition is always true.
I am trying to compare two different strings, one character at a time. I need to return the correct number of digits until they do not equal each other anymore. However, I can't include the character of '.' in the return statement. How would I go about doing this?
import java.util.Scanner;
import java.math.BigDecimal;
public class PiEstimate {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a;
String b;
char y;
char c;
char d;
String userInput;
do {
System.out.print("Enter a number of randomly generated points:");
userInput = in.nextLine();
if (!isValid(userInput)) {
System.out.print("\n" + "You entered an invalid integer. Please enter a valid integer greater than 0: ");
userInput = in.nextLine();
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
} else {
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
}
System.out.println("\n" + "Would you like to play again? Enter 'Y' for yes or 'N' for no: ");
String optionToPlay = in.nextLine();
c = optionToPlay.charAt(0);
d = Character.toUpperCase(c);
if (d == 'n' || d == 'N') {
BigDecimal estimate2= new BigDecimal( (Math.PI / 4) * 4);
System.out.println("\n" + "The best estimate is: " + estimate2);
}
} while (d == 'Y');
} // end psvm
public static boolean isValid(String a) {
boolean isFlag = true;
char holder;
for (int i = 0; i < a.length(); i++) {
holder = a.charAt(i);
if (!Character.isDigit(a.charAt(i))) {
return false;
} if (i == 0 && holder == '-') {
return false;
}
} // end for
return isFlag;
} // end isValid
public static double calculation(String a) { // String a means 'looking for a string
double calc = Double.parseDouble(a);
int i;
double x;
double y;
double c = 0;
double runningCounter = 0;
double totalCounter;
for (i = 0; i < calc; i++) {
x = Math.random();
y = Math.random();
c = Math.sqrt((x * x) + (y * y));
if (c <= 1) {
runningCounter++;
}
} // end for
totalCounter = ((runningCounter / calc) * 4);
calc = totalCounter;
return calc;
}
public static int comparison (String bear, String userInput) {
int i = 0;
String s = calculation(userInput) + "";
int b;
int counter2 = 0;
for (i=0; i < s.length(); i++) {
if (s.charAt(i) != bear.charAt(i)) {
return i;
}
}
return i;
} // end comparison
} // end class
Code from IDE
I am having issues with the things the title suggests. I need to tokenize the string, determine the operation in order to solve it, convert the numbers into int types and return the expression.
What exactly am I doing wrong as far as the parsing and tokenizing goes? Everything seemed ok until I tried to use the stringSplit. The only allowed library functions are Integer.parseInt() and split(). There are quite a few things on StackOverflow to help, but none that do not utilize only these two library functions. Here is the code I have thus far:
public static void main(String[] args)
{
String a[] = {"12 + 34", "56 - 78", "99 * 99", "10 / 3"};
stringSplit(a, ',');
}
public static int parseInt(String a)
{
int i;
int sum = 0;
double x = Integer.parseInt(a);
for(i = 0; i < a.length(); i++)
sum = sum + x;
System.out.printf("%s = %d\n", sum);
}
The end result should look something like:
12 + 34 = 46.00
56 - 78 = -22.00
And the like. I am not really looking for the answer. More of a lead to my answer. Thank you in advance for any and all help!
Here is working version of what you seemed to be attempting to do. I split each element of your input array on space (" "), and then extract out two operands and an operator. I also put in a check for dividing by zero.
public static void main(String[] args) throws Exception {
String a[] = {"12 + 34", "56 - 78", "99 * 99", "10 / 3"};
stringProcess(a);
}
public static void stringProcess(String[] a) {
for (int i=0; i < a.length; ++i) {
String[] parts = a[i].split(" ");
double operand1 = Double.parseDouble(parts[0]);
String operator = parts[1];
double operand2 = Double.parseDouble(parts[2]);
double result = 0.0;
switch (operator) {
case "+":
result = operand1 + operand2;
break;
case "-":
result = operand1 - operand2;
break;
case "*":
result = operand1 * operand2;
break;
case "/":
if (operand2 == 0) {
throw new IllegalArgumentException("Divide by zero!");
}
result = operand1 / operand2;
break;
}
System.out.println(operand1 + " " + operator + " " + operand2 +
" = " + String.format( "%.2f", result));
}
}
Output:
12.0 + 34.0 = 46.00
56.0 - 78.0 = -22.00
99.0 * 99.0 = 9801.00
10.0 / 3.0 = 3.33
As per method syntax.
<Access specifier><modifier><return type><method name>(arguments). If you are giving int as return type your method should return a value, else make the return type as void if you do not need any return value.
public class Test{
public static void main(String[] args) {
String a[] = { "12 + 34", "56 - 78", "99 * 99", "10 / 3" };
parseInt(a);
}
public static void parseInt(String[] a) {
int sum = 0;
for (int i = 0; i < a.length; i++) {
String[] pieces = a[i].split(" ");
if("+".equals(pieces[1])){
sum = Integer.valueOf(pieces[0]) + Integer.valueOf(pieces[2]);
}else if("-".equals(pieces[1])){
sum = Integer.valueOf(pieces[0]) - Integer.valueOf(pieces[2]);
}else if("*".equals(pieces[1])){
sum = Integer.valueOf(pieces[0]) * Integer.valueOf(pieces[2]);
}else {
sum = Integer.valueOf(pieces[0]) / Integer.valueOf(pieces[2]);
}
System.out.println("sum" + sum);
}
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am new to Java and I am currently playing with methods and classes. I have made a small program for calculations, but my methods for multiplication and division is always returning zero. Here are the classes:
Operator class:
public class Operators {
int add(int x, int y) {
int sum;
sum = x + y;
return sum;
}
int sub(int x, int y) {
int sum;
sum = x - y;
return sum;
}
int multiply(int x, int y) {
int sum;
sum = x * y;
return sum;
}
int divide(int x, int y) {
int sum;
sum = x / y;
return sum;
}
double sqrt(double x) {
double sum;
sum = Math.sqrt(x);
return sum;
}
}
Menu class:
public class Menu {
Operators operator = new Operators();
int a, b, addResult;
int c, d, subResult;
int e, f, mulResult;
int g, h, divResult;
double i, sqrResult;
Scanner inndata = new Scanner(System.in);
void chooseOperator(int what) {
switch (what) {
case '1' :
System.out.println("Type in the first number: ");
a = inndata.nextInt();
System.out.println("Type in the number you want to add: ");
b = inndata.nextInt();
addResult = operator.add(a,b);
System.out.println(a + " + " + b + " = " + addResult);
break;
case '2' :
System.out.println("Type in the first number: ");
c = inndata.nextInt();
System.out.println("Type in the number you want to subtract: ");
d = inndata.nextInt();
subResult = operator.sub(c,d);
System.out.println(c + " - " + d + " = " + subResult);
break;
case '3' :
System.out.println("Type in the first number: ");
e = inndata.nextInt();
System.out.println("Type in the number you want to multiply the first number with: ");
f = inndata.nextInt();
subResult = operator.multiply(e,f);
System.out.println(e + " * " + f + " = " + mulResult);
break;
case '4' :
System.out.println("Type in the first number: ");
g = inndata.nextInt();
System.out.println("Type in the number you want to dive the first number with: ");
h = inndata.nextInt();
subResult = operator.multiply(g,h);
System.out.println(g + " / " + h + " = " + divResult);
break;
case '5' :
System.out.println("Type in the number you want to square: ");
i = inndata.nextInt();
sqrResult = operator.sqrt(i);
System.out.println("The square root of " + i + " is " + sqrResult);
break;
}
}
void showMenu() {
System.out.println("Choose operation:");
System.out.println(" 1. add");
System.out.println(" 2. subtract");
System.out.println(" 3. multiply");
System.out.println(" 4. divide");
System.out.println(" 5. square root");
System.out.print("Choose one (q to quit): ");
}
boolean isValid(char ch) {
if (ch < '1' || ch > '5' && ch != 'q' ) return true;
else return false;
}
}
The println command for both case 3 and 4 always shows that (e,f) and (g,h) are caught in the right way, but the math operation always returns 0. Can anyone see whats wrong?
Problem lies with copy & paste.
Change:
subResult = operator.multiply(e,f);
to:
mulResult = operator.multiply(e,f);
Same for case 4:
divResult = operator.divide(g,h);
System.out.println(g + " / " + h + " = " + divResult);
In case 4, you are still calling
operator.multiply(g,h);
I think you meant
operator.divide(g,h);
But - beware! Diving integers will always give an integer result, any decimal part in the 'real' answer will be truncated, e.g. 1/2 = 0, 3/2 = 1.
This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 9 years ago.
I'm doing a program that presents the student with a math quiz. I am having trouble figuring out how to take the input problem type and turning that string into the arithmetic operator. Here is the method for that part of the code. Please and thanks!
public static String getUserChoice(String choice) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the symbol that corresponds to one of the following problems\n"
+ "Addition (+)\n Subtraction (-)\n or Multiplication (*): ");
choice = in.next();
if ("+".equals(choice)){
return +;
}
}
return choice;
Update
Here's the entire code if it helps see what I am doing.
public static void main(String[] args) {
int digit = 0;
int random = 0;
String result1 = getUserChoice("");
digit = getNumberofDigit1(digit);
int number1 = getRandomNumber1(digit);
int number2 = getRandomNumber2(digit);
System.out.println(number1 + result1 + number2);
getCorrectAnswer(number1, result1, number2);
}
public static String getUserChoice(String choice) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the symbol that corresponds to one of the following problems\n"
+ "Addition (+)\n Subtraction (-)\n or Multiplication (*): ");
choice = in.next();
return choice;
}
public static int getNumberofDigit1(int digit) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a 1 for problems with one digit, or a 2 for two-digit problems: ");
digit = in.nextInt();
return digit;
}
public static int getRandomNumber1(int numbers) {
int random = 0;
if (numbers == 1) {
random = (int) (1 + Math.random() * 9);
} else if (numbers == 2) {
random = (int) (10 + Math.random() * 90);
}
return random;
}
public static int getRandomNumber2(int numbers) {
int random2 = 0;
if (numbers == 1) {
random2 = (int) (1 + Math.random() * 9);
} else if (numbers == 2) {
random2 = (int) (10 + Math.random() * 90);
}
return random2;
}
public static void getCorrectAnswer(int number1, String result1, int number2) {
}
public static void getUserAnswer() {
Scanner in = new Scanner(System.in);
}
public static void CheckandDisplayResult() {
}
here is the one approach to your problem:
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
final String result1 = getUserChoice();
final int digit = getNumberofDigit1();
final int number1 = getRandomNumber(digit);
final int number2 = getRandomNumber(digit);
System.out.println(number1 + result1 + number2);
final int userAnswer = input.nextInt();
final int correctAnswer = getCorrectAnswer(number1, result1, number2);
System.out.println( (userAnswer == correctAnswer) ? "Ok" : ("Wrong, right is: " + correctAnswer));
input.close();
}
public static String getUserChoice() {
System.out.println("Please enter the symbol that corresponds to one of the following problems\n" + "Addition (+)\n Subtraction (-)\n or Multiplication (*): ");
return input.next();
}
public static int getNumberofDigit1() {
System.out.println("Enter a 1 for problems with one digit, or a 2 for two-digit problems: ");
return input.nextInt();
}
public static int getRandomNumber(final int numbers) {
return (int) ( (numbers == 1) ? (1 + Math.random() * 9) : (10 + Math.random() * 90) );
}
public static int getCorrectAnswer(final int number1, final String result1, final int number2) {
if ("+".equals(result1))
return number1+number2;
else if ("-".equals(result1))
return number1-number2;
else if ("*".equals(result1))
return number1*number2;
return -1;
}
and here is a little bit another getCorrectAnswer part:
public interface IMyOperator {
public int operation(final int a, final int b);
};
static class classSum implements IMyOperator {
public int operation(final int a, final int b) {
return a+b;
}
}
static class classSub implements IMyOperator {
public int operation(final int a, final int b) {
return a-b;
}
}
static class classMul implements IMyOperator {
public int operation(final int a, final int b) {
return a*b;
}
}
final static HashMap<String, IMyOperator> operators = new HashMap<String, IMyOperator>(3) {{
put("+", new classSum());
put("-", new classSub());
put("*", new classMul());
}};
public static int getCorrectAnswer(final int number1, final String result1, final int number2) {
return operators.get(result1).operation(number1, number2);
}
First, I want to show you how to test to see if it is what you want.
You can always check to make sure it is a string, or int, or w/e by doing the following.
Scanner scan = new Scanner(System.in);
while(scan.hasNext()) {
if(scan.hasNextInt()) {
int response = scan.nextInt();
}
}
Here is code for what you want to do.
import java.util.Random;
import java.util.Scanner;
public class Main {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
// Math Quiz v1.0 //
String printme = "Please choose the quiz type:\n\n"
+ "(1) Addition\n"
+ "(2) Subtraction\n"
+ "(3) Multiplication\n"
+ "(4) Division\n"
+ "(5) Modulus\n\n\n";
System.out.println(printme);
int reponse = in.nextInt();
// Setup //
int a = new Random().nextInt(100);
int b = new Random().nextInt(100);
int answer = -1;
switch(reponse) {
case 1:
System.out.println("What is " + a + " + " + b + "?");
answer = in.nextInt();
if(answer == a + b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 2:
System.out.println("What is " + a + " - " + b + "?");
answer = in.nextInt();
if(answer == a - b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 3:
System.out.println("What is " + a + " * " + b + "?");
answer = in.nextInt();
if(answer == a * b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 4:
System.out.println("What is " + a + " / " + b + "?");
answer = in.nextInt();
if(answer == a / b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 5:
System.out.println("What is " + a + " % " + b + "?");
answer = in.nextInt();
if(answer == a % b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
default:
System.out.println("Error, enter an integer between 1 & 5.");
break;
}
}
}