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.
Related
i have a class in a java program where i am using a toString function to retrieve data. the toString checks a private function in the same class which returns a int value, for displaying different types of return messages.~
The problem is that if i use a local variable in the string function every turns out good, but if i check in the if statements directlly the private function, this function doesnt return any value.
private int computerTryHorizontalPlay() {
int repeatedMyValueCount = 0;
int repeatedYourValueCount = 0;
int[] myPositions = new int[3];
int[] yourPositions = new int[3];
for (int a = 0; a < 3; a++) {
int repeatedMyValue = 0;
int repeatedYourValue = 0;
int emptyFields = 0;
int[] emptyPosition = new int[2];
for (int b = 0; b < 3; b++) {
if (jogoGalo[a][b] == 'X') {
repeatedMyValue++;
} else if (jogoGalo[a][b] == 'O') {
repeatedYourValue++;
}
if (jogoGalo[a][b] == '-') {
emptyPosition[0] = a;
emptyPosition[1] = b;
emptyFields++;
}
}
if (repeatedMyValue == 3 || repeatedYourValue == 3) {
return 3;
} else {
if (emptyFields == 1) {
if (repeatedMyValue == 2) {
repeatedMyValueCount++;
myPositions[repeatedMyValueCount - 1] = emptyPosition[0];
myPositions[repeatedMyValueCount] = emptyPosition[1];
} else if (repeatedYourValue == 2) {
repeatedYourValueCount++;
yourPositions[repeatedYourValueCount - 1] = emptyPosition[0];
yourPositions[repeatedYourValueCount] = emptyPosition[1];
}
}
}
}
if (repeatedMyValueCount > 0) {
jogoGalo[myPositions[0]][myPositions[1]] = 'X';
return 2;
} else if (repeatedYourValueCount > 0) {
jogoGalo[yourPositions[0]][yourPositions[1]] = 'X';
return 1;
}
return 0;
}
This doesn´t work!
public String toString() {
if(computerTryHorizontalPlay() == 3) {
return "The game has already ended!";
}
else if(computerTryHorizontalPlay() == 2) {
return "Computer won!";
}
else if(computerTryHorizontalPlay() == 1) {
return "Computer defendeu!";
}
return null;
}
This works!
public String toString() {
int horizontalFunctionValue = computerTryHorizontalPlay();
if(horizontalFunctionValue == 3) {
return "The game has already ended!";
}
else if(horizontalFunctionValue == 2) {
return "Computer won!";
}
else if(horizontalFunctionValue == 1) {
return "Computer defendeu!";
}
return null;
}
}
toString() must be a read-only method, i.e. it is not allowed to have side-effects like changing the state of the object. Since computerTryHorizontalPlay() is a state-changing method, you are not allowed to call it from toString().
Since the only state-change happens in the last if statement, you can change the code to not execute the play when called from toString(), like this:
private int computerTryHorizontalPlay() {
return computerTryHorizontalPlay(true);
}
private int computerTryHorizontalPlay(boolean doMove) {
// lots of code here
if (repeatedMyValueCount > 0) {
if (doMove)
jogoGalo[myPositions[0]][myPositions[1]] = 'X';
return 2;
} else if (repeatedYourValueCount > 0) {
if (doMove)
jogoGalo[yourPositions[0]][yourPositions[1]] = 'X';
return 1;
}
return 0;
}
public String toString() {
if(computerTryHorizontalPlay(false) == 3) {
return "The game has already ended!";
}
else if(computerTryHorizontalPlay(false) == 2) {
return "Computer won!";
}
else if(computerTryHorizontalPlay(false) == 1) {
return "Computer defeated!";
}
return null;
}
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
}
This program will print a statement for when they are all equal, but not when they aren't. What is wrong?
int k = 0;
while (k < numbers.length - 1 )
{
if(numbers[k]==numbers[k+1])
{
k++;
}
}
if(k == numbers.length - 1)
{
System.out.println("All the numbers are the same");
}
else
{
System.out.println("All the numbers are not the same");
}
You have an infinite loop, see:
int[] numbers = {3,3,5,3,3};
int k = 0;
while (k < numbers.length - 1 ) // k never be k >= numbers.length - 1
{
if(numbers[k]==numbers[k+1]) // if not, k never increase
{
k++;
}
}
if(k == numbers.length - 1)
{
System.out.println("All the numbers are the same");
}
else
{
System.out.println("All the numbers are not the same");
}
You can use following code instead of you solution:
private static boolean isEqual(int[] numbers) {
Integer oldNumber = null;
for(int number: numbers) {
if(oldNumber != null && oldNumber != number) {
return false;
}
oldNumber = number;
}
return true;
}
public static void main(String[] args) {
int[] numbers = {3,3,5,3, 3};
if(isEqual(numbers))
{
System.out.println("All the numbers are the same");
}
else
{
System.out.println("All the numbers are not the same");
}
}
Change your code to use a for loop, and break out when you find a difference:
boolean allSame = true;
for(int i = 0; i < numbers.length - 1; i++)
{
if(numbers[i]!=numbers[i+1])
{
allSame = false;
break;
}
}
if(allSame)
{
System.out.println("All the numbers are the same");
}
else
{
System.out.println("All the numbers are not the same");
}
Try this:
boolean allSame = true;
while (allSame == true) {
for (int i = 0; i < numbers.length; i++) {
if (numbers[0] != numbers[i+1]) {
allSame = false;
}
}
}
//Lets user know if array contained same elements or not
if (allSame) {
System.out.println("All the numbers are the same. ");
}
else {
System.out.println("Not all numbers are the same. ");
}
Check out the "numbers[0]" in that for loop. We can always compare all the elements to the first element because if they're not the same even once, obviously they're not all the same.
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.
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!!!");
}
}