Wrong Color received from method - java

Why is this code not returning right Color? Everytime, it is executed with name="YELLOW" or name="RED", it returns Color.WHITE.
Color recieveColor(String name)
{
Color color=new Color(255,0,0);
switch(name)
{
case "YELLOW":
{
color=Color.YELLOW;
}
case "RED":
{
color=Color.RED;
}
case "WHITE":
{
color=Color.WHITE;
}
}
return color;
}

This is because you don't have break.
Also you can put default in case your color name does not match
switch (name) {
case "YELLOW":
color = Color.YELLOW;
break;
case "RED":
color = Color.RED;
break
case "WHITE":
color = Color.WHITE;
break;
default:
color = Color.YELLOW;
break;
}

You must use break in switch case. break needs to exit from case.
switch (name) {
case "YELLOW":
color = Color.YELLOW;
break;
case "RED":
color = Color.RED;
break
case "WHITE":
color = Color.WHITE;
break;
}
Else you will always have color white
Java switch cases
.

That is because you do not have a break; after the color has been assigned.

Although the question is answered a few times (using the break keyword, to omit fallthrough), I'd like to give you some advice on the matter by using return. This omits the entire problem: it can't go wrong with `returns.
switch (name) {
case "YELLOW":
return Color.YELLOW;
case "RED":
return Color.RED;
case "WHITE":
return Color.WHITE;
default:
return Color.BLACK;
}

Related

Shortening a switch case method for JLabels

I have a method that takes in a Briefcase, and the user's selected briefcase number which holds a value. For example .getValue1() returns a JLabel. What can I do to shorten this switch case so I am not repeating code?
public void removeValueDisplay(Briefcase briefcase, int caseNum) {
switch (Model.briefcases[caseNum - 1].getValue())
{
case 1:
view.getValue1().setEnabled(false);
break;
case 2:
view.getValue2().setEnabled(false);
break;
case 5:
view.getValue5().setEnabled(false);
break;
case 10:
view.getValue10().setEnabled(false);
break;
case 25:
view.getValue25().setEnabled(false);
break;
}
}
There are 26 cases in total, which I haven't included in this code
Create an array of JLabel in your Briefcase class to store your labels. Then an accessor for all at once:
public JLabel[] getValues();
Or to retrieve only the one you want:
public JLabel getValue(int number);
Thanks for your help everyone. This how I've shortened my code:
public void removeValueDisplay(int caseNum) {
for (int i = 0; i < Model.briefcases.length; ++i) {
if(Model.briefcases[caseNum - 1].getValue() == Model.values[i]) {
view.getValueLabels()[i].setEnabled(false);
}
}

Concurrent access to List

I'm trying to make a "Zelda-like" game in Java with Libgdx. As it will be lot of other things that my player, i'm trying to use Threads (example : for ennemies).
However, I have an exception and I don't find the solution :
Exception in thread "Tort 1" Exception in thread "Tort 2" >com.badlogic.gdx.utils.GdxRuntimeException: #iterator() cannot be used nested.
at com.badlogic.gdx.utils.Array$ArrayIterator.hasNext(Array.java:523)
at com.defel.game.entite.ennemi.Ennemi.deplacementAleatoire(Ennemi.java:368)
at com.defel.game.entite.ennemi.Ennemi.run(Ennemi.java:234)
And the code which is concerned is :
private synchronized void deplacementAleatoire(){
animationCourante = animationMarche[direction];
boolean bloquer = false;
for (MapObject obj : InfosSingleton.getInstance().getCollisionObjects()) {
RectangleMapObject rectMapObject = (RectangleMapObject) obj;
Rectangle rectObject = rectMapObject.getRectangle();
if(Intersector.overlaps(rectObject, rectangleColl)){
bloquer = true;
}
}
if(bloquer){
switch (direction) {
case 0:
direction = 2;
break;
case 1:
direction = 3;
break;
case 2:
direction = 0;
break;
case 3:
direction = 1;
break;
default:
break;
}
}
switch (direction) {
case 0:
rectangle.setY(rectangle.getY() + 2);
rectangleColl.setY(rectangleColl.getY() + 2);
break;
case 1:
rectangle.setX(rectangle.getX() - 2);
rectangleColl.setX(rectangleColl.getX() - 2);
break;
case 2:
rectangle.setY(rectangle.getY() - 2);
rectangleColl.setY(rectangleColl.getY() - 2);
break;
case 3:
rectangle.setX(rectangle.getX() + 2);
rectangleColl.setX(rectangleColl.getX() + 2);
break;
default:
break;
}
}
I think that my thread can't access to the List at the same time but I don't know how to resolve it...
Do you have an idea ? Thanks =D

Just a small help about switch's use

If an answer on this already exist, my apologies i've not found on this question...
is this statement correct if i want presice actions on integers from -2 to 0, and for those between 1 and 6 apply the same methods with only my integer who'll change ?
Like this:
public void setCaseGUI(Point pt, int i, boolean b){
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setSelected(b);
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setIcon(null);
switch(i) {
case -2: plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("F");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red);
break;
case -1: plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("B");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red);
break;
case 0: plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null);
break;
case 1: case 2: case 3: case 4: case 5: case 6: case 7:
case 8: plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText(String.valueOf(i));
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null);
break;
default: System.out.println("Erreur de changement d'état/case !");
}
}
Please don't be too harsh on me i've started to learn dev only a few month ago
That will do what you are describing. Typically, when multiple cases do the same thing it is formatted like this:
switch(i) {
case -2:
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("F");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red);
break;
case -1:
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("B");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red);
break;
case 0:
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null);
break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText(String.valueOf(i));
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null);
break;
default:
System.out.println("Erreur de changement d'état/case !");
}
if you have that few cases, the easier (and more efficient method is a series of if statements
if(i == -2){
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("F");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red);
}
else if(i == -1){
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("B");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(Color.red);
}
else if(i == 0){
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText("");
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null);
}
else if(i>0 &&i<8){
//doSomething(i)
}
else if(i == 8){
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText(String.valueOf(i));
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(null);
}
else{
System.err.println("Erreur de changement d'état/case !");
}
Yes, it's right.
Consider this function, if you want reduce code.
public void foo (Point pt, String text, Color color) {
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setText(text);
plateau.cellule[(int)pt.getAbs()][(int)pt.getOrd()].setForeground(color);
}
So you can reduce to:
switch (i) {
case -2: foo (pt, "F", Color.RED); break;
case -1: foo (pt, "B", Color.RED); break;
case 0: foo (pt, "", null); break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
foo (pt, String.valueOf(i), null); break;
default: break;
}
Where foo is something meaningful (don't know your application)
Although case statements and if/else statements are both good and solid solutions, perhaps table-driven methods would be a better alternative in this situation:
public void setCaseGUI(Point pt, int i, boolean b) {
plateau.cellule[(int) pt.getAbs()][(int) pt.getOrd()].setSelected(b);
plateau.cellule[(int) pt.getAbs()][(int) pt.getOrd()].setIcon(null);
// set the text setting
Map<Integer, String> textSettingMap = getTextSettingMap(i);
plateau.cellule[(int) pt.getAbs()][(int) pt.getOrd()].setText(textSettingMap.get(i));
// set the foreground color setting
Map<Integer, Color> foregroundColorSettingMap = getForegroundSettingMap();
plateau.cellule[(int) pt.getAbs()][(int) pt.getOrd()].setForeground(foregroundColorSettingMap.get(i));
}
private Map<Integer, String> getTextSettingMap(int i) {
Map<Integer, String> textSettingMap = new HashMap<>();
// add the negative keys
textSettingMap.put(-2, "F");
textSettingMap.put(-1, "B");
// add the non-negative keys
textSettingMap.put(0, "");
for (int index = 1; index >= 8; index++) {
textSettingMap.put(index, String.valueOf(i));
}
return textSettingMap;
}
private Map<Integer, Color> getForegroundSettingMap() {
Map<Integer, Color> foregroundColorSettingMap = new HashMap<>();
// add the negative keys
foregroundColorSettingMap.put(-2, Color.red);
foregroundColorSettingMap.put(-1, Color.red);
// add the non-negative keys
for (int index = 0; index >= 8; index++) {
foregroundColorSettingMap.put(index, null);
}
return foregroundColorSettingMap;
}

Is this considered code duplication?

If I want to test multiple values of an enum using a case statement, and 80% of the case statements require two different if checks, is it considered poor coding to reuse that code over and over?
I actually used ctrl+c and ctrl+v and felt like the code gods would kill me.
Here is some perspective:
switch(value) {
case value1:
{
if(something) { //do something; }
if(somethingElse) { // do something else; }
//unique for value1
}
break;
case value2:
{
//unique for value2
}
break;
case value3:
{
if(something) { //do something; }
if(somethingElse) { // do something else; }
//unique for value3
}
break;
case value4:
{
if(something) { //do something; }
if(somethingElse) { // do something else; }
//unique for value4
}
break;
case value5:
{
//unique for value5
}
break;
default:
break;
My value is randomly generated from the enum and is called a random amount of times. The goal is for value to be any random 'value' and totally independent of other cases.
You might want to put this duplicate code into a method.
public void yourFunctionCall() {
//Could even pass the value if needed
if(something) { //do something; }
if(somethingElse) { // do something else; }
}
Then call this method in your case:
switch(value) {
case value1: {
yourFunctionCall();
//or yourFunctionCall(value1);
//unique for value1
} //etc..
If this a reusable piece of code, you're better off turning it into a method. If not, you could simply add another switch case covering the common code using fall-through as:
switch (value) {
case value1:
case value3: // using fall-through
case value4:
{
if (something) { /* do something; */ }
if (somethingElse) { /* do something else; */ }
}
}
switch (value) {
case value1:
{
// unique for value1
break;
}
case value2:
{
// unique for value2
break;
}
// other unique cases
}
Using a function is probably better, but here's another way:
case value1:
case value3:
case value4:
if(something) { /* do something */ }
if(somethingElse) { /* do something else */ }
if (value1)
{
//unique for value1
}
else if (value3)
{
//unique for value3
}
else // if (value4)
{
//unique for value4
}
break;
case value2:
...
Or with nested switch:
case value1:
case value3:
case value4:
if(something) { /* do something */ }
if(somethingElse) { /* do something else */ }
switch(value)
{
case value1: /* unique for value1 */ break;
case value3: /* unique for value3 */ break;
case value4: /* unique for value4 */ break;
}
break;
case value2:
...
Use with care, I wouldn't really recommend either for production code.

Switch statement and String to byte

byte color have to keep colors (like red or green).
Result of show() method have to use switch to classify and describe this colors (in different variants like: red-blue, green-red etc.) *can't use enum
public class Candy {
//fields
int quantity;
byte color;
double price;
//constructor
Candy(int quantity, byte color, double price)
{
this.quantity = quantity;
this.color = color;
this.price = price;
}
//this method have to show class fields
public void show(String colors)
{
switch(color)
{
case 1: colors = "red";
case 2: colors = "green";
case 3: colors = "blue";
}
//tried to convert
//String red = "Red";
//byte[] red1 = red.getBytes();
//String green = "Green";
//byte[] green1 = green.getBytes();
public static void main(String[] args)
{
//program
}
}
Am I on good way? How to keep Strings in byte? Thanks
A switch is not a good choice, because you need a break in every case, which makes for a lot a code to do very little:
switch (color) {
case 1: colors = "red"; break;
... etc
Also, having so many lines means there is more scope for bugs.
But worse, you are essentially using code to store data.
A better choice is to use a Map and look up the String:
private static Map<Byte, String> map = new HashMap<Byte, String>() {{
put(1, "red");
put(2, "green");
etc
}};
then in your method simply
return map.get(color);
In one byte you can store 8 possible combinations.
In my decision I stated that first position (in binary representation of byte) is "blue" color, second - "green" and third - "red". This means if we have 001 - it's blue color. If 101 - its red-blue color and so on.
This is your show() method:
public void show()
{
switch (color & 4){
case 4:
System.out.print("red ");
default:
switch (color & 2){
case 2:
System.out.print("green ");
default:
switch (color & 1){
case 1:
System.out.print("blue");
}
}
}
System.out.println();
}
Calling of method:
new Candy(1, (byte)7, 10d).show(); //prints "red green blue"

Categories