Here is my code... can someone please tell me what is wrong?
void keyPressed() {
if (key == '\n') {
equation = typing;
switch (equation.charAt(2)) {
case "-":
if (equation.charAt(3) == "x") {
math[0] = -1;
};
else {
math[0] = int(equation.charAt(3) * -1);
};
}
}
}
I don't understand what is wrong. All of the braces match up. Is it that you can't use an if else inside a switch???
try replacing
if (equation.charAt(3)=="x") {
math[0] = -1;
};
else {
math[0] = int(equation.charAt(3)*-1);
};
with
if (equation.charAt(3)=='x') { // NOTE character comparision
math[0] = -1;
}
else {
math[0] = int(equation.charAt(3)*-1);
}
Related
I am working on a calculator and practicing java and android development. Everything works fine except for the dot function. here is the problem(see the very last dot):
here are the codes:
case R.id.btn_dot:
if (dotSet) {
screenTV.append("");
} else if (isEmpty() || empty) {
screenTV.append("0.");
dotSet = true;
count++;
} else {
screenTV.append(".");
dotSet = true;
count++;
}
an operand:
ase R.id.btn_add:
if (isEmpty()) {
screenTV.append("");
} else if (screenTvGet().endsWith("+")) {
screenTV.append("");
} else if (!isEmpty()) {
screenTV.append("+");
dotSet = false;
empty = true;
resultSet = false;
count = 0;
}
break;
and a number:
case R.id.btn0:
if (resultSet) {
screenTV.append("");
} else if (isEmpty()) {
screenTV.append("");
} else {
screenTV.append("0");
empty = false;
}
Finally, the backspace function:
case R.id.btn_backspace:
String screenContent;
String screen = screenTV.getText().toString();
int screenMinusOne = screen.length() - 1;
String screenMinus = String.valueOf(screenMinusOne);
if (screen.endsWith("."))
dotSet = false;
if (isEmpty()) {
screenTV.setText("");
} else {
screenContent = screen.substring(0, screen.length() - 1);
screenTV.setText(screenContent);
}
break;
forget about the "count".
I believe you can see the whole picture. now I want somehow when I clear an operand with "BackSpace function" and the previous number has a dot in it, the dot button doesn't just add an '.' or "0." to the screen instead returns null or just adds this "". I hope my question is clear.
Remove dotSet. You don't need it.
Then, similar to how you do this for btn_add:
} else if (screenTvGet().endsWith("+")) {
screenTV.append("");
use a regex for btn_dot to check if there is a . in the last part of the text:
} else if (screenTvGet().matches(".*\\.\\d*")) {
screenTV.append("");
So i have an assignment to write infix to postfix method without any nested loops (loops in loops) and i didn't notice that and i wrote long method with nested loops, any idea how to fix it? here is the code
How can i divide them into smaller method while have stack?
List<String> infix2Postfix(List<String> infix) {
Stack<String> opStack = new Stack<>();
List<String> outPut = new ArrayList<>();
for (String inComing : infix) {
// When incoming is one of -,+,*,/,^
if (OPERATORS.contains(inComing)) {
if (opStack.empty() || opStack.peek().equals("(")) {
....
} else {
....
if (inComingP == 4 && inComingP == operatorP) {
....
} else if (inComingP == operatorP) {
...
} else if (inComingP < operatorP) {
while (!opStack.empty() && !opStack.peek().equals("(")) {
...
}
opStack.push(inComing);
} else {
opStack.push(inComing);
}
}
}
// when incoming is one of "(" , ")"
else if ("()".contains(inComing)) {
if (")".equals(inComing)) {
while (opStack.size() != 0 && !opStack.peek().equals("(")) {
...
}
if (opStack.size() == 0) {
...
} else {
opStack.pop();
}
} else {
opStack.add(inComing);
}
} else {
outPut.add(inComing);
}
}
if (opStack.contains("(")) {
throw new IllegalArgumentException(MISSING_OPERATOR);
}
while (!opStack.empty()) {
outPut.add(opStack.pop());
}
return outPut;
}
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 6 years ago.
I am writing a code that will import a string of characters from a text file, analyze the string using a stack and determine which "language" the string belongs to based on whether or not it fits certain rules. The code below tests to see if an input follows the pattern (A^nB^)^p (where n is greater than or equal to 0). The way I have it written is to load the first set of A's and B's onto a stack, then load the second set of A's and B's onto another stack, pop the two stacks at the same time and compare the returned values. If they match, move on (until the two stacks empty at the same time, hopefully) if they don't then return false.
public static boolean checkL4(File file) throws IOException
{
Stack stack1 = new Stack();
Stack stack2 = new Stack();
Stack stack3 = new Stack();
boolean firstCompare = true;
boolean bStart = false;
char w = 0;
try (Scanner sc = new Scanner(file).useDelimiter("\\s*"))
{
while (sc.hasNext()){
w = sc.next().charAt(0);
if (w == 0) {
return true;
}
if (w != 'A' && w != 'B')
{
return false;
}
if (w == 'A') {
if(!bStart) {
stack1.push(w);
stack3.push(w);
}
if(bStart && stack2.isEmpty()) {
stack2.push(w);
} else {
if (firstCompare) {
while (!stack1.isEmpty() || !stack2.isEmpty()) {
if (!stack1.isEmpty() && stack2.isEmpty())
{
return true;
}
if (stack1.isEmpty() && !stack2.isEmpty()) {
return false;
} else {
if (stack1.pop() == stack2.pop()) {
return true;
} else {
return false;
}
}
}
stack1.push(w);
firstCompare = false;
} else {
if(stack1.isEmpty()){
while (!stack3.isEmpty() || !stack2.isEmpty()) {
if (stack3.isEmpty() && !stack2.isEmpty()) {
return false;
} else {
if (stack2.isEmpty() && !stack3.isEmpty()) {
return false;
} else {
if (stack3.pop() == stack2.pop()) {
return true;
} else {
return false;
}
}
}
}
stack1.push(w);
}
if (stack3.isEmpty()){
while (!stack1.isEmpty() || !stack2.isEmpty()) {
if (stack1.isEmpty() && !stack2.isEmpty()) {
return false;
} else {
if (stack2.isEmpty() && !stack1.isEmpty()) {
return false;
} else {
if (stack1.pop() == stack2.pop()) {
return true;
} else {
return false;
}
}
}
}
stack1.push(w);
}
}
}
}
if (w == 'B') {
bStart = true;
if(bStart && stack2.isEmpty()) {
stack2.push(w);
}
if(bStart && !stack2.isEmpty()) {
if (!stack1.isEmpty()) {
stack3.push(w);
}
if(!stack3.isEmpty()) {
stack1.push(w);
}
}
}
}
}
return false;
}
This code works correctly for most inputs (returning true for AB and AABBBAABBB, and returning false for BBAA) but in some cases where it should return false (like ABBA and AABBCCD) it returns true. So why is it returning true for cases that are palindromes and cases where there are non A and non B letters. I know I have a statement in there that states if w (the input) is not and A and not a B, return false. This is worked in similar methods I have written, so why not this one? I have also written this to return false if the two returned values don't match (which they shouldn't if the input is a palindrome).
I think you should use .isEqual to compare between two Strings instead of using ==
I have the following block of code. Basically it determines in baseball if a player gets a number of bases, what happens based on if someone is on 1st/2nd/3rd. I did this out brute force but is there a way to rewrite this to drastically reduce the line count? I haven't been able to come up with a good way to do it.
int runsScored = 0;
switch (action) {
case 0:
break;
case 1:
if (third) {
if (second) {
if (first) {
runsScored = 2;
second = false;
} else {
runsScored = 2;
first = true;
second = false;
third = false;
}
} else {
if (first) {
runsScored = 1;
second = true;
third = false;
} else {
runsScored = 1;
first = true;
third = false;
}
}
} else {
if (second) {
if (first) {
third = true;
} else {
first = true;
}
} else {
if (first) {
second = true;
} else {
first = true;
}
}
}
break;
case 2:
if (third) {
if (second) {
if (first) {
runsScored = 2;
first = false;
} else {
runsScored = 2;
third = false;
}
} else {
if (first) {
runsScored = 1;
second = true;
} else {
runsScored = 1;
second = true;
third = false;
}
}
} else {
if (second) {
if (first) {
runsScored = 1;
third = true;
second = true;
first = false;
} else {
runsScored = 1;
}
} else {
if (first) {
first = false;
second = true;
third = true;
} else {
second = true;
}
}
}
break;
case 3:
if (third) {
if (second) {
if (first) {
runsScored = 3;
first = false;
second = false;
third = true;
} else {
runsScored = 2;
second = false;
}
} else {
if (first) {
runsScored = 2;
first = false;
} else {
runsScored = 1;
}
}
} else {
if (second) {
if (first) {
runsScored = 2;
third = true;
second = false;
first = false;
} else {
runsScored = 1;
second = false;
third = true;
}
} else {
if (first) {
runsScored = 1;
first = false;
second = false;
third = true;
} else {
third = true;
}
}
}
break;
case 4:
if (third) {
if (second) {
if (first) {
runsScored = 4;
first = false;
second = false;
third = false;
} else {
runsScored = 3;
second = false;
third = false;
}
} else {
if (first) {
runsScored = 3;
first = false;
third = false;
} else {
runsScored = 2;
third = false;
}
}
} else {
if (second) {
if (first) {
runsScored = 3;
third = false;
second = false;
first = false;
} else {
runsScored = 2;
second = false;
third = false;
}
} else {
if (first) {
runsScored = 2;
first = false;
second = false;
third = false;
} else {
runsScored = 1;
}
}
}
break;
default:
throw new AssertionError();
}
return runsScored;
Well I'd be describing this with class and letting it manage itself, but a good first step.
if (third) {
if (second) {
if (first) {
runsScored = 2;
second = false;
} else {
runsScored = 2;
first = true;
second = false;
third = false;
}
if (third) {
if (second) {
runsScored = 2;
second = false;
if (!first) {
first = true;
third = false;
}
i.e. factor out the same code on either side of the else. Once you've cleared out some of the undergrowth, something simpler may become visible.
I'd do it with bitwise operators (shifts and bitwise and)
(see http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html)
int runsScored = 0;
int action=1;
boolean first = false;
boolean second = true;
boolean third = true;
// Encode the bases in a bitstring.
int onbases = 0;
onbases += third ? 1 : 0;
onbases <<= 1;
onbases += second ? 1 : 0;
onbases <<= 1;
onbases += first ? 1 : 0;
onbases <<= 1;
// Bitmasks for use in the loop.
int homeplate = 16;
int basesloaded = 2+4+8;
onbases += 1; // Represent the batter who hasn't yet left the plate.
for (int i=0; i<action; i++) {
onbases <<= 1;
if ((onbases & homeplate) > 0) {
runsScored += 1;
}
}
// Remove the "players" who crossed home plate.
onbases &= basesloaded;
// onbases now reflects who's on base *after* the run.
// Decode the bitstring.
first = (onbases & 2) > 0;
second = (onbases & 4) > 0;
third = (onbases & 8) > 0;
Integer.toBinaryString(int) is useful for debugging, and if you use these operators, I find it helpful to go heavy on parentheses, because order-of-operations sometimes doesn't fall out intuitively.
Edit: What I posted earlier forgot to put the batter on base. I believe it's fixed.
Assuming your action variable is what base the hitter will end up on, and first, second, third are booleans for batters on base:
Instead of checking each boolean, perhaps transform them into a single array. For example, a runner on first and third looks like [1,0,1]. A runner on second and third looks like [0,1,1]. Then you can write a function that takes in your action variable and the array of bases and returns the number of runs and the new bases array.
This could certainly remove the nested statements from your case statement, but maybe you can think of a way to make this work better than nested ifs?
A shorter version for the booleans (only):
boolean new_first = (action == 1) || (action == 2) && (first &!second & third);
boolean new_second = (action == 2) || (action == 1
&& (first && !(second && third))
|| (!first && second && !third));
boolean new_third = (action == 3)
|| (action == 2 && first)
|| (action == 1 && (first && second));
The runsScored part is harder.
I have several cases and I am just using simple if ... if else blocks.
How can I reduce the number of if statements in this code?
Perhaps I could use a lookup table, but I am not sure how to implement it in Java.
private int transition(char current, int state)
{
if(state == 0)
{
if(current == 'b')
{
return 1;
}
else
return 0;
}
if(state == 1)
{
if(current == 'a')
{
return 2;
}
else
return 0;
}
if(state == 2)
{
if(current == 's')
{
return 3;
}
else
return 0;
}
if(state == 3)
{
if(current == 'e')
{
return 3;
}
if(current == 'b')
{
return 4;
}
else
return 0;
}
if(state == 4)
{
if(current == 'a')
{
return 5;
}
else
return 0;
}
if(state == 5)
{
if(current == 'l')
{
return 6;
}
else
return 0;
}
else
return 0;
}
What you're trying to do looks very much like a finite state machine, and these are usually implemented with the help of a transition table. Once you set up the table, it's simply a matter of indexing to the position you want to get the return value. Assuming your return values are all less than 256, you can use a 2D byte array:
byte table[][] = new byte[NUM_STATES][NUM_CHARACTERS];
// Populate the non-zero entries of the table
table[0]['b'] = 1;
table[1]['a'] = 2;
// etc...
private int transition(char current, int state) {
return table[state][current];
}
Well, you can easily utilize hash. Simple and clean.
// declare hashtable
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("0-b", 1);
map.put("1-a", 2);
map.put("2-s", 3);
...
// get result
Integer result = map.get(state + "-" + current);
// change null (nothing found) to zero
return result == null ? 0 : result;
consider interfaces + enums:
interface State<T>
{
public void State<T> step(T input);
}
enum MyState implements State<Character> {
STATE0(0) { #Override public void MyState step(Character c) { return c == 'b' ? STATE1 : STATE0; }},
STATE1(1) { #Override public void MyState step(Character c) { return c == 'a' ? STATE2 : STATE0; }},
/* rest of states here */
final private int value;
MyState(int value) { this.value = value; }
public int getValue() { return this.value; }
}
class SomeClass
{
public MyState currentState = STATE0;
public void step(char input)
{
this.currentState = this.currentState.step(input);
}
}
i switch statement would be best here:
private int transition(char current, int state)
{
switch(state)
{
case 0:
return current == 'b' ? 1 : 0;
case 1:
return current == 'a' ? 2 : 0;
case 2:
return current == 's' ? 3 : 0;
case 3:
return current == 'e' ? 3 : (current == 'b' ? 4 : 0);
case 4:
return current == 'a' ? 5 : 0;
case 5:
return current == 'l' ? 6 : 0;
default:
return 0;
}
}
And a note, theres only 5 if statements there checking pure intergers, this is not exactly an overhead.
Looks like you need a better abstraction for a finite state machine. Think about a class that encapsulates what you want in a better way so you can extend it by configuration rather than modifying code.
If this code is about to be expanded over the time, why not use a state machine? Each state will return the next state based on the character it receives. Maybe it's an overkill for this code, but it'll be a lot easier to maintain, expand & read.
Use switch statement for the outer if chain:
switch (state) {
case 0: <code> ; break;
case 1: <code> ; break;
case 2: <code> ; break;
<etc>
default: return 0; break;
}