public static int evaluate(Scanner input)
{
if (input.hasNextInt())
{
return input.nextInt();
}
else
{
String operator = input.next();
int operand1 = evaluate(input);
int operand2 = evaluate(input);
return evaluate(operator, operand1, operand2);
}
}
// pre : operator is one of *, /, %, + or -
// post: returns the result of applying the given operator to
// the given operands
public static int evaluate(String operator, int operand1, int operand2)
{
if (operator.equals("*"))
{
return operand1 * operand2;
}
else if (operator.equals("/"))
{
return operand1 / operand2;
}
else if (operator.equals("%"))
{
return operand1 % operand2;
}
else if (operator.equals("+"))
{
return operand1 + operand2;
}
else if (operator.equals("-"))
{
return operand1 - operand2;
}
else
{
throw new RuntimeException("illegal operator " + operator);
}
}
I want to take this code and convert it to 2 stacks (one stack for the operators and the other stack for the operands) for using prefix expressions in a user-input GUI with an actionlistener. How can I write the code to convert this code to 2 stacks? By the way, this is homework and I understand that you're not allowed to give me the answers outright, so if you can provide me easy-to-understand pseudo code, that will be much appreciated. Thank you for your help.
Your pseudo is here:
public static int evaluate(Scanner input)
{
if (input.hasNextInt())
{
int stack_top_value=input.nextInt();
stack_for_operand.push(stack_top_value);
return stack_top_value;
}
else
{
String operator = input.next();
stack_for_operator.push(operator);
int operand1 = evaluate(input);
int operand2 = evaluate(input);
return evaluate(operator, operand1, operand2);
}
}
Related
I want to do a simple beginner project using methods, if statements, and user input. I am having an issue though with the calc() method. How can I return two different data types in java, and if I cannot, how could I do it, still by using more than the main method?
import java.util.Scanner; //allow user input
public class fourFunctionCalculator{
public static void main(String[] args) {
Scanner keyboardInput = new Scanner(System.in);
System.out.print("Enter your first number:"); //get first number
double num1 = keyboardInput.nextDouble();
System.out.print("Enter your operator: "); // get operator
String name = keyboardInput.next(); //grabs everything user types until a space
System.out.print("Enter your second number: "); //get second number
double num2 = keyboardInput.nextDouble();
System.out.println(calc(num1,op,num2));
}
//troublesome part is here
public static double calc(double num1, String op, double num2){
if (op == "+") {
return (num1 + num2);
}
else if (op == "-") {
return (num1 - num2);
}
else if (op == "*") {
return (num1 * num2);
}
else if (op == "/") {
return (num1 / num2);
}
else {
return ("INVALID OPERATOR");
}
}
}
you could generate a custom Exception, also you need to use the method .equals() inside the if validations, otherwise it is not going to work.
fourFunctionCalculator.java
import java.util.Scanner; //allow user input
public class fourFunctionCalculator{
public static void main(String[] args) {
Scanner keyboardInput = new Scanner(System.in);
System.out.print("Enter your first number:"); //get first number
double num1 = keyboardInput.nextDouble();
System.out.print("Enter your operator: "); // get operator
String name = keyboardInput.next(); //grabs everything user types until a space
System.out.print("Enter your second number: "); //get second number
double num2 = keyboardInput.nextDouble();
try {
System.out.println(calc(num1,name,num2));
} catch (InvalidOperatorException e) {
System.out.println(e);
}
}
public static double calc(double num1, String op, double num2){
if (op.equals("+")) {
return (num1 + num2);
}
else if (op.equals("-")) {
return (num1 - num2);
}
else if (op.equals("*")) {
return (num1 * num2);
}
else if (op.equals("/")) {enter code here
return (num1 / num2);
}
throw new InvalidOperatorException("INVALID OPERATOR : " + op);
}
}
InvalidOperatorException.java
public class InvalidOperatorException
extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidOperatorException(String errorMessage) {
super(errorMessage);
}
}
I recommend returning an OptionalDouble object as placeholder of something valid or not...
Ex #1: return OptionalDouble.of(num1 + num2); // first if outcome
Ex #2: return OptionalDouble.empty(); // for the last else
Then your main(...) method needs to be something like...
System.out.println(calc(num1,op,num2).orElseThrow(() -> new IllegalArgumentException("INVALID OPERATOR")));
I suggest returning always String.
public static String calc(double num1, String op, double num2){
if (op == "+") {
return String.valueOf(num1 + num2);
}
else if (op == "-") {
return String.valueOf(num1 - num2);
}
else if (op == "*") {
return String.valueOf(num1 * num2);
}
else if (op == "/") {
return String.valueOf(num1 / num2);
}
else {
return ("INVALID OPERATOR");
}
}
One of the problems that I'm having is that I can't use Camel case. I have to use Pascal. I found out while correcting the below code that when I change the int to a double like our instructor wants, I get a cannot switch on a value of type double.
I am trying to look for something else to use instead of a switch that can get me the same functionality. Any help is appreciated. Thanks!
import java.util.Random;
import java.util.Scanner;
public class CalculatorWithMethods {
// scanner object creation
static Scanner input = new Scanner(System.in);
boolean mainloop = true;
public static void main(String[] args) {
//Declaring variables
double res;
//calling the method
double choice = getMenuOption();
switch (choice) {
case 1:
{
//calling the method to get the operands
double operand1 = getOperand("What is the first number?");
double operand2 = getOperand("What is the second number?");
res = add(operand1, operand2);
System.out.println(operand1 + " + " + operand2 + " = " + res);
break;
}
case 2:
{
//calling the method to get the operands
double operand1 = getOperand("What is the first number?");
double operand2 = getOperand("What is the second number?");
res = subtract(operand1, operand2);
System.out.println(operand1 + " - " + operand2 + " = " + res);
break;
}
case 3:
{
//calling the method to get the operands
double operand1 = getOperand("What is the first number?");
double operand2 = getOperand("What is the second number?");
res = multiply(operand1, operand2);
System.out.println(operand1 + " * " + operand2 + " = " + res);
break;
}
case 4:
{
//calling the method to get the operands
double operand1 = getOperand("What is the first number?");
double operand2 = getOperand("What is the second number?");
if (operand2 == 0) {
System.out.println("The Second Number is Double.NAN.");
} else {
//calling the method to get the operands
operand1 = getOperand("What is the first number?");
operand2 = getOperand("What is the second number?");
res = divide(operand1, operand2);
System.out.println(operand1 + " / " + operand2 + " = " + res);
}
break;
}
case 5:
{
double operand1 = getOperand("What is the lower limit ?");
double operand2 = getOperand("What is the upper limit ?");
res = random(operand1, operand2);
System.out.println("The Random Number is :" + res);
break;
}
}
}
//This method will perform the add operation
public static double add(double operand1, double operand2) {
return operand1 + operand2;
}
//This method will perform the subtract operation
public static double subtract(double operand1, double operand2) {
return operand1 - operand2;
}
//This method will perform the multiply operation
public static double multiply(double operand1, double operand2) {
return operand1 * operand2;
}
//This method will perform the division operation
public static double divide(double operand1, double operand2) {
return operand1 / operand2;
}
//This method returns the random number
public static double random(double x, double y) {
Random generator = new Random();
return generator.nextInt((int)(y - x) + 1) + x;
}
//This method will get the operands entered by the user
public static double getOperand(String str) {
System.out.print(str);
double num = input.nextDouble();
return num;
}
//This method will display the menu
public static int getMenuOption() {
int choice;
// user interaction until quit performed.
while (true) {
// displaying menu
System.out.println("\nMenu\n1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Generate Random Number\n6. Quit");
// ask user choice
System.out.println("What would you like to do?");
choice = input.nextInt();
if (choice < 1 || choice > 5) {
System.out.println("** Invalid Choice **");
continue;
} else {
return choice;
}
}
}
}
After this:
//calling the method
double choice = getMenuOption();
do this:
long intCastedChoice = (long)choice;
Then switch the intCastedChoice instead.
I have the following pseudocode and need to write a java method to evaluate a prefix expression:
Algorithm valueOfPrefixExpression(prefixExpression)
Input: a valid positive-integer arithmetic expression in prefix form
Return value: the value of the prefix expression
if next token is an integer
return the integer
else
Read an operator, say op
firstOperand gets valueOfPrefixExpression(remainingExpression)
secondOperand gets valueOfPrefixExpression(remainingExpression)
return firstOperand op secondOperand
endif
How can I write this method? I tried this and I think it could be right but I am getting a "missing return statement" error so I can't compile. Assume method is only called if args has 1 or more elements. (no empty arrays)
public static int prefixAlgorithm(String[] args) {
for (int i = 0; i < args.length; i++) {
if (!args[i].equals("+") && !args[i].equals("-")
&& !args[i].equals("*") && !args[i].equals("/")) {
int operand = parseInt(args[i]);
return operand;
} else {
int firstOperand = prefixAlgorithm(Arrays.copyOfRange(args, i, (args.length - 1)));
int secondOperand = prefixAlgorithm(Arrays.copyOfRange(args, i, (args.length - 1)));
if (args[i].equals("+")) {
return firstOperand + secondOperand;
} else if (args[i].equals("-")) {
return firstOperand - secondOperand;
} else if (args[i].equals("*")) {
return firstOperand * secondOperand;
} else if (args[i].equals("/")) {
return firstOperand / secondOperand;
}
}
}
}
PrefixEvaluator with input and Scanner:
import java.util.*;
public class PrefixEvaluator {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("This program evaluates prefix expressions");
System.out.println("for operators +, -, *, / and %");
System.out.print("expression? ");
System.out.println("value = " + evaluate(console));
}
// pre : input contains a legal prefix expression
// post: expression is consumed and the result is returned
public static double evaluate(Scanner input) {
if (input.hasNextDouble()) {
return input.nextDouble();
} else {
String operator = input.next();
double operand1 = evaluate(input);
double operand2 = evaluate(input);
return evaluate(operator, operand1, operand2);
}
}
// pre : operator is one of +, -, *, / or %
// post: returns the result of applying the given operator to
// the given operands
public static double evaluate(String operator, double operand1,
double operand2) {
if (operator.equals("+")) {
return operand1 + operand2;
} else if (operator.equals("-")) {
return operand1 - operand2;
} else if (operator.equals("*")) {
return operand1 * operand2;
} else if (operator.equals("/")) {
return operand1 / operand2;
} else if (operator.equals("%")) {
return operand1 % operand2;
} else {
throw new RuntimeException("illegal operator " + operator);
}
}
}
PrefixEvaluator with no input and queue:
import java.util.*;
public class PrefixEvaluator {
public static void main(String[] args) {
String input = "- * + 4 3 2 5";
String[] expression = input.split ( " " );
Queue<String> expressionQueue = new LinkedList<String>();
for (String element : expression)
{
expressionQueue.add ( element );
}
System.out.println("value = " + evaluate(expressionQueue));
}
// pre : input contains a legal prefix expression
// post: expression is consumed and the result is returned
public static double evaluate(Queue <String> input) {
if(input.peek ( ) != null && input.peek ( ).matches ( "^(-?)\\d+$" ))
{
return Long.parseLong ( input.poll ( ) );
}
else
{
String operator = input.poll();
double operand1 = evaluate(input);
double operand2 = evaluate(input);
return evaluate(operator, operand1, operand2);
}
}
// pre : operator is one of +, -, *, / or %
// post: returns the result of applying the given operator to
// the given operands
public static double evaluate(String operator, double operand1,
double operand2) {
if (operator.equals("+")) {
return operand1 + operand2;
} else if (operator.equals("-")) {
return operand1 - operand2;
} else if (operator.equals("*")) {
return operand1 * operand2;
} else if (operator.equals("/")) {
return operand1 / operand2;
} else if (operator.equals("%")) {
return operand1 % operand2;
} else {
throw new RuntimeException("illegal operator " + operator);
}
}
}
I/O Example:
This program evaluates prefix expressions
for operators +, -, *, / and %
expression? - * + 4 3 2 5
value = 9.0
Documentation:
Queues: Queue (Java Platform SE 7 )
Patterns: Pattern (Java Platform SE 7 )
Your compilation problem is because you don't have a guaranteed return from the method. If arg[i] is something other than one of the four expected characters for the entire array, you'll simply run off the bottom of the function.
You may believe that the input will always conform to expectations, but compilerse know better than to trust humans. :-)
private class InputListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// Create an integer and character stack
Stack<Integer> operandStack = new Stack<Integer>();
Stack<Character> operatorStack = new Stack<Character>();
// User input in input text field
String input = inputTextField.getText();
// Create string tokenizer containing string input
StringTokenizer strToken = new StringTokenizer(input);
// Loop while there are tokens
while (strToken.hasMoreTokens())
{
String i = strToken.nextToken();
int operand;
char operator;
try
{
operand = Integer.parseInt(i);
operandStack.push(operand);
}
catch (NumberFormatException nfe)
{
operator = i.charAt(0);
operatorStack.push(operator);
}
}
// Loop until there is only one item left in the
// operandStack. This one item left is the result
while(operandStack.size() > 1)
{
// Perform the operations on the stack
// and push the result back onto the operandStack
operandStack.push(operate(operandStack.pop(),
operandStack.pop(), operatorStack.pop()));
}
// Display the result as a string in the result text field
resultTextField.setText(Integer.toString(operandStack.peek()));
}
// Sum and product computed
public int operate(Integer operand1, Integer operand2, char operator)
{
switch(operator)
{
case '*':
return operand2 * operand1;
case '/':
return operand2 / operand1;
case '%':
return operand2 % operand1;
case '+':
return operand2 + operand1;
case '-':
return operand2 - operand1;
default:
throw new IllegalStateException("Unknown operator " + operator + " ");
}
}
}
The prefix expression code provided is incorrectly evaluating expressions with more than one operator. The expression: * + 16 4 + 3 1 should evaluate to 80 = ((16 + 4) * (3 + 1)), but instead it evaluates to 128, which I think is evaluating as: ((16 + 4) * (3 + 1) + (16 * 3)). How do I edit the code to correct this problem? Thank you for your help.
In prefix evaluation,Important thing to remember is
operand 1= pop();
operand 2= pop();
and say the operator is -
The value that is pushed is operand 1 - operand 2 and not operand 2 - operand 1
But something else is causing * + 16 4 + 3 1 to evaluate to 128.
I used the following algo for evaluating in java and it works fine
1.Take the prefix expression as a string in a variable with characters separated by single space.
2.Traverse the string from index length-1 to 0
3.If its a number, perform push ,and if its a multidigit number,first obtain the full number and then push it
4.If its an operator then simply do the thing which i mentioned in beginning of the answer.
It is a simple code.
import java.io.*;
import java.util.*;
class PREFIXEVAL
{
public static void main(String []args)throws IOException
{
String p,n="";StringBuffer b;int i,op1,op2;char c;Stack<Integer> s=new Stack<Integer>();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the prefix expression separated by spaces");
p=br.readLine();
i=p.length()-1;
while(i>=0)
{
c=p.charAt(i);
if(c>=48&&c<=57)
n=n+c;
else if(c==' '&&!n.equals(""))
{/*handles both single and multidigit numbers*/
b=new StringBuffer(n);b.reverse();n=b.toString();
s.push(Integer.parseInt(n));n="";
}
else
{
if(c=='+')
{
op1=s.pop();
op2=s.pop();
s.push(op1+op2);
}
else if(c=='-')
{
op1=s.pop();
op2=s.pop();
s.push(op1-op2);
}
else if(c=='*')
{
op1=s.pop();
op2=s.pop();
s.push(op1*op2);
}
else if(c=='%')
{
op1=s.pop();
op2=s.pop();
s.push(op1%op2);
}
else if(c=='/')
{
op1=s.pop();
op2=s.pop();
s.push(op1/op2);
}
}
i--;
}
System.out.println("the prefix expression evaluates to "+s.peek());
}
}
I'm new to Java programming. I am trying to make a Fraction Calculator but when I try to run the program it gives me an error. The error is with the Switch statements but I don't know what happened.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Welcome to My FracCalc");
boolean continueProcessing = true;
while (continueProcessing) {
System.out.println("Type an expression and press <enter>");
String Operand1 = console.next();
if (Operand1.equals("quit")) {
continueProcessing = false;
System.out.println("Good bye!");
break;
} else {
Operand1 = parseFullNumber(Operand1);
}
String Operator = console.next();
if (Operator.equals("quit")) {
continueProcessing = false;
System.out.println("Good bye!");
break;
} else if (Operator.equals("+") || Operator.equals("-") || Operator.equals("/") || Operator.equals("*")) {
} else {
throw new ArithmeticException();
}
String Operand2 = console.next();
if (Operand2.equals("quit")) {
continueProcessing = false;
System.out.println("Good bye!");
break;
} else {
Operand2 = parseFullNumber(Operand2);
}
System.out.println( Operand1 + " " + Operator + " " + Operand2);
//System.out.println("First Fraction is: " + Operand1);
//System.out.println("Operator is: " + Operator);
//System.out.println("Second Fraction is: " + Operand2);
float answer;
System.out.println(Operator);
switch (Operator) {
case "+":
answer = Operand1 + Operand2;
break;
case "-":
answer = Operand1 - Operand2;
break;
case "*":
answer = Operand1 * Operand2;
break;
case "/":
answer = Operand1 / Operand2;
break;
}
}
}
public static String parseFullNumber(String input) {
int wholeNumber = 0;
int numerator = 0;
int denominator = 0;
;
int underscoreId = input.indexOf('_');
int slashId = input.indexOf('/');
// Check for underscore "_" //
if (underscoreId > -1) {
wholeNumber = Integer.parseInt(input.substring(0, underscoreId));
numerator = Integer.parseInt(input.substring(underscoreId + 1, slashId));
denominator = Integer.parseInt(input.substring(slashId + 1, input.length()));
} else {
if (slashId > -1) {
// no underscore but there is a slash //
numerator = Integer.parseInt(input.substring(0, slashId));
denominator = Integer.parseInt(input.substring(slashId + 1, input.length()));
} else {
// there is no underscore or slash //
wholeNumber = Integer.parseInt(input);
}
}
return simplify(wholeNumber, numerator, denominator);
}
//simplifying fractions //
public static String simplify(int wholeNumber, int numerator, int denominator) {
// absolute values //
int absNumerator = Math.abs(numerator);
// factor if applicable //
if (absNumerator > 1) {
int commonFactor = 1;
for (int i = 2; i < Math.min(absNumerator, denominator); i++) {
if (numerator % i == 0 && denominator % i == 0) {
commonFactor = i;
}
}
numerator /= commonFactor;
denominator /= commonFactor;
}
// reduce if applicable //
if (absNumerator > denominator) {
int reduction = numerator / denominator;
if (wholeNumber >= 0) {
wholeNumber += reduction;
} else {
wholeNumber -= reduction;
}
numerator %= denominator;
}
// prints //
if (wholeNumber != 0) {
if (numerator != 0) {
return wholeNumber + "_" + numerator + "/" + denominator;
} else {
return String.valueOf(wholeNumber);
}
} else {
if (numerator != 0) {
return numerator + "/" + denominator;
} else {
return String.valueOf(0);
}
}
}
}
Here is the error i got:
Exception in thread "main" java.lang.Error:
Unresolved compilation problems:
Type mismatch:
cannot convert from String to float The operator - is undefined for the argument type(s) java.lang.String, java.lang.String
The operator * is undefined for the argument type(s) java.lang.String, java.lang.String
The operator / is undefined for the argument type(s) java.lang.String, java.lang.String
at FracCalcApp.main(FracCalcApp.java:53)
Operand1 and Operand2 are String(s). You need to parse them before you can perform arithmetic. Something like,
double answer;
System.out.println(Operator);
switch (Operator) {
case "+":
answer = Double.valueOf(Operand1) + Double.valueOf(Operand2);
break;
case "-":
answer = Double.valueOf(Operand1) - Double.valueOf(Operand2);
break;
case "*":
answer = Double.valueOf(Operand1) * Double.valueOf(Operand2);
break;
case "/":
answer = Double.valueOf(Operand1) / Double.valueOf(Operand2);
break;
}
Finally, by convention, Java variables should start with a lower case letter; operand1, operand2 and operator.
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
float a = sc.nextFloat();
System.out.println("Enter second number");
float b = sc.nextFloat();
System.out.println("choose your operation");
char operator = sc.next().charAt(0);
float answer;
switch (operator){
case '+' :
answer = a +b;
System.out.println("Answer:"+answer);
break;
case '-' :
answer = a-b;
System.out.println("Answer:"+answer);
break;
case '*' :
answer = a*b;
System.out.println("Answer:"+answer);
break;
default:
answer = a/b;
System.out.println("Answer:"+answer);
}
}