Best way to change operators in string to their opposite - java

I have a string like: value += 5 * 3 - (2 / 4) for example.
Now I must change all operators to their opposite, so:
+ to -
- to +
* to /
/ to *
My problem is when I use replaceAll() function
First time:
string.replaceAll("+", "-"); I become: value -= 5 * 3 - (2 / 4)
Second time:
string.replaceAll("-", "+"); I become: value += 5 * 3 + (2 / 4)
but it's need to be: value -= 5 * 3 + (2 / 4)
How can I achive that?

You could create a Map with the Characters to replace and iterate through the String like this:
public static void main(String[] args) {
Map<Character, Character> replacers = new HashMap<>();
replacers.put('+', '-');
replacers.put('-', '+');
String value = "value += 5 * 3 - (2 / 4)";
StringBuilder out = new StringBuilder();
for (char c : value.toCharArray()) {
out.append(replacers.getOrDefault(c, c));
}
System.out.println(out.toString());
}
This will print out:
value -= 5 * 3 + (2 / 4)

Why not just loop through string char-by-char and replace single letter at a time to avoid such chaos?
public String revert(String expression){
char[] temp = expression.toCharArray();
for(int i = 0; temp.length> i; i++){
switch(temp[i]){
case '/':
temp[i] = '*';
break;
case '*':
temp[i] = '/';
break;
case '-':
temp[i] = '+';
break;
case '+':
temp[i] = '-';
break;
}
}
return new String(temp);
}

You could first replace your symbols (+,-,...) to some different ones that cannot be present in your expression e.g. +->A, -->B, ... and than all As to -, Bs to +, ... .
Other option is creating array of chars from your string and than iterate this array invert your symbols in situ. and than create String again.

I think a simple loop will work;
String exp="YOUR EXPRESSION HERE";
String newStr="";
//loop through the string
for(int i=0;i<exp.length();i++)
{
char ch=exp.charAt(i);//extract a charcter
switch(ch)
{
case '+':
newExp+='-';// replace + with -
break;
case '-':
newStr+='+';// and - with +
break;
case '*';
newStr+='/'// divide with *
break;
case '/'
newStr+='*';// multiply with /
break;
default:
newStr+=ch;// leave it as it is
}
}

You are probably better off just looping through the values, perhaps in a char array.
String val = "value += 5 * 3 - (2 / 4)";
char[] cArray = val.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cArray.length; i++) {
if (cArray[i] == '+') {
sb.append("-");
} else if (cArray[i] == '-') {
sb.append("+");
// repeat for others
} else {
sb.append(cArray[i]);
}
}
Output:
value -= 5 * 3 + (2 / 4)

Related

Random Math Question Generator not following while loop

I'm a new java coder getting into it doing a project. I coded it how i believe the system would execute it and yet it doesn't seem to be following the While loops requirements. I want it to generate random number, do a random operation, then ask the user for an answer. The answer must be not decimal and the random numbers must be below 10 to make the questions easier as its for a lower target audience. I'm kind of stuck now on this piece. Apologies if this doesn't make sense as i say it is a first attempt for me.
import java.util.Random;
import java.lang.Math;
import java.util.Scanner;
public class RandomisedQuestions{
public static void QuestionGenerator(){
Random r = new Random();
Scanner s = new Scanner(System.in);
int intA = 0;
int intB = 0;
char operator ='?';
double value = 1.2;
for (int i = 0; i < 3; i++) {
intA = (int)(10.0 * Math.random());//the (int) forces the number to be an int
intB = (int)(10.0 * Math.random());
if (intA <= 0 && intB <= 0){
intA = (int)(10.0 * Math.random());//the (int) forces the number to be an int
intB = (int)(10.0 * Math.random());
System.out.println(intA + intB);
}
while ((value % 1) !=0 && value > 1){//Runs while value is not whole
switch (r.nextInt(4)){
case 0: operator = '+';
value = intA+intB;
break;
case 1: operator = '-';
value = intA-intB;;
break;
case 2: operator = '*';
value = intA*intB;;
break;
case 3: operator = '/';
value = intA/intB;;
break;
default: operator = '?';
}
//System.out.println(operator);
}
System.out.println(intA +""+ operator +""+ intB);
System.out.println("Enter the answer");
int uGuess = s.nextInt();
if (uGuess == value){
System.out.println("Correct");
}
else{
System.out.println("Incorrect");
}
}
}
}
It's better to use ThreadLocalRandom.nextInt to generate your numbers:
// At the start of your program initialize the generator:
ThreadLocalRandom r = ThreadLocalRandom.current();
// Later use it:
do {
intA = ThreadLocalRandom.nextInt(1, 10);
intB = ThreadLocalRandom.nextInt(1, 10);
switch (r.nextInt(4)) {
case 0: operator = '+';
value = intA + intB;
break;
case 1: operator = '-';
value = intA - intB;
break;
case 2: operator = '*';
value = intA * intB;
break;
case 3: operator = '/';
value = (double)intA / intB;
break;
default: operator = '?';
}
} while (value != (int)value || value <= 1);
Also note the conversion to double in division case, otherwise the division will be performed for integer types.

java switch statement not ignoring the cases not listed

I want to ignore all other characters besides A, G, T, C, but when I put N at the end of the string, it prints out 00. the output should be 00 0101 1010 1111,
but it is 00 0101 1010 1111 00. I used the default case in the switch statement because I thought this would ignore all other characters besides the ones listed. Is there something I am doing wrong?
import java.util.BitSet;
public class Main {
public static void main(String[] args){
String originalString = "aCCGGAATTN";
int bitSetSize = 2 * originalString.length();
BitSet bitSet = new BitSet(bitSetSize);
originalString = originalString.toUpperCase();
for (int i = 0; i < originalString.length(); i++) {
switch(originalString.charAt(i)){
case 'A':
bitSet.clear(i * 2);
bitSet.clear(i * 2 + 1);
break;
case 'C':
bitSet.clear(i * 2);
bitSet.set(i * 2 + 1);
break;
case 'G':
bitSet.set(i * 2);
bitSet.clear(i * 2 + 1);
break;
case 'T':
bitSet.set(i * 2);
bitSet.set(i * 2 + 1);
break;
default:
break;
}
}
// print all the bits in the bitset
for (int i = 0; i < bitSetSize; i++) {
if (bitSet.get(i))
System.out.print("1");
else
System.out.print("0");
}
}
}
It's the the switch that's the problem, it's the fact that you're using indices into your original, unfiltered string, to decide which bits to set.
Use two different variables to keep track of the input and the output indices:
for (int i = 0, j = 0; i < originalString.length(); i++) {
switch(originalString.charAt(i)){
case 'A':
bitSet.clear(j * 2);
bitSet.clear(j * 2 + 1);
j++;
break;
...
}
}

String index out of range: 2.Doing calculation in Postfix expression style.

I'm making a RPN calculator, I have done the part of converting infix to postfix, now I want to evaluate the expression in postfix.
example:
converting from ((3 + 5 1)=8) 14 to 3 5 1 +8 = 14 (I have done that). now evaluating the latter expression.
The instructions I have:
Given a postx expression v 1:::v n,
where v i is either an operand or an operator,
the following algorithm evaluates the expression. A helper string, temp2, is
used during the calculation.
i = 1
while i<= n
if v_i is an operand: Push v_i to tmp2.
if v_i is
an operator: Apply v_i to the top two elements of tmp2. Replace
these by the result in tmp2.
i = i + 1
Output result from tmp2.
My code:
static int eval(String postfix) {
int result = 0;
String temp2 = "";
int num1, num2;
char operator;
for (int i = 0; i < postfix.length(); i++) {
char M = postfix.charAt(i);
// if v_i is an operand: Push v_i to tmp2.
if (Character.isDigit(postfix.charAt(i))) {
temp2 = M + temp2;
}
/*
* if v_i is an operator: Apply v_i to the top two elements of tmp2.
* Replace these by the result in tmp2.
*/
if (postfix.charAt(i) == '+' || postfix.charAt(i) == '-' || postfix.charAt(i) == '*'
|| postfix.charAt(i) == '/') {
temp2 = M + temp2.substring(2);
num1 = Character.getNumericValue(temp2.charAt(temp2.length() - 1));
operator = postfix.charAt(i);
num2 = Character.getNumericValue(temp2.charAt(temp2.length() + i - 1));
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
}
}
return result;
}
I get
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at:
num2 = Character.getNumericValue(temp2.charAt(temp2.length() + i - 1));

String index out of range when accessing chars in a String

I'm trying to make an RPN calculator. I have done the conversion from infix to postfix, now I want to evaluate the converted expression. When I enter any expression I get error
String index out of range: 1.
Here's my code with what I'm supposed to do in the program:
static int eval(String postfix) {
int result = 0;
String temp2 = "";
int num1, num2, OPS;
char operator;
String delete = "";
for (int i = 0; i < postfix.length(); i++) {
char M = postfix.charAt(i);
// if v_i is an operand: Push v_i to tmp2.
if (Character.isDigit(postfix.charAt(i))) {
temp2 = M + temp2;
}
/*
* if v_i is an operator: Apply v_i to the top two elements of tmp2.
* Replace these by the result in tmp2.
*/
if (postfix.charAt(i) == '+' || postfix.charAt(i) == '-' || postfix.charAt(i) == '*'
|| postfix.charAt(i) == '/') {
temp2 = M + temp2.substring(2);
}
while (postfix.charAt(0) != '0') {
num1 = Character.getNumericValue(temp2.charAt(temp2.length()-1));
delete = delete.substring(0,i);
operator = postfix.charAt(i);
num2 = Character.getNumericValue(temp2.charAt(temp2.length()+i));
//Integer.parseInt(postfix.substring(0,i));
result = num1 + num2;
result = num1 - num2;
result = num1 * num2;
result = num1 / num2;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
}
if (temp2.length() != 0) {
temp2 = result + temp2;
}
}
return result;
}
I get the error in this part:
while (postfix.charAt(0) != '0') {
num1 = Character.getNumericValue(temp2.charAt(temp2.length()-1));
delete = delete.substring(0,i);
operator = postfix.charAt(i);
num2 = Character.getNumericValue(temp2.charAt(temp2.length()+i));
//Integer.parseInt(postfix.substring(0,i));
As you can see, I have tried some different string manipulation but they're all incorrect.
My supervisor said something about reading the string from backwards or the last string or something, But I never understood what they meant. Thanks for any help in advance
temp2.charAt(temp2.length()+i)
You are accessing a character of the string with charAt. However temp2 contains temp2.length() characters. Hence you can acces them from index 0 to temp2.length() - 1. Hence accessing the character at position temp2.length()+i is out of range... (for i > 0 !!)
Take a look at your previous one, temp2.charAt(temp2.length()-1).
Here you accessed the last character of the string (at index temp2.length()-1). Any access with a greater index will result in an index out of range.
EDIT : The stop condition of your while loop is while (postfix.charAt(0) != '0'). In the loop you never change the postfix string. Hence if the condition is met (first character of postfix is not '0') you'll have an infinite loop. Hence you'll never reach the return statement.
Change this line
Character.getNumericValue(temp2.charAt(temp2.length()+i));
to
Character.getNumericValue(temp2.charAt(temp2.length()+i-1));

ArrayStack: getting wrong output on implementation

The program in java is to evaluate the post-fix arithmetic expression.
I am not getting any error in my program but I am getting the wrong output.
I am trying to evaluate the expression (1*(((2+3)*(4-5))+6)) where its result is 1.
But I am getting the output as 11.
Its post-fix expression is 1 2 3 + 4 5 - * 6 + *
Looking forward for your help.
Thank you!!
public static void evaluatePostfix(String sol)
{
ArrayStack<Double> nlist = new ArrayStack<Double> ();
double op1, op2, result;
char ch;
for (int i = 0; i < sol.length(); i++)
{
if ('0' <= sol.charAt(i) && sol.charAt(i) <= '9')
nlist.push((double)(sol.charAt(i) - '0'));
else
if (sol.charAt(i)=='+'||sol.charAt(i)=='-'||sol.charAt(i)=='*'||sol.charAt(i)=='/')
{
op1 = nlist.pop();
op2 = nlist.pop();
ch = sol.charAt(i);
switch(ch){
case '+':
nlist.push(op1 + op2);
break;
case '-':
nlist.push(op1 - op2);
break;
case '*':
nlist.push(op1 * op2);
break;
case '/':
nlist.push(op1 / op2);
break;
default:nlist.push(0.000);
}
}
}
result = nlist.pop();
System.out.println(result);
}
When you pop from the stack, op2 is the element at the top and op1 is at top-1. Change it to:
op2 = nlist.pop();
op1 = nlist.pop();
To be more clear if your postfix expression is 56 - (so 5-6 in infix) your stack is
| 6 |
| 5 |
and when you get the - you are doing nlist.push(op1 - op2); which pushes 6-5 into the stack while you should push 5-6.

Categories

Resources