Alternating between even and odd elements in Array with GUI - java

I'm trying to work with more GUI stuff but I'm having problem with something. I have an array of JLabels. Each of them contain 1 number from 0 to 7. I'm making the numbers "light up" by changing the background color from black to green. Is there any way to make all the even numbers "light up" while keeping all the odd numbers dark and then vice versa? I tried using a timer but my algorithm isn't working as it should. Below is the code for the method that configures the timer. Thanks
public void configureAlternatingTimer() {
if (this.timer != null) {
this.timer.stop();
}
this.timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
for (int i = 0; i <= 8; i++) {
if (i == 0 || i == 2 || i == 4 || i == 6) {
lights[1].setBackground(Color.black);
lights[3].setBackground(Color.black);
lights[5].setBackground(Color.black);
lights[7].setBackground(Color.black);
lights[i].setBackground(Color.green);
}
if (i == 1 || i == 3 || i == 5 || i == 7) {
lights[0].setBackground(Color.black);
lights[2].setBackground(Color.black);
lights[4].setBackground(Color.black);
lights[6].setBackground(Color.black);
lights[i].setBackground(Color.green);
}
if(i==8) {
return;
}
}
}
});
this.timer.start();
}
Also, I'm trying to simulate a "larson scanner" which would light up to 7 then go back down to 0 then repeat. I can get it to go from 0 to 7 it's just the going back down part that I'm having trouble with. Thanks

Drop the for-loop, it's preventing the Event Dispatching Thread from processing repaint requests
Instead, each time that the actionPerformed method is called, update some kind of counter and then take action on it, for example...
this.timer = new Timer(100, new ActionListener() {
private int sequence = 0;
public void actionPerformed(ActionEvent evt) {
if (sequence % 2 == 0) {
lights[1].setBackground(Color.black);
lights[3].setBackground(Color.black);
lights[5].setBackground(Color.black);
lights[7].setBackground(Color.black);
lights[sequence].setBackground(Color.green);
} else {
lights[0].setBackground(Color.black);
lights[2].setBackground(Color.black);
lights[4].setBackground(Color.black);
lights[6].setBackground(Color.black);
lights[sequence].setBackground(Color.green);
}
sequence++;
if (sequence > 7) {
// This seems to be important...?
}
}
});
Updated based on comments
This should show all odds or all evens...
Timer timer = new Timer(500, new ActionListener() {
private int sequence = 0;
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(sequence + "; " + (sequence % 2));
for (int index = 0; index < lights.length; index++) {
if (index % 2 == 0 && sequence % 2 == 0 || index % 2 != 0 && sequence % 2 != 0) {
lights[index].setBackground(Color.GREEN);
} else {
lights[index].setBackground(Color.BLACK);
}
}
sequence++;
if (sequence > 7) {
sequence = 0;
}
}
});

To determine if you have an even or odd number, you should think about using modulus operator % to determine if a number is odd or even. The modulus will return the remainder of a number after it has been divided.
For example:
4 / 2 = 2r0
5 / 2 = 2r1
6 / 2 = 3r0
7 / 2 = 3r1
so on and so forth...
if(i % 2 == 0) {
// even
} else {
// odd
}

Related

FizzBuzz: It gives me the wrong print statement. What is wrong?

Everybody knows that FizzBuzz question that interviewers ask students.
Basically, when you have an incrementor and for each number which is a divisible of 3 you say fizz, for a number divisible by 5 you say buzz, while if it is divisible by both(3 and 5) you say FizzBuzz, hence the name.
It is a relatively easy problem to solve and I have done it, but I think my solution is a bit clunky. This is it:
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i;
}
for (int i : numbers) {
if (i % 3 == 0) {
System.out.println("Fizz");
} else if(i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println("FizzBuzz");
}
}
But the problem is that when the number is divisible by both 3 and 5 it gives me "Fizz" for some reason. Can somebody explain to me, because I'm new to java programming. Thanks in advance!
The problem lies in the order of your if statements. Lets take a look at the number 15, which is the first number divisible by both 3 and 5. Because of the order in which you have your if statements, the first statement that is checked is
if ( 15 % 3 == 0)
The result of the operation is indeed equal to 0, as 15 is divisible by 3 and so "Fizz" is printed and your else is ignored.
Think about how you should structure the order of your if statements and which additional condition should you introduce to catch the specific case of being divisible by both i % 3 == 0 && i % 5 == 0.
When you enter the if statement and your number is 15 for exemple, you enter the first if statement and.. prints "Fizz" as you stated, because 15 % 3 == 0 returns true. Then it ignores the else.
You want the first if to be
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");*
}
Try this code
public static void main(String[] args) {
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i;
}
for (int i : numbers) {
if ((i % 3 == 0) && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if(i % 5 == 0) {
System.out.println("Buzz");
} else if (i % 3 == 0){
System.out.println("Fizz");
}
}
}

Java Hailstone Sequence

I have to do a Hailstone Sequence code in Java for example it should go like this:
10 5 16 8 4 2 1 4 2 1
Mine goes like this:
10 5 16 8 4 2 1
How to fix this?
This is my code:
static int counter;
static int HailstoneNumbers(int Number)
{
System.out.print(Number+ " ");
if (Number == 1 && counter == 0) {
return counter;
}
else if (Number == 1 && counter != 0) {
counter++;
return counter;
}
else if (Number % 2 == 0) {
counter++;
HailstoneNumbers(Number / 2);
}
else if (Number % 2 != 0) {
counter++;
HailstoneNumbers(3 * Number + 1);
}
return counter;
}
public static void main(String[] args)
{
int Number;
KeyboardReader reader = new KeyboardReader();
System.out.println("What is your intial value? ");
Number = reader.readInt();
int x;
x = HailstoneNumbers(Number);
System.out.println();
System.out.println("Number of Steps: " +x);
}
}
Your code explicitly says to stop the sequence when it reaches the number 1. Maybe you meant the behavior to be different depending on the value of counter, but it isn't clear why it should not stop at the first 1 but should stop at the second (as counter will not be 0 for either).

Comparing and finding an ArrayList with the longest length

I am solving a task linked to the Collatz Problem. I have created a method that produces 1 from any starting number:
public static void sequence(int value)
{
ArrayList<Integer> calc = new ArrayList<Integer>();
calc.add(value);
while(value != 1)
{
if(value % 2 == 0)
{
value = value / 2;
}
else if(value % 2 != 0)
{
value = (value * 3) + 1;
}
calc.add(value);
if(value == 1 )
{
System.out.println(calc);
}
}
}
public static void main(String[] args) {
for(int x = 1000000; x > 0; x--)
{
sequence(x);
}
}
}
The next part of my task is finding a method which will find the longest Collatz sequence below 1,000,000.
I came up with several solutions such as the one below..of course none of them worked.
while(value != 1)
{
if(value % 2 == 0)
{
value = value / 2;
}
else if(value % 2 != 0)
{
value = (value * 3) + 1;
}
calc1.add(value);
if(calc1.size() > calc2.size())
{
calc2 = calc1;
}
}
System.out.println(calc2);
}
Could anyone please help and guide me to finding the correct methods for finding the longest Collatz sequence using the comparison of 2 or more ArrayLists. If there are better options than the use of an ArrayList I more than welcome these methods.
Thanks.
You need to maintain a maxList which will get updated with the longest sequence.
You can either pass it to your calc() method in each call or declare it as a Class variable for using it on top of both calc() and main() methods.
// to update the max list
maxList = (list.size() > maxList.size()) ? list : maxList;
At the end just print the results
System.out.println(maxList.size());
System.out.println(maxList);
Update: You need to figure out efficient ways to pass numbers in the calc() method.
It will throw java.lang.OutOfMemoryError for large input.

Java Monopoly Game

I made a Board and I set the board's layout to null. So I position my token's by moving them pixel by pixel. But when turning the corners I am having a trouble. After first 10 position token can make the turn and continue for the next 10 position. But it is impossible for my token to make the 2. turn.
Can anyone advice me a better code for this problem. I think I make things get more complicated than it is.
if(g.getPosx() <= 650 && g.getPosx() >= 50 && g.getPosy()==650) {
if(g.getPosx()-unitChange*d.getDice() <= 50) {
temp = unitChange*d.getDice() - (g.getPosx() - 50);
g.setPosx(50);
g.setPosy(g.getPosy()-temp);
}
else {
g.setPosx(g.getPosx()-unitChange*d.getDice());
temp = 0;
}
}
else if(g.getPosy() <= 650 && g.getPosy() >= 50 && g.getPosx()==650) {
if(g.getPosy()-unitChange*d.getDice() <= 50) {
temp = unitChange*d.getDice() - (g.getPosy() - 50);
g.setPosy(50);
g.setPosx(g.getPosx()-temp);
}
else {
g.setPosy(g.getPosy()-unitChange*d.getDice());
temp = 0;
}
}
else if(g.getPosx() <= 650 && g.getPosx() >= 50 && g.getPosy()==50) {
if(g.getPosx()-unitChange*d.getDice() <= 50) {
temp = unitChange*d.getDice() - (g.getPosx() - 50);
g.setPosx(50);
g.setPosy(g.getPosy()-temp);
}
else {
g.setPosx(g.getPosx()-unitChange*d.getDice());
temp = 0;
}
}
else if(g.getPosy() <= 650 && g.getPosy() >= 50 && g.getPosx()==50) {
if(g.getPosy()-unitChange*d.getDice() <= 50) {
temp = unitChange*d.getDice() - (g.getPosy() - 50);
g.setPosy(50);
g.setPosx(g.getPosx()-temp);
}
else {
g.setPosy(g.getPosy()-unitChange*d.getDice());
temp = 0;
}
}
Instead of using the current X and Y positions to track which location the piece is stopped on, try tracking which property the piece has landed on instead. so property 1 would be the first stop on the board after GO all the way up to boardwalk at position 39. Then you can have a function like
movePlayerToLocation(Player player, int location){
// calculate your x and y based on the property locatoin
if(locatoin < 11){
// on first edge
} else if (location < 21) {
// on second edge
} else if (location < 31)
// on third edge
} else {
// on fourth edge of the board
}
// do your g.setPos-ing
}

How do I make make my code repeat itself?

public Action getMove(CritterInfo info) {
count++;
Direction d = info.getDirection();
if (count < 100) {
if (info.getFront() == Neighbor.OTHER) {
return Action.INFECT;
} else {
return Action.RIGHT;
}
}
if (count >= 100) {
if (info.getFront() == Neighbor.OTHER) {
return Action.INFECT;
} else if (count / 100.0 < 2.0 && count / 100.0 >= 1.0 && !(d == Direction.EAST)) {
return Action.LEFT;
} else if (count / 100.0 < 3.0 && count / 100.0 >= 2.0 && !(d == Direction.WEST)) {
return Action.RIGHT;
} else {
return Action.HOP;
}
}
return Action.INFECT;
}
Right now I have this code that is part of my critter and i'm having problems are the if (count >= 100) part of the code. I can't get my go east and go west code to repeat itself because when I divide count by 100.0, it only works up until 299 then it just stays going west running into the wall. I've tried to set an else if statement after my go west code stating
} else if (count == 299) {
count = 0;
}
but this didn't solve my problem either. Any ideas? I just want my critter to sweep east and west over and over again.
Just use variables instead of your numbers, and change them each time their numbers are reached.Then you can create a method that changes the direction each time the number reaches 100+(100*n).
So, if you reach 200, it will check that the condition I set above is true and will therefore change directions for the next 100 numbers.
Was this what you were looking for , or did I misunderstand what you wanted?
You can use some kind of "cyclic" function like modulo (%) instead of the absolute value of count. E.g.
public Action getMove(CritterInfo info) {
count++;
Direction d = info.getDirection();
if (count < 100) {
if (info.getFront() == Neighbor.OTHER) {
return Action.INFECT;
} else {
return Action.RIGHT;
}
}
else {
int choiceOfAction = (count - 100)%200;
if (0 <= choiceOfDir && choiceOfDir < 100 && !(d == Direction.EAST)) {
return Action.LEFT;
} else if (100 <= choiceOfDir && choiceOfDir < 200 && !(d == Direction.WEST)) {
return Action.RIGHT;
} else {
return Action.HOP;
}
}
}
The line int choiceOfAction = (count - 100)%200; will yield a value of choiceOfAction with:
if count is in [100, 200[ : choiceOfAction is in [0, 100[
if count is in [200, 300[ : choiceOfAction is in [100, 200[
if count is in [300, 400[ : choiceOfAction is in [0, 100[
etc.
Note that I removed the last return in your method that was never reached, and also, that in the case above you will HOP only when you reach the limit and change direction.

Categories