While loop boolean confusion - java

Why is my boolean t being set to false after the while loop. I have placed print statements and the "if" conditional within the while loop that sets t=false; never gets hit. Why when I print t out in between the for and while loop does t=false; ?
public void addStudents(Student student){
System.out.println("in addStudents");
boolean t = true;
int counter = 0;
while ( t = true && counter < students.length ){
// System.out.println("while");
if (students[counter].equals(student)) {
// System.out.println("ppppppppppppppppppppppp");
t = false;
counter ++;
// System.out.println("never");
} else {
counter++;
}
}
if (t == true) {
if (students[students.length - 1] != null){
// System.out.println("xxxxxxxxxxxx");
Student[] newstudentsarray = new Student[students.length + 1];
for (int i = 0; i < students.length; i++){
newstudentsarray[i] = students[i];
}
students = newstudentsarray;
students[students.length - 1] = student;
}
}
}

The problem is the Java Operator Precedence where the operator && has a higher precedence as =.
So the statement t = true && counter < students.length is complied into t = (true && counter < students.length) and t is alway set to false at the end of the loop.
You probably wanted to write t == true && counter < students.length but mistyped ==.
This is the reason why it's better to write just
boolean falsy = false;
if(falsy) {
System.out.println("This should never happen");
}
if(!falsy) {
System.out.println("This should always happen");
}
Instead of
boolean falsy = false;
if(falsy == true) {
System.out.println("This should never happen");
}
if(falsy == false) {
System.out.println("This should always happen");
}
When you mistyped you got
boolean falsy = false;
if(falsy = true) {
System.out.println("This should never happen."); // This happens
}
if(falsy = false) {
System.out.println("This should always happen"); // This didn't happens
}

Related

Printing datastructure from input doesn't work

I'm trying to create a program which prints a datastructure from the input. The input and output looks like this: http://puu.sh/kDMc9/2d46462d4d.png. So for example, in the first test case: the first line indicates how many lines will follow in that case. Then if it's the number 1 as the first number on a line it means that you want to add elements to stack/queue/priority-queue and 2 means you want to take out an element, so the second number on a line is the value. Then the output prints if it's stack,queue, priority-queue, impossible or not sure(can be more than one)
This is the code I have now:
import java.util.PriorityQueue;
import java.util.Scanner;
public class DataStructure {
public static void main(String[] args)
{
while(calculate());
}
private static boolean calculate()
{
Scanner input = new Scanner(System.in);
int numberOfRowsPerCase = input.nextInt();
Stack<Integer> stack = new Stack<Integer>();
Queue<Integer> queue = new Queue<Integer>();
PriorityQueue<Integer> prioQueue = new PriorityQueue<Integer>();
boolean stackBool = true;
boolean queueBool = true;
boolean prioQueueBool = true;
int next;
for(int i = 0; i < numberOfRowsPerCase; i++)
{
next = input.nextInt();
if(next == 1)
{
next = input.nextInt();
stack.push(next);
queue.enqueue(next);
prioQueue.add(next);
}
else if(next == 2)
{
next = input.nextInt();
if(!stack.pop().equals(next))
{
stackBool = false;
}
else if(!queue.dequeue().equals(next))
{
queueBool = false;
}
else if(!prioQueue.poll().equals(next))
{
prioQueueBool = false;
}
}
if(stackBool == true)
{
System.out.println("stack");
}
else if(queueBool == true)
{
System.out.println("queue");
}
else if(prioQueueBool == true)
{
System.out.println("priority queue");
}
else if((stackBool == true && queueBool == true) || (queueBool == true && prioQueueBool == true) || (stackBool == true && prioQueueBool == true))
{
System.out.println("not sure");
}
else
{
System.out.println("impossible");
}
}
//Check EOF
String in;
in = input.nextLine();
in = input.nextLine();
if(in.equals(""))
{
return false;
}
return true;
}
}
But when I run the test-case on the picture above, my program prints this: https://ideone.com/mIO1bs which is wrong. I can't find why it does that, can anyone else here maybe see?
Assuming that your logic setting the boolean flags is correct then this part
if(stackBool == true)
{
System.out.println("stack");
}
...
else if((stackBool == true && queueBool == true) || (queueBool == true && prioQueueBool == true) || (stackBool == true && prioQueueBool == true))
{
System.out.println("not sure");
}
will never work as intended because parts of the second condition were already caught by the first condition.
The better suggestion is to come up with a clearer way of representing this. A suggestion that will still probably work is to put your more complicated if statements at the start of the if-else chain.
Disregarding above assumption:
if(!stack.pop().equals(next))
{
stackBool = false;
}
else if(!queue.dequeue().equals(next))
{
queueBool = false;
}
else if(!prioQueue.poll().equals(next))
{
prioQueueBool = false;
}
These should not be elses, they're all completely independent.

Why is my break statement being ignored?

In my method under the if statement:
if (currentLocationX == 0 && currentLocationY == 4)
I have a break statement that should make the program exit out of the while loop and return true for 'answer' and for the method. Yet after some testing it seems that after returning true for 'answer', it goes back into the while loop giving the wrong results int the end. Why is my break statement not doing what it's supposed to? Thank you!
P.S. (this method calls on some other method that were not relevant to mention here)
public boolean solveMaze()
{
boolean answer = false;
int currentLocationX;
int currentLocationY;
//push starting location
pushX(2);
pushY(1);
while((isEmptyX() == false) && (isEmptyY() == false))
{
printMaze();
System.out.println();
currentLocationX = popX();
currentLocationY = popY();
//mark current location as visited
visited(currentLocationX, currentLocationY, maze);
System.out.println("Current Location: " + currentLocationX + ", " + currentLocationY);
if (currentLocationX == 0 && currentLocationY == 4)
{
answer = true;
break;
}
else
{
//push all unvisited OPEN neighbor locations into stack
if (checkEast(currentLocationX, currentLocationY) == 0)
{
pushX(eastX(currentLocationX));
pushY(eastY(currentLocationY));
}
else;
if (checkSouth(currentLocationX, currentLocationY)== 0)
{
pushX(southX(currentLocationX));
pushY(southY(currentLocationY));
}
else;
if (checkWest(currentLocationX, currentLocationY)== 0)
{
pushX(westX(currentLocationX));
pushY(westY(currentLocationY));
}
else;
if (checkNorth(currentLocationX, currentLocationY)== 0)
{
pushX (northX(currentLocationX));
pushY(northY(currentLocationY));
}
else;
}
}
return answer;
}
I wrote out the basic logic of your method as
public static boolean solveMaze() {
boolean answer = false;
int currentLocationX = 0;
int currentLocationY = 4;
while (true) {
if (currentLocationX == 0 && currentLocationY == 4) {
System.out.println("Hit the break");
break;
} else {
System.out.println("Missed the break");
}
}
return answer;
}
and if you execute it you get Hit the break. So your solveMaze() method is fine in terms of breaking out of the loop once it satisfies your if-statement. I would say that if you see your code subsequently going back into the while loop, it must be that solveMaze() was called a second time.

This method that determines the winner of a Mancala does not work

Mancala is a fascinating game that I programmed in Java. On the image below we see a Mancala gameboard. For my problem you need to know that a A1-A6,B1-B6 are called pits and the big pits are called kalahs.
(source: pressmantoy.com)
The pits A1-A6 and right kalah belongs to player A and pits B1-B6 and left kalah to player B.
The game ends when all six pits on one side of the gameboard are empty or when there are more than 24 pits in one player's kalah. This is what I tried to program in a boolean method (which returns true if there is a winner so I can use other method to tell who it is):
public boolean isThereAWinner() {
ArrayList <SuperPit> pitsOfOwner = owner.getmyPits();
ArrayList <SuperPit> pitsOfOpponent = owner.getopponent().getmyPits();
for (int i = 0; i < pitsOfOwner.size(); i++) {
if (pitsOfOwner.get(i).isValidPlayOption() == true)
return false;
}
for (int i = 0; i < pitsOfOpponent.size(); i++) {
if (pitsOfOpponent.get(i).isValidPlayOption() == true)
return false;
}
if (owner.getKalah().getSeed() > 24) return true;
return false;
}
Where:
protected int seed;
public int getSeed() {
return seed;
}
public boolean isValidPlayOption() {
if (getSeed() > 0) return true;
else return false;
}
The oppositepit() and nextPit() methods work. The myPits ArrayLists contain the pits that belong to the two respective players.
I thought that this method should work since if one player no longer has seeds in his pit the game should stop. The method isThereAWinner() is run every time a player makes a move.
Unfortunately, the method always returns false. I have no idea why and hope someone here can provide me with some insight.
It's always returning false because of :
for (int i = 0; i < pitsOfOwner.size(); i++) {
if (pitsOfOwner.get(i).isValidPlayOption() == true)
return false;
}
The moment any pit has seeds, it returns false, even if the other board is completely empty.
How about:
int sum1 = 0;
for (int i = 0; i < pitsOfOwner.size(); i++) {
sum1 += pitsOfOwner.get(i).getSeed();
}
if (sum1 == 0) return true; // all pits are empty
If one player has one valid play option, you already return a value. You need to continue checking.
You don't return true if a player doesn't have a move.
What about checking the opponent's kalah?
== true is redundant.
Code:
public boolean isThereAWinner() {
ArrayList <SuperPit> pitsOfOwner = owner.getmyPits();
ArrayList <SuperPit> pitsOfOpponent = owner.getopponent().getmyPits();
boolean hasLost = true;
for (int i = 0; i < pitsOfOwner.size() && hasLost; i++) {
if (pitsOfOwner.get(i).isValidPlayOption())
hasLost = false;
}
if (hasLost) return true;
hasLost = true;
for (int i = 0; i < pitsOfOpponent.size() && hasLost; i++) {
if (pitsOfOpponent.get(i).isValidPlayOption())
hasLost = false;
}
if (hasLost) return true;
if (owner.getKalah().getSeed() > 24) return true;
if (owner.getopponent().getKalah().getSeed() > 24) return true;
return false;
}
The && hasLost is just an optimization to stop the loop once you find a move.
With less redundancy:
private boolean hasLost(Player player)
{
boolean hasLost = true;
for (int i = 0; i < player.getmyPits().size() && hasLost; i++) {
if (player.getmyPits().get(i).isValidPlayOption())
hasLost = false;
}
return (hasLost || player.getopponent().getKalah().getSeed() > 24);
}
public boolean isThereAWinner() {
if (hasLost(owner)) return true;
if (hasLost(owner.getopponent())) return true;
return false;
}

Java 2Dimensional Boolean Array Values

I'm having a problem with my 2 dimensional boolean array. (or it may be with the logic of printing out the values). I set all of the values in the array to false in the beginning, and then later i print out the values to the screen. When i print them out, they all come up as true.
x=20;
y=10;
boolArray = new boolean[x][y];
for(int c=0;c<x;c++)
{
for(int i=0;i<y;i++)
{
boolArray[c][i] = false;
}
}
System.out.println("2D Boolean Array:");
for(int a = 0; a < boolArray.length; a++)
{
for(int b = 0; b < boolArray[a].length; b++)
{
if(boolArray[a][b] = true)
{
System.out.print("T");
}
else if(boolArray[a][b] = false)
{
System.out.print("F");
}
}
}
This is bad:
if(boolArray[a][b] = true)
{
System.out.print("T");
}
else if(boolArray[a][b] = false)
{
System.out.print("F");
}
you are using the assignment operator = instead of the comparison operator ==
You could change it to
if(boolArray[a][b] == true)
//...
else if(boolArray[a][b] == false)
or nicer
if(boolArray[a][b])
//...
else if(!boolArray[a][b])
or even nicer:
if(boolArray[a][b])
//...
else
Try this:
if(boolArray[a][b])
{
System.out.print("T");
}
else
{
System.out.print("F");
}
With booleans you can do like
if(boolean field)
You have used = assigment instead of == comparison.

Testing parentheses in a equation using stack java

I'm writing a program that will take in an equation and check if all the parentheses line up and it will output if it is good or not.
For Ex: (3+4) is good
((3*8) is NOT Good
I'm not allowed to use java's built in push() pop() methods ext..
I have to make my own which I think I got....I think!
The problem I'm having is in the Test() method.
First I'm not sure how to write the while loop like:
while(there are still characters)
Anyway the output I'm getting is: stack is empty -1
Any help is appreciated. I'm one of the slower program learners and I couldn't be trying any harder. Thanks.
Here's what I got:
public class Stacked {
int top;
char stack[];
int maxLen;
public Stacked(int max) {
top = -1;
maxLen = max;
stack = new char[maxLen];
}
public void push(char item) {
top++;
stack[top] = item;
}
public int pop() {
//x = stack[top];
//top = top - 1;
top--;
return stack[top];
}
public boolean isStackEmpty() {
if(top == -1) {
System.out.println("Stack is empty" + top);
return true;
} else
return false;
}
public void reset() {
top = -1;
}
public void showStack() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j = top; j > -1; j--){
System.out.println(stack[j]);
}
System.out.println(" ");
}
public void showStack0toTop() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j=0; j>=top; j++){
System.out.println(stack[j]);
}
System.out.println(" ");
}
//}
public boolean test(String p ){
boolean balanced = false;
balanced = false;
//while ( )
for(char i = '('; i < p.length(); i++ ){
push('(');
}
for (char j = ')'; j < p.length(); j++){
pop();
}
if (isStackEmpty()) {
balanced = true;
//return balanced;
}
return balanced;
}
public static void main(String[] args) {
Stacked stacks = new Stacked(100);
String y = new String("(((1+2)*3)");
stacks.test(y);
//System.out.println(stacks.test(y));
}
}
Now I'm getting somewhere. I need to be pointed in the right direction again. Thanks everyone this helped big time. I still have a lot more to do but this is good for now. Eventually I need to create a two more methods: one "infix to postfix" and the other "evaluating postfix" and at the end I'll need to read in answers from a text file instead of putting my own into the main method. Thanks again much appreciated.
Unless you need to actually evaluate the equation, a stack is too complicated a solution here. You simply need a counter:
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
//check if there are more closed than open
if (openParentheses < 0) {
return false;
}
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
If you absolutely must use stacks, use this:
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
push('x'); //doesn't matter what character you push on to the stack
} else if (p.charAt(i) == ')') {
pop();
}
//check if there are more closed than open
if (stackIsEmpty()) {
return false;
}
}
if (isStackEmpty()) {
return true;
} else {
return false;
}
I agree with Griff except that you should include another check if you didn't have more closed parentheses than open. (x*y))( is not a valid entry.
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
if(openParentheses<0)
return false;
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
You may be required to use a stack, but this could be done with a simple counter. This will show you a how to iterate over the characters of a String:
boolean test(String p) {
int balance = 0;
for (int idx = 0; idx < p.length(); ++idx) {
char ch = p.charAt(idx);
if (ch == '(')
++balance;
else if (ch == ')')
--balance;
if (balance < 0)
return false;
}
return balance == 0;
}
Of course, you could replace the increment and decrement with pushes and pops, respectively, on a stack.
For parsing you can use a for loop over the index and address the character of the string at the certain index.
But you actually do not need a stack, an integer variable openBraces is sufficient:
initialize with 0
for '(' you increment the variable one
for ')' you decrement the variable one
if openBraces is <0, you immediately give an error
if at the end openBraces is not equal to 0, you give an error.
Since you should do your homework yourself, I did not post source code, only explanations ;)
I think you just need this --
for ( int i = 0 ; i < p.length(); i++ ) {
char c = p.charAt(i);
if ( c == '(' )
push('(');
else if ( c == ')' ) {
if ( isStackEmpty() ) {
// Return error here because of unbalanced close paranthesis
}
pop();
}
else {
// do nothing
}
}
You CAN use a stack if you must, but considering how simplistic this is, you just need a counter that you increment and decrement and check for 0 at the end.
If you do use a counter, you should check after every decrement if the value is less than 0. If so, throw an error.
Edited based on Ryan/Dave Ball's comments.
It could be done like this:
String equation = "(2+3))";
Integer counter = 0;
//while(equation)
for(int i=0; i<equation.length();i++)
{
if(equation.charAt(i)=='(')
{
counter++;
}
else
if(equation.charAt(i)==')')
{
counter--;
}
}
if(counter == 0)
{
System.out.println("Is good!!!");
}
else
{
System.out.println("Not good!!!");
}
}

Categories