I am using Stack class to calculate simple arithmetic expressions involving integers,
such as 1+2*3.your program would execute operations in the order given,without regarding to the precedence of operators.
*Thus, the expression 1+2*3 should be calculated (1+2)*3=9,not 1+(2*3)=7.
If i get the input as 1+2*3,i know how to convert the string 1,2,3 to Integer.but i don't know how to covert +,* from string type to operator.
My code logic is:
For eg: Given string 2 + (3 * 5), So 3 * 5 will be operated first then +2 will be performed in result of 3 * 5.
probably the best way to do it will be equals, but it's best to ignore whitespaces:
i'm not quite sure how you split your string, but for example, if you have a char op and two integer a and b:
String str = op.replace(" ", "");
if(str.equals("*")){
retVal = a*b;
} else if(str.equals("+")){
retVal = a+b;
}//etc
Do what Ogen suggested and manually check the operator. A quick shortcut to doing the if, else if .... structure is switch, that is
switch(operand) {
case "*":
break;
case "+":
break;
.....
default:
}
You will have to manually check and assign the operator. E.g.
if (s.equals("+")) {
// addition
}
Quick solution: Use below code for executing correct javascript Arithmetic expression in java.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine se = manager.getEngineByName("JavaScript");
try {
Object result = se.eval(val);
System.out.println(result.toString());
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Ok, assuming your assignment needs you to use the Stack class and you already have the logic to pick numbers ( including the negative numbers -- that would an operator followed by another operator in all but one cases) and operators and parens, what you could do is as follows.
If you encounter a number, pop the last two elements from your stack. The first item you pop will be an operator and the next will be a number. Evaluate the expression and push it into Stack and continue.
You can ignore the parenthesis. You will also have to handle the case of reading a number or parenthesis the first time.
Related
im doing an assignment which requires me to create 3 classes.
1 with getting 2 random integers,
1 with getting random operators such as + - * / which should be done so in char method
the last one to check if the simple mathematics answer is correct using booleans via user Scanner input.
i need a little help here as im not sure if i've done the random operators method correctly and am really lost at how i should tabulate both random int and operators together in one class.
here's the code i've done so far:
public static char getOperator (int x, int y)
{
char operator;
int answer;
switch (rand.nextInt(4))
{
case 0: operator = '+';
answer = x + y;
break;
case 1: operator = '-';
answer = x - y;;
break;
case 2: operator = '*';
answer = x * y;;
break;
case 3: operator = '/';
answer = x / y;;
break;
default: operator = '?';
}
return operator;
}
I believe you mean you need to create 3 methods (and not classes).
One that creates a random integer (it's a bad design to create a
method that returns two integers instead of just calling two times
one that returns one int).
One that returns a random operator
One that checks if an operation consisting of "random-number
random-operator random-number" is equal to user input
Anyways, there's a lot to unpack here, so:
Your first method getTwoIntegers is incorrect, you're asking for two integers in input but you never actually use them, then you return one random number.
The method getOperator needs to be redesigned to have no input and return one char (equal to + - x /).
Your final method will call the your first method twice, then the second method once, it will then print the operation for the user to see, and check if the response is correct.
Hopefully this can help you conceptualize better the way you should build your code.
I didn't post the source code since I believe it's much better for you if you try to do it by yourself (this being an assignment and all)
Good luck and have fun :)
I wrote the following code based on the Wikipedia algorithm for RPN using Stacks:
public static void reversePolish(String[] x){
Stack temp = new Stack();
Integer one;
Integer two;
Integer result;
for(String x1:x){
switch(x1){
case "+":
one = (Integer) temp.pop();
two = (Integer) temp.pop();
result = one+two;
System.out.println(one + "+"+two);
temp.push(result);
break;
case "-":
one = (Integer) temp.pop();
two = (Integer) temp.pop();
result = one+two;
temp.push(result);
break;
default :
temp.push(Integer.parseInt(x1));
}
}
result = (Integer) temp.pop();
System.out.println(result);
}
However it gives me an error:
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:102)
at java.util.Stack.pop(Stack.java:84)
at TestingItOut.reversePolish(TestingItOut.java:57)
at TestingItOut.main(TestingItOut.java:31)
C:\Users\Sanchit\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
I have absolutely no idea what raises the error. HELP NEEDED
I don't think throwing an EmptyStackException is the problem with your program - it runs perfectly well on my computer.
The reason that an EmptyStackException is thrown is probably the data you pass to reversePolish().
As an example, a valid input should be:
"1", "2", "+", "3", "-", "6", "+"
Which means 1+2-3+6. That is, if you wish to calculate a result with a binary operator and 2 operands, write the operands first and put the operator after them.
For more details, see Reverse Polish Notation.
So why was an EmptyStackException thrown?
Your algorithm is simple: on an operand, push it into a stack, on an operator, pop the operands, calculate the result, and push it back. The problem is, if the program finds an operator and the stack does not contain sufficient operands, it still tries to pop the 2 required operands, and, EmptyStackException.
To polish the algorithm, you can first check the size of stack before popping, and print a human-readable message saying "There's not enough operands!" instead of throwing an EmptyStackException. The code could be like this: (partial)
case "+":
if (temp.size() < 2) {
System.out.println("There's not enough operands!");
return;
}
one = (Integer) temp.pop();
two = (Integer) temp.pop();
result = one + two;
System.out.println(one + " + " + two);
temp.push(result);
break;
Something more.
In case you haven't noticed, you've written result = one + two; under case "-":, which I take as a simple typo error. It should be result = one - two.
And if you run the program in an environment equal to or higher than Java 1.5, Stack should contain an generic type. In your case, it should be Stack<Integer> temp = new Stack<Integer>();. (If you're in Java 7 or newer, you can write Stack<Integer> temp = new Stack<>(); for the sake of simplicity) And then you don't have to write one = (Integer) temp.pop();. one = temp.pop() is okay.
One more thing:
You simply write result = (Integer) temp.pop(); at the end, which is still not the perfect thing.
Imaging the input being "1", "2", "+", "3", "-", "6", "+", "7".
Translated, it's 1 + 2 - 3 + 6 7. If you write this down and give it to your teacher, you will get a zero mark, because there's no operator connecting 6 and 7 - that is, 7 is redundant.
However, if you give this to your program, it will output 7 instead of croaking some warnings. This is not the desired behavior.
So, the right thing to do is, write:
if (temp.size() == 1) {
result = (Integer) temp.pop();
System.out.println(result);
} else System.out.println("Redundant operands!");
Put the break; command and all of it seemed to work. Not gonna fiddle around with it too much now!
I'm still quite new to programming, so I'm sorry if I caused you to face palm.
Right now, I am trying to create parentheses-expander in Java. The current program can already expand the parentheses, but it can not simplify the results, because the terms are not in the descending order. I do understand that you could try to add the terms without re-ordering them by comparing the variables contained in each of the elements. However, I want the program to "show work" like a human, so I need the terms in descending order.
And for that, I want to create a method that, given a string arrayList, re-orders the elements in something like descending order for polynomials in math.
If any of the variables had exponents, the variable is just repeated to the number of the exponent.
for example:
X^2 = XX,
a^3 = aaa,
Z^5 = ZZZZZ
Also, there will be no negative exponents nor parentheses.
All elements have either + or - at the beginning(and no other operators after that).
All elements have a coefficient, even if it is 1.
Capital letters have higher importance than lower case letters, and elements with just numbers should be re-located to the very end.
I forgot the mathematical word for that, but the terms should be ordered in a interest of A, then B so on until Z, and then a,b,c,...so on.(I mean, terms with most A comes first, B second ,C third... up until z)
Coefficients and operators should be ignored.
For example, if the input was this:
[-1b,+3XX,-4AA,+1aaa,+20CCa,-9ABa,-9ABaa,+20CCCa,+3BBX,+1aab,+10]
Then I want the method to return the arrayList like:
[-4AA,-9ABaa,-9ABa,+3BBX,+20CCCa,+20CCa,+3XX,+1aaa,+1aab,-1b,+10]
I'm very much stuck right here. any help will be appreciated. If I didn't describe my problem clear enough, please let me know. I will clarify.
I believe wolfram alpha already has parentheses expanding capabilities. However, I still want to make this.
If anyone can help me with this, that will be amazing. Thanks in advance!
You have a couple of challenges that need to be dealt with individually:
How do I parse something like -1b into a format I can work with?
How do I sort by a custom sorting rule?
For the first part, your rule is very well-defined and the format is pretty simple. This lends itself well to using a regular expression to parse it:
Also, there will be no negative exponents nor parentheses. All elements have either + or - at the beginning(and no other operators after that). All elements have a coefficient, even if it is 1.
So a good regular expression format might be:
([-+]\d+)(\w+)?
This would result in two "capture groups". The first would be the numeric part, and the second would be the (optional) repeated string part.
After decomposing each entry into these two separate parts, it is pretty easy to come up with a set of rules for determining the sort order:
If both of them are numbers (having only the first part), then sort as numbers
If one of them is a number, and the other has letters, sort the number afterward.
If both have numbers and letters, sort according to the letters only using normal String sorting.
An easy way to do custom sorting is to write a custom Comparator class which would be used as an argument to the sort function. Combining all the ideas presented above that might look something like this:
public class PolynomialComparator implements Comparator<String> {
private static Pattern pattern = Pattern.compile("([-+]\\d+)(\\w+)?");
#Override
public int compare(String s1, String s2) {
if (s1 == null) throw new NullPointerException("s1");
if (s2 == null) throw new NullPointerException("s2");
int compare = 0;
Matcher m1 = pattern.matcher(s1);
Matcher m2 = pattern.matcher(s2);
if (!m1.matches()) throw new IllegalArgumentException("Invalid Polynomial format: " + s1);
if (!m2.matches()) throw new IllegalArgumentException("Invalid Polynomial format: " + s2);
int n1 = Integer.parseInt(m1.group(1));
int n2 = Integer.parseInt(m2.group(1));
String p1 = m1.group(2);
String p2 = m2.group(2);
if (p1 == null && p2 == null) { // Rule #1: just compare numbers
compare = n2 - n1;
} else if (p1 == null) { // Rule #2: always sort number last
compare = 1;
} else if (p2 == null) { // Rule #2: always sort non-number first
compare = -1;
} else { // Rule #3: compare the letters
compare = m1.group(2).compareTo(m2.group(2));
}
return compare;
}
}
Finally, to tie it all together, here is a simple program that correctly sorts your provided example using this Comparator (with the exception of your second and third entry which I believe is wrong in your example):
public static void main(String args[]){
String input = "[-1b,+3XX,-4AA,+1aaa,+20CCa,-9ABa,-9ABaa,+20CCCa,+3BBX,+1aab,+10]";
String[] array = input.substring(1, input.length() - 1).split(",");
Arrays.sort(array, new PolynomialComparator());
System.out.println("[" + String.join(",", array) + "]");
}
OUTPUT: [-4AA,-9ABa,-9ABaa,+3BBX,+20CCCa,+20CCa,+3XX,+1aaa,+1aab,-1b,+10]
Hopefully you can spend some time walking through this and learn a few ideas that will help you on your way. Cheers!
This question already has answers here:
How to convert String object to Boolean Object?
(16 answers)
Closed 7 years ago.
I am very, very new at programming so sorry if this is a stupid question, but I can't find an answer anywhere.
In a program that I am working on the user can choose one of five options for problems to practice: addition, subtraction, multiplication, division, and remainders. There is a scanner that asks them to put in the fist letter of the name of the types of problems they want to practice (A or a, S or s, M or m, D or d, R or r). I want to make an if/else statement that will print out different problems depending on which one they choose.
The problem is, from what I can tell if/else statements will only work with boolean variables, but boolean variables don't like strings or string variables. I have seen ways to convert specific strings to variables, but since the user is deciding on the string, I have no way to know what they are going to choose every time. Is there anyway to convert a string variable to a boolean variable?? (i.e. the boolean variable is true when the string variable = "A")
if(s) can take boolean expressions (and use boolean operators, such as or). For example, String.equals(Object) (or String.equalsIgnoreCase(String)). Something like,
if (string.equals("A") || string.equals("a")) {
// ...
} else if (string.equalsIgnoreCase("B")) {// <-- or equalsIgnoreCase(String).
// ...
}
Personally, my favorite way is to use a switch statement when you're dealing with input, and while it doesn't use boolean values as you are use to in an if statement, for me it feels cleaner.
Your code would look like something such as:
switch(userInput.toLowerCase())
{
case "a":
// addition code
break;
case "s":
// subtraction code
break;
case "m":
// multiplication code
break;
case "d":
// division code
break;
case "r":
// remainder code
break;
default: // every other option besides (a, s, m, d, and r)
// print some error, user put wrong input
break;
}
Ypu can use
java.lang.Boolean(String s)
Allocates a Boolean object representing the value true if the string
argument is not null and is equal, ignoring case, to the string
"true".
Here's what you can do.You're dealing with a fairly simple problem.
Pseudo-Code
if(input=="A")
{
Do Addition
}
if(input=="M")
{
Do Multiplication
}
else
{
Give Error
}
Essentially, you want to check if the user input is equal to a particular string. You use the double equal to operator (==) here to perform the check.If the condition is TRUE and it will enter the block.
The Point is that the if block is evaluated on the basis of any expression that results into boolean values(i.e. true or false).
So there is no need to convert a String to Boolean.
All you have to do is just check if input string meets your criteria using a method provided by String Class in java called String.equals(String) or String.equalsIgnoreCase(String);
The return type of above methods is boolean (primitive) which will be evaluated by if statement as per your requirements.
To explore String Class in java
run "javap java.lang.String" on shell/bash/command prompt for programmer's guide to check out the contents of String Class
So your code will be something like
if(input.equalsIgnoreCase("a"))
{
// Calculations for addition
}
else if(input.equalsIgnoreCase("s"))
{
// Calculations for Substraction
}
Instead you can use switch-case as support for String in switch-case has been included from jdk7.
Also switch-case should be faster in this case as it will not check all cases as done by else if.
switch(input)
{
case "a":
case "A":
// Calculations for addition
break;
case "s":
case "S"
// Calculations for subtraction
break;
case "m":
case "M":
// Calculations for multiplication
break;
case "d":
case "D":
// Calculations for division
break;
case "r":
case "R":
// Calculations for remainder
break;
default: // for any other option besides above
// whatever handling you wanna do for wrong input
break;
}
I have a doubt which follows.
public static void main(String[] args) throws IOException{
int number=1;
System.out.println("M"+number+1);
}
Output: M11
But I want to get it printed M2 instead of M11. I couldn't number++ as the variable is involved with a for loop, which gives me different result if I do so and couldn't print it using another print statement, as the output format changes.
Requesting you to help me how to print it properly.
Try this:
System.out.printf("M%d%n", number+1);
Where %n is a newline
Add a bracket around your sum, to enforce the sum to happen first. That way, your bracket having the highest precedence will be evaluated first, and then the concatenation will take place.
System.out.println("M"+(number+1));
It has to do with the precedence order in which java concatenates the String,
Basically Java is saying
"M"+number = "M1"
"M1"+1 = "M11"
You can overload the precedence just like you do with maths
"M"+(number+1)
This now reads
"M"+(number+1) = "M"+(1+1) = "M"+2 = "M2"
Try
System.out.println("M"+(number+1));
Try this:
System.out.println("M"+(number+1));
A cleaner way to separate data from invariants:
int number=1;
System.out.printf("M%d%n",number+1);
System.out.println("M"+number+1);
Here You are using + as a concatanation Operator as Its in the println() method.
To use + to do sum, You need to Give it high Precedence which You can do with covering it with brackets as Shown Below:
System.out.println("M"+(number+1));
System.out.println("M"+number+1);
String concatination in java works this way:
if the first operand is of type String and you use + operator, it concatinates the next operand and the result would be a String.
try
System.out.println("M"+(number+1));
In this case as the () paranthesis have the highest precedence the things inside the brackets would be evaluated first. then the resulting int value would be concatenated with the String literal resultingin a string "M2"
If you perform + operation after a string, it takes it as concatenation:
"d" + 1 + 1 // = d11
Whereas if you do the vice versa + is taken as addition:
1 + 1 + "d" // = 2d