How to make multiplication and division counted first in my calculator? - java

Hello guys im trying to make a calculator that is based on user scanner input, The calculator works fine for calculating from left to right but im having difficulties putting priorities in *,/ and ()
for example 3+(5*2)+1 should be 14 instead mine is 17, and then when i tried
5+((2+1)*3)-1 it gives me weird error..
Can anyone help please? and how can i make my code appear more efficient and simpler thank you in advance.
So here is my code :
System.out.print("Input Equation : ");
n = s.next() + s.nextLine();
n = n.replaceAll("\\s+", "");
char[] nans = n.toCharArray();
c = 0;
for (int i = 0; i < n.length(); i++)
if (nans[i] == '+' || nans[i] == '-' || nans[i] == '/' || nans[i] == '*')
c++;
char[] op = new char[c];
int[] num = new int[c + 1];
c = 0;
for (int i = 0; i < n.length(); i++) {
if (nans[i] == '+' || nans[i] == '-' || nans[i] == '/' || nans[i] == '*') {
op[c] = nans[i];
c++;
}
}
c = 0;
for (int i = 0; i < n.length(); i++) {
if (nans[i] == '1' || nans[i] == '2' || nans[i] == '3' || nans[i] == '4' || nans[i] == '5'
|| nans[i] == '6' || nans[i] == '7' || nans[i] == '8' || nans[i] == '9' || nans[i] == '0')
nus = nus + nans[i];
else if (nans[i] == '+' || nans[i] == '-' || nans[i] == '/' || nans[i] == '*') {
num[c] = Integer.parseInt(nus);
nus = "";
c++;
}
if (i == n.length() - 1){
num[c] = Integer.parseInt(nus);
}
}
for (int i = 0; i < c; i++) {
if (op[i] == '+') {
result = result + num[i] + num[i + 1];
num[i + 1] = 0;
}
else if (op[i] == '-') {
result = result + num[i] - num[i + 1];
num[i + 1] = 0;
}
else if (op[i] == '/') {
result = (result + num[i]) / num[i + 1];
num[i + 1] = 0;
}
else if (op[i] == '*') {
result = (result + num[i]) * num[i + 1];
num[i + 1] = 0;
}
}
System.out.print(" = "+ result);

When you read a token (that is an argument for operator or simply a number), make sure that the next operator is not multiplication or division, otherwise, you want to calculate that one. You can achieve this by means of recursion easily.

Related

the code works all well until the last else if statement (with the != 'R' etc.) when i run the code to test that statement, the code fails to function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
making a connect4 game, so this is just some part of the logic - no floating pieces, no invalid letters (pieces - only R and Y acceptable) '.' represents an empty gap.
boolean arrayCheck = false;
do {
for (int j = 0; j < connect4Board[0].length; j++) {
for (int i = 0; i < connect4Board.length - 1; i++) {
if ((connect4Board[i][j] == 'R') || (connect4Board[i][j] == 'Y')) {
if ((connect4Board[i + 1][j] == '.') || (connect4Board[i + 1][j] == 0)) {
return arrayCheck; //makes sure a gap underneath is not present and seen as a floating piece
}
else if ((connect4Board[i + 1][j] == 'R') || (connect4Board[i + 1][j] == 'Y')) {
i++;
}
}
else if ((connect4Board[i][j] == '.') || (connect4Board[i][j] == 0)) {
if ((connect4Board[i + 1][j] == 'R') || (connect4Board[i + 1][j] == 'Y') || connect4Board[i + 1][j] == '.' || (connect4Board[i + 1][j] == 0)) {
i++;
} else {
return arrayCheck;
}
}
else if((connect4Board[i][j] != 'R') && (connect4Board[i][j] != 'Y') && (connect4Board[i][j] != '.')) {
return arrayCheck; //where it all goes wrong. code bugs out and doesn't output anything (should output true or false) but the console just stays empty.
}
i--;
}
j++;
}
} while (arrayCheck);
I don't know whether the problem is because of the do-while loop, or the if statement itself. I've tried to put the if statement at the beginning of the loop, outside the loop, and at the end but the problem seems to be the same regardless of where I put it. the console just remains blank (stays running without continuing with any other actions). What should I do?
1. Check if valid space
The first if checks if it is a valid space, if not it will return false and as a result ending the loop.
2. Check for floating piece
You can then check if they are valid
at the end you have i--;
Do you need to do this?
i++
Or
i--
Or nether of them? Because you already increment for every nested if.
Debuging
To help debug your code try printing i with System.out.println(i);Notice what happens to it.
Is the loop creating an infinite loop?
Example
I created the array as:
char[][] connect4Board = {{'R','.','.','.','.'},{'T','.','.','.','.'},{'R','.','.','.','.'},{'R','.','.','.','.'}};
Could it possibly be how the counter i is incremented?
This works for me..
boolean arrayCheck = false;
do {
for (int j = 0; j < connect4Board.length; j++) {
for (int i = 0; i < connect4Board.length - 1; i++) {
/*1. Check if valid space*/
if ((connect4Board[i][j] != 'R') && (connect4Board[i][j] != 'Y') && (connect4Board[i][j] != '.'))
return arrayCheck;
/*2. Check for floating piece*/
if ((connect4Board[i][j] == 'R') || (connect4Board[i][j] == 'Y'))
if ((connect4Board[i + 1][j] == '.') || (connect4Board[i + 1][j] == 0))
return arrayCheck;
else if ((connect4Board[i + 1][j] == 'R') || (connect4Board[i + 1][j] == 'Y'))
i++;
if ((connect4Board[i][j] == '.') || (connect4Board[i][j] == 0))
if ((connect4Board[i + 1][j] == 'R') || (connect4Board[i + 1][j] == 'Y') || connect4Board[i + 1][j] == '.' || (connect4Board[i + 1][j] == 0))
i++;
else
return arrayCheck;
//Do you need to increment?
// i++; Or i--;
}
j++;
}
} while (arrayCheck);
return true;
}

Simplify a given algebraic string. Output the simplified string without parentheses

The examples look like this, Input : "a-(b+c)" output "a-b-c", Input : "a-(a+b)" output "b"
I came up with this method, but the result for input: "a-(a+b)" is "a-a-b", which the correct one should be "b", how to improve that?
public String simplify(String str)
{
int len = str.length();
char res[] = new char[len];
int index = 0, i = 0;
Stack<Integer> s = new Stack<Integer> ();
s.push(0);
while (i < len) {
if (str.charAt(i) == '+') {
if (s.peek() == 1)
res[index++] = '-';
// If top is 0, append the same operator
if (s.peek() == 0)
res[index++] = '+';
} else if (str.charAt(i) == '-') {
if (s.peek() == 1)
res[index++] = '+';
else if (s.peek() == 0)
res[index++] = '-';
} else if (str.charAt(i) == '(' && i > 0) {
if (str.charAt(i - 1) == '-') {
// x is opposite to the top of stack
int x = (s.peek() == 1) ? 0 : 1;
s.push(x);
}
else if (str.charAt(i - 1) == '+')
s.push(s.peek());
}
else if (str.charAt(i) == ')')
s.pop();
else
res[index++] = str.charAt(i);
i++;
}
return new String(res);
}

How to fix a program that incorrectly calculates the percentages of numbers in Java?

I am trying to find the frequency of each letter in a document, so this program counts up the number of occurrences of each letter, and then finds the total number of letters. Then it's supposed to find the frequency, the problem is it counts the letters correctly and the total, but the percentages incorrectly. How do I calculate the percentage?
//find number of occurrences for each letter
String[] letter = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
int[] count = new int[26];
int totalCount = 0;
for(int i = 0; i < subset.length(); i++)
{
char letters = subset.charAt(i);
if(letters == 'a')
count[0]++;
else if(letters == 'b')
count[1]++;
else if(letters == 'c')
count[2]++;
else if(letters == 'd')
count[3]++;
else if(letters == 'e')
count[4]++;
else if(letters == 'f')
count[5]++;
else if(letters == 'g')
count[6]++;
else if(letters == 'h')
count[7]++;
else if(letters == 'i')
count[8]++;
else if(letters == 'j')
count[9]++;
else if(letters == 'k')
count[10]++;
else if(letters == 'l')
count[11]++;
else if(letters == 'm')
count[12]++;
else if(letters == 'n')
count[13]++;
else if(letters == 'o')
count[14]++;
else if(letters == 'p')
count[15]++;
else if(letters == 'q')
count[16]++;
else if(letters == 'r')
count[17]++;
else if(letters == 's')
count[18]++;
else if(letters == 't')
count[19]++;
else if(letters == 'u')
count[20]++;
else if(letters == 'v')
count[21]++;
else if(letters == 'w')
count[22]++;
else if(letters == 'x')
count[23]++;
else if(letters == 'y')
count[24]++;
else if(letters == 'z')
count[25]++;
}
//find total characters in document
double[] frequency = new double[26];
for(int i = 0; i < 26; i++)
{
totalCount += count[i];
frequency[i] = ((double)count[i] / (totalCount + 1)) * 100; //the problem
}
System.out.println(totalCount);
//for(int i = 0; i < 26; i++)
//{
// frequency[i] = (double)(count[i] / totalCount * 100);
//}
//print
System.out.println(" Letter Occurrences Frequency");
System.out.println("--------------------------------");
for(int i = 0; i < 26; i++)
{
System.out.println(" " + letter[i] + "\t " + count[i] + "\t " + df.format(frequency[i]));
}
The frequency needs to be calculated after you have the totalCount:
for(int i = 0; i < 26; i++) {
totalCount += count[i];
}
System.out.println(totalCount);
System.out.println(" Letter Occurrences Frequency");
System.out.println("--------------------------------");
for(int i = 0; i < 26; i++) {
frequency[i] = ((double)count[i] / (totalCount + 1)) * 100;
System.out.println(" " + letter[i] + "\t " + count[i] + "\t " + df.format(frequency[i]));
}
Side note
You don't need a for loop for totalCount since it's just the length of the string (i.e. totalCount = subset.length())
you wouldn't need 25 if else statements to find letter counts... Just do:
count[subset.charAt(i) - 61]++;
61 is the ASCII value for letter 'a'

Why doesn't this code work? FizzBuzz JAVA

I cant get "FizzBuzz". No matter what the input, the "FizzBuzz" code isn't running. What did I do wrong?
public String[] fizzBuzz(int start, int end) {
int diff = end-start;
String[] array = new String[diff];
for (int i = 0; i < diff; i++) {
if (start%3 == 0 && start%5 == 0) array[i] = "FizzBuzz";
if (start%3 == 0 || start%5 == 0) {
if (start%3 == 0) array[i] = "Fizz";
if (start%5 == 0) array[i] = "Buzz";
}
else {
array[i] = String.valueOf(start);
}
start++;
}
return array;
}
Logic in your if statements is a bit busted, using your code as the starting point, you'd have to do something like this.
if (start%3 == 0 && start%5 == 0) {
array[i] = "FizzBuzz";
}
else if (start%3 == 0 || start%5 == 0) {
if (start%3 == 0) array[i] = "Fizz";
if (start%5 == 0) array[i] = "Buzz";
}
else {
array[i] = String.valueOf(start);
}
String s = "" + i;
if ((i % 3) == 0) {
s += " Fizz";
}
if ((i % 5) == 0) {
s+= " Buzz";
}
System.out.println(s);
This code snippet placed in a loop will print Fizz, Buzz and Fizz Buzz on i divisible by 3, 5 and 15 respectively.
you should try this.
class FizzBuzz{
public static void main(String args[]){
int n = 100;
for(int i=0;i<=n;i++){
if((i % 3) == 0 && (i % 5) != 0){
System.out.println("Fizz");
}
else if((i % 5) == 0 && (i % 3) != 0){
System.out.println("Buzz");
}else if((i % 3) == 0 && (i % 5) == 0){
System.out.println("FizzBuzz");
}else{
System.out.println(""+i);
}
}
}
}

String to Char || Char to String

Let suppose I have a button
case R.id.button:
which will do the following functionality:
int position;
String keyInStringForm = et2.getText().toString();
int keyInIntegerForm = Integer.parseInt(keyInStringForm);
String text = et1.getText().toString();
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == 'a' || text.charAt(i) == 'A') {
position = 0;
break;
} else if (text.charAt(i) == 'b' || text.charAt(i) == 'B') {
position = 1;
break;
} else if (text.charAt(i) == 'c' || text.charAt(i) == 'C') {
position = 2;
break;
} else if (text.charAt(i) == 'd' || text.charAt(i) == 'D') {
position = 3;
break;
} else if (text.charAt(i) == 'e' || text.charAt(i) == 'E') {
position = 4;
break;
} else if (text.charAt(i) == 'f' || text.charAt(i) == 'F') {
position = 5;
break;
} else if (text.charAt(i) == 'g' || text.charAt(i) == 'G') {
position = 6;
break;
} else if (text.charAt(i) == 'h' || text.charAt(i) == 'H') {
position = 7;
break;
} else if (text.charAt(i) == 'i' || text.charAt(i) == 'I') {
position = 8;
break;
} else if (text.charAt(i) == 'j' || text.charAt(i) == 'J') {
position = 9;
break;
} else if (text.charAt(i) == 'k' || text.charAt(i) == 'K') {
position = 10;
break;
} else if (text.charAt(i) == 'l' || text.charAt(i) == 'L') {
position = 11;
break;
} else if (text.charAt(i) == 'm' || text.charAt(i) == 'M') {
position = 12;
break;
} else if (text.charAt(i) == 'n' || text.charAt(i) == 'N') {
position = 13;
break;
} else if (text.charAt(i) == 'o' || text.charAt(i) == 'O') {
position = 14;
break;
} else if (text.charAt(i) == 'p' || text.charAt(i) == 'P') {
position = 15;
break;
} else if (text.charAt(i) == 'q' || text.charAt(i) == 'Q') {
position = 16;
break;
} else if (text.charAt(i) == 'r' || text.charAt(i) == 'R') {
position = 17;
break;
} else if (text.charAt(i) == 's' || text.charAt(i) == 'S') {
position = 18;
break;
} else if (text.charAt(i) == 't' || text.charAt(i) == 'T') {
position = 19;
break;
} else if (text.charAt(i) == 'u' || text.charAt(i) == 'U') {
position = 20;
break;
} else if (text.charAt(i) == 'v' || text.charAt(i) == 'V') {
position = 21;
break;
} else if (text.charAt(i) == 'w' || text.charAt(i) == 'W') {
position = 22;
break;
} else if (text.charAt(i) == 'x' || text.charAt(i) == 'X') {
position = 23;
break;
} else if (text.charAt(i) == 'y' || text.charAt(i) == 'Y') {
position = 24;
break;
} else if (text.charAt(i) == 'z' || text.charAt(i) == 'Z') {
position = 25;
break;
} else if (text.charAt(i) == ' ') {
position = 26;
break;
}
int initialResult = position + keyInIntegerForm;
int finalResult = initialResult % 26;
char resultantChar = alphabets[finalResult];
where as "alphabets" is a char array for a-z characters.
} // for
Now there will be more that one "resultantChar", I want those "resultantChar" to be combined together to form a string so I can set it onto a textview.
How do I do that
If I understood you correctly, try do something like this:
StringBuffer result = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
...
char resultantChar = alphabets[finalResult];
result.append(resultantChar);
}
System.out.println(result);
Please, simplify your code using that!
char ch = 'Z';
ch = Character.toLowerCase(ch);
int position = Character.getNumericValue(ch) - Character.getNumericValue('a');
Or, for your case:
char ch = Character.toLowerCase(text.charAt(i));
if (ch >= 'a' && ch <= 'z') {
position = Character.getNumericValue(ch) - Character.getNumericValue('a');
} else if (ch == ' ') {
position = 26;
}
Use http://developer.android.com/reference/java/lang/StringBuilder.html stringbuilder you can append char with stringbuilder

Categories