I was hoping somebody could help me with with this. I am trying to add a constructor to allow the input of polynomial data from a string in the form 3x^y and put the coefficient, variable, and exponent values into the corresponding variables defined in a class. The constructor I have implemented allows the program to compile, but will freeze when running the application if...
this:
trinomial[0] = new Term (3,'x',2);
is set to:
trinomial[0] = new Term ("3x^y");
Basically, I'm trying to get the defined class to accept both forms of input (string and double/char/exponent formats). Any help with this would be greatly appreciated.
public class TrinomialTest {
static void printTrinomial(Term[] x) {
for (int i = 0; i < x.length; i++) {
//AUTOMATICALLY CALLS TOSTRING() WHEN PRINTLN
System.out.print(x[i]);
}
}
public static void main(String[] args) {
Term[] trinomial = new Term[3];
trinomial[0] = new Term(3, 'x', 2);
trinomial[1] = new Term(12, 'x', 1);
trinomial[2] = new Term(-23, 'x', 0);
printTrinomial(trinomial);
}
}
class Term {
private double coefficient; //the number
private char variable; // the letter
private int exponent;
public Term(double c, char v, int e) {
coefficient = c;
variable = v;
exponent = e;
}
//New Constructor
public Term(String Term) {
String c = "";
String v = "";
String e = "";
int exponentIndex = 0;
exponentIndex = Term.indexOf("^");
if (Term.substring(0, 1).matches("[0-9]")) {
c = Term.substring(0, 1);
v = Term.substring(1, 2);
} else {
c = "0";
v = Term.substring(0, 1);
}
do {
e = Term.substring(exponentIndex, exponentIndex + 1);
} while (Term.indexOf("^") != -1);
coefficient = Double.parseDouble(c);
variable = v.charAt(0);
exponent = Integer.parseInt(e);
}
public String toString() {
int c = (int) coefficient;
if (exponent == 1 && c > 0)
return ("" + "+" + c + variable);
else if (exponent == 1 && c < 0)
return ("" + c + variable);
else if (exponent == 0 && c > 0)
return ("" + "+" + c);
else if (exponent == 0 && c < 0)
return ("" + c);
return ("" + c + variable + "^" + exponent);
}
}
Simple solution:
String term = "32x^33";
String[] tokens = term.split("\\^");
String coeff = tokens[0].substring(0, tokens[0].length()-1);
String var = tokens[0].substring(tokens[0].length()-1, tokens[0].length());
String exp = tokens[1];
System.out.println("coeff = "+coeff+", var = "+var+", exp = "+exp);
Related
I am working on this simple program that adds two polynomials. However, I am getting wrong results and could not spot the mistake.
import java.util.LinkedList;
public class Polynomial {
private LinkedList<Term> terms = new LinkedList<Term>();
private class Term {
private int coef;
private int exp;
public Term(int coef, int exp) {
this.coef = coef;
this.exp = exp;
}
public int getCoef() {
return coef;
}
public int getExp() {
return exp;
}
public String toString() {
return (this.coef + "x^" + this.exp);
}
}
public String addPoly(String first, String second) {
LinkedList<Term> otherTerms = new LinkedList<Term>();
String result = "";
String [] termsArray1 = first.split(";");
String [] termsArray2 = second.split(";");
for (int i = 0; i < termsArray1.length; i++) {
String [] temp = termsArray1[i].split("x\\^");
int currentCoef = Integer.parseInt(temp[0]);
int currentExp = Integer.parseInt(temp[1]);
Term currentTerm = new Term(currentCoef, currentExp);
terms.add(currentTerm);
}
for (int i = 0; i < termsArray2.length; i++) {
String [] temp = termsArray2[i].split("x\\^");
int currentCoef = Integer.parseInt(temp[0]);
int currentExp = Integer.parseInt(temp[1]);
Term currentTerm = new Term(currentCoef, currentExp);
otherTerms.add(currentTerm);
}
int i = 0;
int j = 0;
while (true){
if(i == terms.size() || j == otherTerms.size()) {
break;
}
if(terms.get(i).getExp() < otherTerms.get(j).getExp()) {
result += (otherTerms.get(j).toString() + ";");
j++;
}
if(terms.get(i).getExp() > otherTerms.get(j).getExp()) {
result += (terms.get(i).toString() + ";");
i++;
}
if(terms.get(i).getExp() == otherTerms.get(j).getExp()) {
Term temp = new Term((terms.get(i).getCoef() + otherTerms.get(j).getCoef()), terms.get(i).getExp());
result += (temp.toString() + ";");
i++;
j++;
}
}
result = result.substring(0, result.length()-1);
return result;
}
}
::Test::
String s3 = "5x^2;-4x^1;3x^0";
String s4 = "6x^4;-1x^3;3x^2";
Polynomial p = new Polynomial();
System.out.println(p.addPoly(s4, s3));
Expected result: 6x^4;-1x^3;7x^2;-4x^1;3x^0
Actual result: 3x^4;7x^2;-1x^1;10x^0
The problem is that when your loop exits, one of the following can still be true:
i < terms.size()
j < j == otherTerms.size()
And this is the case with your example input. This means that part of one of the terms has not been processed and integrated into the output.
A second problem is that your multiple if statements are not exclusive; after the first if block is executed and j++ has executed, it might well be that j is an invalid index in otherTerms when the second if is evaluated. This should be avoided by turning the second and third if into else if.
Here is a fix for that loop:
while (i < terms.size() || j < otherTerms.size()) {
if(i == terms.size() || j < otherTerms.size() && terms.get(i).getExp() < otherTerms.get(j).getExp()) {
result += (otherTerms.get(j).toString() + ";");
j++;
}
else if(j == otherTerms.size() || i < terms.size() && terms.get(i).getExp() > otherTerms.get(j).getExp()) {
result += (terms.get(i).toString() + ";");
i++;
}
else if(terms.get(i).getExp() == otherTerms.get(j).getExp()) {
Term temp = new Term((terms.get(i).getCoef() + otherTerms.get(j).getCoef()), terms.get(i).getExp());
result += (temp.toString() + ";");
i++;
j++;
}
}
Better approach
Your approach is not really OOP. Ideally, the first expression should serve to create one instance of Polynomial and the other expression should serve to create another instance of Polynomial. Then there should be a method that can add another Polynomial instance to the own instance. Finally there should be a toString method that returns the instance as a string in the required format. Your driver code would then look like this:
Polynomial a = new Polynomial("5x^2;-4x^1;3x^0");
Polynomial b = new Polynomial("6x^4;-1x^3;3x^2");
Polynomial sum = a.addPoly(b);
System.out.println(sum.toString());
This is much more object oriented, and will automatically avoid the code repetition that you currently have.
I am trying to get my Binary to Decimal method to calculate properly. I have to use the multiply and/or divide methods in the "bToD" method. I can't figure out how to get it return the answer correct. It should only be returning "5", but instead it is returning 45. I need to fix this method in order to continue the remaining Hexadecimal to Binary and Octal to Binary methods.
package numType;
import java.util.Scanner;
public class numType{
public static String multiply2(String n) { //return 2*n
String r = "";
int c = 0;
for (int i = n.length()-1; i >= 0; i--) {
int p = (n.charAt(i)-'0')*2+c;
c = p/10;
r = p%10+r;
}
if (c > 0)
r = c+r;
return r;
}
public static String divide2(String n) { //return n/2
String r = "";
int b = 0;
int i = 0;
if (n.charAt(0) < '2') {
b = 1;
i = 1;
}
for (; i < n.length(); i++) {
int p = (n.charAt(i)-'0')+b*10;
b = p%2;
r += p/2;
}
if (r.length() == 0)
r = "0";
return r;
}
//convert binary string b to an equivalent decimal string.
public static String bToD(String b)
{
String s = "";
int n = 0;
if (b.charAt(b.length()-1) == '1')
n = 1;
else
n = 0;
int pow = 1; //INITIALIZE POWER # FROM THE SECOND TO LAST 2^1
for (int i=b.length()-2; i>=0; i--) // LIST #'S FROM MOST RIGHT-HAND SIDE
{
char ch = b.charAt(i);
String temp = "" + ch;
for (int j=1; j<=pow; j++)
temp = multiply2(temp);
//System.out.println(temp);
int n1 = 0;
for (int k=0; k<temp.length(); k++)
{
n1 = n1*10 + (int) (temp.charAt(k)-'0');
}
n = n + n1;
s = temp;
pow++;
}
s = s + n;
return s;
}
//convert decimal string d to an equivalent binary string.
public static String dToB(String d)
{
String s = "";
while (!d.equals("0"))
{
String d1 = divide2(d);
d1 = multiply2(d1);
if (d1.equals(d))
s = "0" + s;
else
s = "1" + s;
d = divide2(d);
}
return s;
}
//convert binary string b to an equivalent octal string.
public static String bToO(String b)
{
String s = "";
int groups = b.length()/3;
int index = 0;
//System.out.println(index); //bToD(b)
while (groups != index)
{
for (int i = b.length()-3; i >= 0; i--)
{
for (int j=1; j<=i; j++)
{
String temp = b.substring(b.length()-3,b.length()); //last 3 digits in binary
String sSub = b.substring(0,b.length()-3); //first digits in binary
s = bToD(temp);
}
}
index++;
}
return s;
}
//convert octal string o to an equivalent binary string.
public static String oToB(String o)
{
String s ="";
int digits = o.length();
int index = 0;
while (digits != index)
{
for (int i=o.length()-1; i>=0; i--)
{
char ch = o.charAt(i);
//System.out.println(digits);
switch (ch)
{
case '7':
s = s + "111";
index++;
break;
case '6':
s = s + "110";
index++;
break;
case '5':
s = s + "101";
index++;
break;
case '4':
s = s + "100";
index++;
break;
case '3':
s = s + "011";
index++;
break;
case '2':
s = s + "010";
index++;
break;
case '1':
s = s + "001";
index++;
break;
case '0':
s = s + "000";
index++;
break;
}
}
}
return s;
}
//convert binary string b to an equivalent hexadecimal string.
public static String bToH(String b)
{
String s ="";
return s;
}
//convert hexadecimal string h to an equivalent binary string.
public static String hToB(String h)
{
String s ="";
return s;
}
public static void main(String[] args) {
// TODO code application logic here
String b,d,o,h;
b = "101";
System.out.println("Binary to Decimal:");
System.out.println(b + " => " + bToD(b));
System.out.println();
System.out.println("Decimal to Binary:");
d = "45";
System.out.println(d + " => " + dToB(d));
System.out.println();
System.out.println("Binary to Octal:");
b = "100101101";
System.out.println(b + " => " + bToO(b));
System.out.println();
System.out.println("Octal to Binary:");
o = "";
System.out.println(o + " => " + oToB(o));
System.out.println();
System.out.println("Binary to Hexadecimal:");
b = "";
System.out.println(b + " => " + bToH(b));
System.out.println();
System.out.println("Hexadecimal to Binary:");
h = "";
System.out.println(h + " => " + hToB(h));
}
}
Here's a solution, yours is quite convoluted.
//convert binary string b to an equivalent decimal string.
public static String bToD(String b)
{
int ans = 0, pow = 0;
//For every digit in binary
for(int i=b.length()-1; i>=0; i--){
// Get string of current char
String cur = Character.toString(b.charAt(i));
for (int j=0; j<pow; j++)
cur = multiply2(cur);
ans += Integer.parseInt(cur);
pow++;
}
return Integer.toString(ans);
}
so I have a code that should multiplicate two Binary Numbers as String without using ParseInt. My code actually works by far but it's multiplicating as decimal numbers. Something in the part where it should do the addition is wrong.
Thanks for any kind of help!
public static String multiply(String binary1, String binary2)
String b1 = new StringBuilder(binary1).reverse().toString();
String b2 = new StringBuilder(binary2).reverse().toString();
int[] m = new int[binary1.length()+binary2.length()];
for (int i = 0; i < binary1.length(); i++) {
for (int j = 0; j < binary2.length(); j++) {
m[i+j] += (b1.charAt(i)-'0')*(b2.charAt(j)-'0');
}
}
StringBuilder sb = new StringBuilder();
for(int i=0; i < m.length; i++) {
int mod = m[i]%10;
int carry = m[i]/10;
if (i+1 < m.length) {
m[i + 1] = m[i + 1] + carry;
}
sb.insert(0, mod);
}
// delete leading zeros
while (sb.charAt(0) == '0' && sb.length() > 1) {
sb.deleteCharAt(0);
}
return sb.toString();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("1. Faktor: ");
String input1 = scan.next("(0|1)*");
System.out.print("2. Faktor: ");
String input2 = scan.next("(0|1)*");
scan.close();
System.out.println("Ergebnis: " + multiply(input1, input2));
}
}
You may not use Integer.parseInt but nobody forbid you to implement your own parser:
private static int parseBinaryString(String s) {
int binary = 0;
for (int i = s.length() - 1, c; i >= 0; i--) {
binary <<= 1;
c = s.charAt(i);
if (c == '1') {
binary++;
} else if (c != '0') {
throw new NumberFormatException(s);
}
}
return binary;
}
Which can then be simply used like this in your multiply method:
private static String multiply(String a, String b) {
return Integer.toBinaryString(parseBinaryString(a) * parseBinaryString(b));
}
And if you can't use Integer.toBinaryString you can implement that method yourself:
private static String toBinaryString(int i) {
StringBuilder binary = new StringBuilder();
for (int t = i; t != 0; t >>= 1) {
binary.append((i & t) != 0 ? 1 : 0);
}
return binary.toString();
}
So I have here my code implementing Three Address Code in arithmetic expression.
class ThreeAddressCode {
private static final char[][] precedence = {
{'/', '1'},
{'*', '1'},
{'+', '2'},
{'-', '2'}
};
private static int precedenceOf(String t)
{
char token = t.charAt(0);
for (int i=0; i < precedence.length; i++)
{
if (token == precedence[i][0])
{
return Integer.parseInt(precedence[i][1]+"");
}
}
return -1;
}
public static void main(String[] args) throws Exception
{
int i, j, opc=0;
char token;
boolean processed[];
String[][] operators = new String[10][2];
String expr="", temp;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter an expression: ");
expr = in.readLine();
processed = new boolean[expr.length()];
for (i=0; i < processed.length; i++)
{
processed[i] = false;
}
for (i=0; i < expr.length(); i++)
{
token = expr.charAt(i);
for (j=0; j < precedence.length; j++)
{
if (token==precedence[j][0])
{
operators[opc][0] = token+"";
operators[opc][1] = i+"";
opc++;
break;
}
}
}
System.out.println("\nOperators:\nOperator\tLocation");
for (i=0; i < opc; i++)
{
System.out.println(operators[i][0] + "\t\t" + operators[i][1]);
}
//sort
for (i=opc-1; i >= 0; i--)
{
for (j=0; j < i; j++)
{
if (precedenceOf(operators[j][0]) > precedenceOf(operators[j+1][0]))
{
temp = operators[j][0];
operators[j][0] = operators[j+1][0];
operators[j+1][0] = temp;
temp = operators[j][1];
operators[j][1] = operators[j+1][1];
operators[j+1][1] = temp;
}
}
}
System.out.println("\nOperators sorted in their precedence:\nOperator\tLocation");
for (i=0; i < opc; i++)
{
System.out.println(operators[i][0] + "\t\t" + operators[i][1]);
}
System.out.println();
for (i=0; i < opc; i++)
{
j = Integer.parseInt(operators[i][1]+"");
String op1="", op2="";
if (processed[j-1]==true)
{
if (precedenceOf(operators[i-1][0]) == precedenceOf(operators[i][0]))
{
op1 = "t"+i;
}
else
{
for (int x=0; x < opc; x++)
{
if ((j-2) == Integer.parseInt(operators[x][1]))
{
op1 = "t"+(x+1)+"";
}
}
}
}
else
{
op1 = expr.charAt(j-1)+"";
}
if (processed[j+1]==true)
{
for (int x=0; x < opc; x++)
{
if ((j+2) == Integer.parseInt(operators[x][1]))
{
op2 = "t"+(x+1)+"";
}
}
}
else
{
op2 = expr.charAt(j+1)+"";
}
System.out.println("t"+(i+1)+" = "+op1+operators[i][0]+op2);
processed[j] = processed[j-1] = processed[j+1] = true;
}
}
}
Sample Output
Input : a * b / c
t1 = a * b
t2 = t1 / c
What the program does is evaluate the arithmetic expression and shows them step by step by operators.
Can you help me to include parenthesis in the priorities? and achieve an output like this
Sample Output
Input : a * ( b + c )
t1 = b + c
t2 = a * t2
Right now, the parenthesis is treated like an operand.
I did not use any of your code. Sorry.
This was a fun one to think about. I have never considered how you would do something like this. It does not follow all of the best practices to a "T", but the question inspired me to consider how you would do this in a rudimentary way.
You could make much of this code smaller by using more Java Frameworks, but it was enjoyable to strictly try to work this out logically.
This code is missing most validation (i.e. The user inputs an erroneous expression)
It does however check if there are an equal number of open and close parenthesis.
Lastly, I had to wrap things up so I did not extend into expressions with nested parenthesis.
Example a * ( b * ( c / d ) - e ) >> this code does not handle this scenario, and would have to be enhanced to accommodate for this.
Otherwise, it should give a pretty good idea as to one way you could go about building a program to work through parenthesis.
I hope it helps
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MathPriority {
public static void main(String[] args) {
String expression = "a * (b * c) + (d / e)"; //You can work out how you want input to com in
List<String> priorityList = getPriorityList(expression);//Find parenthesis and sets priority.
expression = expression.replace(" ", "").replace("(", "").replace(")", "");//Take out any spaces and parenthesis
for (int i = 0; i < priorityList.size(); i++) {//Replaces the piece in parenthesis with var and outputs var
expression = expression.replace(priorityList.get(i), "t" + (i + 1));
System.out.println("t" + (i + 1) + " = " + priorityList.get(i));
}
System.out.println("t" + (priorityList.size() + 1) + " = " + expression);//pushes final variable set
}
//You can use this to build a List of indexes of a character within a String
public static List<Integer> getAllOccurencesOfChar(List<String> expression, String indexO) {
List<Integer> parIndexList = new ArrayList<>();
for (int i = 0; i < expression.size(); i++) {
if (expression.get(i).contains(indexO)) {
if (!parIndexList.contains(i) && i > 0) {
parIndexList.add(i);
}
}
}
return parIndexList;
}
//Outputs a list of substrings. They can later be used to parse through the inital string
public static List<String> getPriorityList(String expression) {
List<String> priorityList = new ArrayList<>();
expression = expression.replace(" ", "");
String[] eParts = expression.split("");
List<String> expressionParts = new ArrayList<>();//Get expression into single chars
for (String e : eParts) {//If you change this to an Array.List, it will not work. This type of list is fixed in size
expressionParts.add(e);
}
List<Integer> parIndexList = getAllOccurencesOfChar(expressionParts, "(");//find all open paranthesis
List<Integer> rParIndexList = getAllOccurencesOfChar(expressionParts, ")");//find all close paranthesis
if (parIndexList.size() != rParIndexList.size()) {
System.out.println("Your Equation does not have an equal number of open and close parenthesis");
System.exit(0);
}
//Work out the parenthesis
int loopIterator = parIndexList.size();//This will change as we iterate
for (int pars = loopIterator - 1; pars >= 0; pars--) {
int start = parIndexList.get(pars); //Define a start
int end = 0; //and End
//int end = rParIndexList.get(pars);
for (int contemplate = 0; contemplate < loopIterator; contemplate++) {//contemplate where given parenthesis starts and where its closing tag is
if (parIndexList.get(pars) < rParIndexList.get(contemplate)) {
end = rParIndexList.get(contemplate);//find first occurence and set true end
break;//then stop
}
}
String expre = "";
for (int concat = start + 1; concat < end; concat++) {
expre += expressionParts.get(concat);//put the priorityList's subExpression together
}
priorityList.add(expre);//add that subExpression to the list
expressionParts.subList(start, end + 1).clear();//remove these expressionParts
/*Re-establish where the parenthesis are, since we removed parts of the expression in the list*/
parIndexList = getAllOccurencesOfChar(expressionParts, "(");//find all open paranthesis
rParIndexList = getAllOccurencesOfChar(expressionParts, ")");//find all close paranthesis
loopIterator = parIndexList.size();//resize the forLoop
}
return priorityList;
}
public static List<Integer> getStartEndPosition(String fullExpression, String subExpression) {
List<Integer> sAndE = new ArrayList<>();
String[] eParts = subExpression.split("");
List<String> wordParts = new ArrayList<>();
wordParts.addAll(Arrays.asList(eParts));
/*Find multiples of same operand*/
List<Integer> add = getAllOccurencesOfChar(wordParts, "+");
List<Integer> subtract = getAllOccurencesOfChar(wordParts, "-");
List<Integer> divide = getAllOccurencesOfChar(wordParts, "/");
List<Integer> multiply = getAllOccurencesOfChar(wordParts, "*");
/*Find single Operands*/
int plus = subExpression.indexOf("+");
int minus = subExpression.indexOf("-");
int div = subExpression.indexOf("/");
int mult = subExpression.indexOf("*");
int multiOperands = plus + minus + div + mult;//See if multiples exist
int startingPosition = 0;
if (add.size() > 1 || subtract.size() > 1 || divide.size() > 1 || multiply.size() > 1
|| multiOperands > 0) {
//expression has multiple opreands of different types
String findStart = wordParts.get(0) + wordParts.get(1);
String findEnd = wordParts.get(wordParts.size() - 2) + wordParts.get(wordParts.size() - 1);
startingPosition = fullExpression.indexOf(findStart);
sAndE.add(startingPosition);
int endPosition = fullExpression.indexOf(findEnd);
sAndE.add(endPosition);
} else {
startingPosition = fullExpression.indexOf(subExpression);
sAndE.add(startingPosition);
sAndE.add(startingPosition + subExpression.length());
}
return sAndE;
}
}
String expression = "a * (b * c) + (d / e)"
Outputs:
t1 = d/e
t2 = b*c
t3 = a*t2+t1
This is my task, Given an input of an expression consisting of a string of letters and operators (plus sign, minus sign, and letters. IE: ‘b-d+e-f’) and a file with a set of variable/value pairs separated by commas (i.e: a=1,b=7,c=3,d=14) write a program that would output the result of the inputted expression.
For example, if the expression input was ("a + b+c -d") and the file input was ( a=1,b=7,c=3,d=14) the output would be -3.
Hi I am trying to do a simple java code which outputs a number if i add 4 letters. When I do different combinations like d-c+a+b it gives me a inccorect number like 118.0. Can someone tell me where in my code my calculations are wrong..
Thank you
the ValVarPairs.txt contains these numbers-> a=100,b=5,c=10,d=13
This is what i coded.
package com.ecsgrid;
import java.io.*;
public class testC {
public static void main(String[] args) {
int i = 0,j = 0;
double result, values[] = new double[4];
char k, operators[] = new char[3];
for (i = 0; i <= 2; i++)
operators[i] = '+'; // default is to add the values
File myfile;
StreamTokenizer tok;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String InputText;
i = 0;
try {
myfile = new File("C:\\VarValPairs.txt");
tok = new StreamTokenizer(new FileReader(myfile));
tok.eolIsSignificant(false);
while ((tok.nextToken() != StreamTokenizer.TT_EOF) && (i <= 3)){
if ((tok.ttype == StreamTokenizer.TT_NUMBER))
values[i++] = tok.nval;
}
}
catch(FileNotFoundException e) { System.err.println(e); return; }
catch(IOException f) { System.out.println(f); return; }
System.out.println("Enter letters and operators:");
try {
InputText = in.readLine();
}
catch(IOException f) { System.out.println(f); return; }
for (i = 0; i < InputText.length(); i++)
{
k = InputText.charAt(i);
if ((k == '+') || (k == '-'))
{
if (j <= 2) operators[j++] = k;
}
}
result = values[0];
for (i = 0; i <= 2; i++){
if (operators[i] == '+')
result = result + values[i+1];
else
result = result - values[i+1];
}
System.out.println(result);
}
}
I'm not sure where your calculations are wrong, but you could do something like this:
EDITED CODE:
import java.io.*;
import java.util.*;
public class test{
public static int a;
public static int b;
public static int c;
public static int d;
public static int fin = 0;
public static String temp;
public static void main(String[] args){
try{
Scanner input = new Scanner(new File("yourfile.txt"));
temp = "";
while(input.hasNext()){ //stores the letters
temp = temp + input.next();
}
input.close();
}
catch(Exception e){
}
/*
THIS IS IF THE FILE yourfile.txt IS IN THIS FORMAT EXACTLY:
a=1
b=2
c=3
d=4
*/
for(int i = 0; i < temp.length(); i++){ //intitializes the values
String message = "" + temp.charAt(i);
if(message.equals("a") || message.equals("b") || message.equals("c") || message.equals("d")){
String val = "" + temp.charAt(i+2);
setValue(message,val);
}
}
Scanner enter = new Scanner(System.in);
System.out.print("ENTER EXPRESSION: ");
String ex = enter.nextLine();
for(int b = 0; b < ex.length(); b++){
String m = ""+ ex.charAt(b);
if(b == 0){
if(m.equals("a") || m.equals("b") || m.equals("c") || m.equals("d")){
fin = fin + getValue(m);
}
}
else{
if(m.equals("a") || m.equals("b") || m.equals("c") || m.equals("d")){
String check = "" + ex.charAt(b-1);
if(check.equals("+")){
fin = fin + getValue(m);
}
if(check.equals("-")){
fin = fin - getValue(m);
}
}
}
}
System.out.println(fin);
}
public static void setValue(String variable, String value){
if(variable.equals("a")){
a = Integer.parseInt(value);
}
if(variable.equals("b")){
b = Integer.parseInt(value);
}
if(variable.equals("c")){
c = Integer.parseInt(value);
}
if(variable.equals("d")){
d = Integer.parseInt(value);
}
}
public static int ret = 0;
public static int getValue(String var){
if(var.equals("a")){
ret = a;
}
if(var.equals("b")){
ret = b;
}
if(var.equals("c")){
ret = c;
}
if(var.equals("d")){
ret = d;
}
return ret;
}
}
There are some problems in your code where you use "==" instead of .equals()