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);
}
}
Related
I am using Android studio for my highest card wins Game. I have three java classes called Cards, Deck, Gamelogic. everything is going good so far but I am just having a little trouble starting a function for my comparing cards method. This is what I have so far ...
import android.graphics.Color;
/**
* Created by azib2 on 12/1/2016.
*/
enum Suite {
Heart, diamond, spades, clubs;
public String toString()
{
switch (this) {
case Heart:
return "Heart";
case diamond:
return "diamond";
case spades:
return "spades";
case clubs:
return "clubs";
default:
return "Wrong type";
}
}
public String symbol(){
switch (this) {
case Heart:
return "\u2764";
case diamond:
return "\u2666";
case spades:
return "\u2660";
case clubs:
return "\u2663";
default:
return "Wrong type";
}
}
public int colors() {
switch (this) {
case Heart:
case diamond:
return Color.RED;
case spades:
case clubs:
return Color.BLACK;
}
return 0;
}
}
public class Cards {
private int cardnum;
private Suite suitetype;
public Cards(int cardnum, Suite suitetype){
this.cardnum = cardnum;
this.suitetype = suitetype;
}
public String CardType(int num){
switch(num){
case 1: return "A";
case 2: return "2";
case 3 : return"3";
case 4: return "4";
case 5: return "5";
case 6: return "6";
case 7: return "7";
case 8: return "8";
case 9: return "9";
case 10: return "10";
case 11: return "J";
case 12: return "Q";
case 13: return "K";
default: return " error invaild ";
}
}
public void CompareCards(){
}
public int Getcardnum (){
return cardnum;
}
public Suite getsuite(){
return suitetype;
}
}
What should I do to compare cards?
First, I recommend "Cards" be "Card". But I'll stick with "Cards" here.
This seems like a good use-case for Comparable interface:
public class Cards implements Comparable<Cards> {
// Ace lowest:
public int compareTo(Card other) {
return Integer.compare(cardnum, other.cardnum);
}
}
Then to see if one card is higher than another:
if(card.compareTo(otherCard) > 0) { ... }
With this approach, you could even sort a list of cards using:
List<Cards> cards = new ArrayList<Cards>();
// Add all cards desired
Collections.sort(cards);
If you want stable sorting (by both value and suit):
public class Cards implements Comparable<Cards> {
// Ace lowest:
public int compareTo(Card other) {
// Compare by value first
int diff = Integer.compare(cardnum, other.cardnum);
if(diff != 0) return diff;
// Compare by suit
return suitetype.compareTo(other.suitetype);
}
}
I have been scouring the internet for answers to my problem. I have found some good advice and have changed my original code, but I am yet to discover the answer to my initial problem.
I am trying to take string data from a series of Jtextfields and writing them to an arraylist, and then in turn taking the written data from the arraylist and transfering it to the same text fields.
public class Form extends javax.swing.JFrame {
public ArrayList<Personal> personalList;
public ArrayList<Business> businessList;
public ArrayList<Personal> displayPersonalList;
public ArrayList<Business> displayBusinessList;
public Form() {
initArrayLists();
}
private void initArrayLists(){
personalList = new ArrayList<Personal>();
businessList = new ArrayList<Business>();
displayPersonalList = new ArrayList<Personal>();
displayBusinessList = new ArrayList<Business>();
}
this is my submit button that writes to the arraylists.
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt)
{
if (contactTypeLabel.getText().equals("Personal Contact")){
Personal p = new Personal();
p.first = firstNameTF.getText();
p.last = lastNameTF.getText();
p.address = addressTF.getText();
p.s = stateTF.getText();
p.zip = zipTF.getText();
p.phone = phoneTF.getText();
p.email = emailTF.getText();
personalList.add(p);
Personal d = new Personal();
d.first = firstNameTF.getText();
displayPersonalList.add(p);
resetTextFields();
}else if (contactTypeLabel.getText().equals("Business Contact")){
Business b = new Business();
b.first = firstNameTF.getText();
b.last = lastNameTF.getText();
b.address = addressTF.getText();
b.s = stateTF.getText();
b.zip = zipTF.getText();
b.phone = phoneTF.getText();
b.email = emailTF.getText();
businessList.add(b);
Business d = new Business();
d.first = firstNameTF.getText();
displayBusinessList.add(d);
resetTextFields();
}
}
here is the code to change to display mode, with a combobox that should populate for accessing the arraylist to fill the textfields with selected data
private void displayPersonalButtonActionPerformed(java.awt.event.ActionEvent evt)
{
personalFieldViewer();
submitButton.setVisible(false);
displayComboBox.setVisible(true);
clearTextFields();
for (Object item : displayPersonalList) {
displayComboBox.addItem(item);
}
}
this is the code for the combobox action and code to fill the text fields
private void displayComboBoxActionPerformed(java.awt.event.ActionEvent evt)
{
int x;
switch (displayComboBox.getSelectedIndex()){
case 0:
for (x = 0; x < x + 8; x ++) {
switch (x){
case 0 :firstNameTF.setText(personalList.get(x).toString());
break;
case 1 :lastNameTF.setText(personalList.get(x).toString());
break;
case 2 :addressTF.setText(personalList.get(x).toString());
break;
case 3 :stateTF.setText(personalList.get(x).toString());
break;
case 4 :zipTF.setText(personalList.get(x).toString());
break;
case 5 :phoneTF.setText(personalList.get(x).toString());
break;
case 6 :dobTF.setText(personalList.get(x).toString());
break;
case 7 :emailTF.setText(personalList.get(x).toString());
break;
}
}
break;
case 1:
for (x = 8; x < x + 8; x ++) {
switch (x){
case 8 :firstNameTF.setText(personalList.get(x).toString());
break;
case 9 :lastNameTF.setText(personalList.get(x).toString());
break;
case 10 :addressTF.setText(personalList.get(x).toString());
break;
case 11 :stateTF.setText(personalList.get(x).toString());
break;
case 12 :zipTF.setText(personalList.get(x).toString());
break;
case 13 :phoneTF.setText(personalList.get(x).toString());
break;
case 14 :dobTF.setText(personalList.get(x).toString());
break;
case 15 :emailTF.setText(personalList.get(x).toString());
break;
}
}
break;
case 2:
for (x = 16; x < x + 8; x ++) {
switch (x){
case 16 :firstNameTF.setText(personalList.get(x).toString());
break;
case 17 :lastNameTF.setText(personalList.get(x).toString());
break;
case 18 :addressTF.setText(personalList.get(x).toString());
break;
case 19 :stateTF.setText(personalList.get(x).toString());
break;
case 20 :zipTF.setText(personalList.get(x).toString());
break;
case 21 :phoneTF.setText(personalList.get(x).toString());
break;
case 22 :dobTF.setText(personalList.get(x).toString());
break;
case 23 :emailTF.setText(personalList.get(x).toString());
break;
}
}
break;
}
}
here are the classes that hold the variables for the arraylists.
public class Contacts {
public String first, last, address, s, zip, phone, email;
}
public class Personal extends Contacts{
public String dob;
}
public class Business extends Contacts{
public String title, organization;
}
when I alternately try to fill the arraylists with *.add(textfield.getText()); Java will not allow this as well as using variables first=firstNameTF.getText(); then *.add(first); I get the same error message...
Please try to refrain from being negative, and I have read the API regarding arraylists. Thank you.
Your arraylist declarations has type either Personal or Business. So these list cant add a string value. So when you say personalList.add(textfield.getText()); its actually trying to add String object to a list that can contain only Personal object.
Secondly the for loop inside displayComboBoxActionPerformed() method results in an infinite loop. for (x = 0; x < x + 8; x ++). Insted of having different for loops and switch statements you could do something like
private void displayComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
if(displayComboBox.getSelectedIndex() > -1){
int start = displayComboBox.getSelectedIndex() * 8;
for (int x = start; x < start + 8; x ++) {
firstNameTF.setText(personalList.get(x).toString());
}
}
}
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 there a way to use relational operators (<,<=,>,>=) in a switch statement?
int score = 95;
switch(score) {
case (score >= 90):
// do stuff
}
the above example (obviously) doesn't work
No you can not.
From jls-14.11
The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.
Relational operators (<,<=,>,>=) results in boolean and which is not allowded.
All of the following must be true, or a compile-time error occurs:
Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.
No two of the case constant expressions associated with a switch statement may have the same value.
No switch label is null.
At most one default label may be associated with the same switch statement.
This might help you if you need to do it with switch itself,
char g ='X';
int marks = 65;
switch(marks/10)
{
case 1:
case 2:
case 3:
case 4: g = 'F';
break;
case 5: g = 'E';
break;
case 6: g = 'D';
break;
case 7: g = 'C';
break;
case 8: g = 'B';
break;
case 9:
case 10: g = 'A';
break;
}
System.out.println(g);
It works this way,
if(marks<50)
g='F';
else if(marks<60)
g='E';
else if(marks<70)
g='D';
else if(marks<80)
g='C';
else if(marks<90)
g='B';
else if(marks<=100)
g='A';
Unfortunately NO, though you can use case fall (kind of hacky) by grouping multiple case statements without break and implement code when a range ends:
int score = 95;
switch(score) {
..
case 79: System.out.println("value in 70-79 range"); break;
case 80:
..
case 85: System.out.println("value in 80-85 range"); break;
case 90:
case 91:
case 92:
case 93:
case 94:
case 95: System.out.println("value in 90-95 range"); break;
default: break;
}
IMHO, using if would be more appropriate in your particular case.
It will never work. You should understand what switch does in the first place.
It will execute the statements falling under the case which matches the switch argument.
In this case, score is an argument which is 95 but score>=90 will always evaluate to either true or false and never matches an integer.
You should use if statements instead.
Also Java doesn't allow booleans in switch cases so yea.
Simply NO
int score = 95;
switch(score) {
case (score >= 90):
// do stuff
}
You are passing a int value to switch. So the case's must be in int values, where
(score >= 90)
Turns boolean.
Your case is a good candidaate for if else
The docs for switch-case statement state:
a switch statement tests expressions based only on a single integer, enumerated value, or String object.
So there is no boolean. Doing so would make no sence since you only have two values: true or false.
What you could do is write a method which checks the score and then returns a one of the types switch can handle
For example:
enum CheckScore {
SCORE_HIGHER_EQUAL_90,
...
}
public CheckScore checkScore(int score) {
if(score >= 90) {
return SCORE_HIGHER_EQUAL_90;
} else if(...) {
return ...
}
}
and then use it in your switch:
switch(checkScore(score)) {
case SCORE_HIGHER_EQUAL_90:
// do stuff
}
... Or You could just use if, else-if, else directly!
Obviously, this is not possible as a language construct. But, just for fun, we could implement it by ourselves!
public class Switch<T, V> {
public static interface Action<V> {
V run();
}
private final T value;
private boolean runAction = false;
private boolean completed = false;
private Action<V> actionToRun;
public Switch(T value) {
this.value = value;
}
static public <T, V> Switch<T, V> on(T value) {
return new Switch<T, V>(value);
}
public Switch<T, V> ifTrue(boolean condition) {
runAction |= condition;
return this;
}
public Switch<T, V> ifEquals(T other) {
return ifTrue(value.equals(other));
}
public Switch<T, V> byDefault(Action<V> action) {
this.actionToRun = action;
return this;
}
public Switch<T, V> then(Action<V> action) {
if (runAction && !completed) {
actionToRun = action;
completed = true;
}
return this;
}
public V getResult() {
if (actionToRun == null) {
throw new IllegalStateException("none of conditions matched and no default action was provided");
}
return actionToRun.run();
}
}
Switch accepts any value to switch on and then provides functionality to match over boolean conditions (ifTrue method) or by exact matches (ifEquals method). Providing a value to switch on is needed just for the latter feature.
After building the conditions, user invokes getResult to obtain the result.
For example, we could create a method that tells us what it thinks about our score:
String tellMeMyScore(int score) {
return Switch.<Integer, String> on(score).byDefault(new Action<String>() {
public String run() {
return "really poor score";
}
}).ifTrue(score > 95).then(new Action<String>() {
public String run() {
return "you rock!";
}
}).ifTrue(score > 65).then(new Action<String>() {
public String run() {
return "not bad, not bad";
}
}).ifEquals(42).then(new Action<String>() {
public String run() {
return "that's the answer!";
}
}).getResult();
}
This simple test:
for (int score : new int[] { 97, 85, 66, 55, 42, 32, 4 }) {
System.out.println(score + ": " + tellMeMyScore(score));
}
Prints out:
97: you rock!
85: not bad, not bad
66: not bad, not bad
55: really poor score
42: that's the answer!
32: really poor score
4: really poor score
Right now I am doing the classic shape program involving shape classes. I can do the create circle or rectangle object without any problem. But when I get perimeter or area of all the objects, it turns out all the objects are null. Here is the code:
//Case menu selection actions
Here it the instance variables and arrays
private int menu_select;
private int i=0;
private Shape[] s = new Shape[10];
Here is the menu options
public static void display_menu()
{
System.out.print("Choose an option:\n"+
"1-Add a new circle\n"+
"2-Add a new rectangle\n"+
"3-Delete all shapes\n"+
"4-Scale all shapes\n"+
"5-Display perimeter of all shapes\n"+
"6-Display the area of all shapes\n"+
"7-Enter scale factor\n"+
"8-Exit program\n");
}
Here is the the menu code
Here is the switch
//Case menu selection actions
public void select_case()
{
if(i<=10)
{
switch (menu_select)
{
case 1: Circle c = new Circle(1);
s[i]=c;
i++;
break;
case 2: Rectangle r = new Rectangle(1,1);
s[i]=r;
i++;
break;
case 3: s=null;
i=0;
break;
case 4: Scanner input = new Scanner(System.in);
double d = input.nextDouble();
for(int i=0; i<s.length; i++)
{
s[i].setScaleFactor(d);
}
break;
case 5: for(int i=0; i<s.length; i++)
{
if(s[i] != null)
{
System.out.println(s[i].getPerimeter());
}
}
break;
case 6: for(int i=0; i<s.length; i++)
{
System.out.println(s[i].getArea());
}
break;
case 7: //Enter scale factor
//No need for a case 8 since while loop terminates it.
default: System.out.println("Number must be 1-8");
}
}
}
Here is the main method
public static void main(String args[])
{
Menu m;
do
{
Menu.display_menu();
m = new Menu(0);
}
while(m.getMenu_Select() != 8);
}
}
I have tried giving the shape array indice a fixed number and I still get a null object. I have also tried removing the for loop with the fixed indice and still get null objects.
You're creating a new Menu object with each iteration of the loop!
{
Menu.display_menu();
m = new Menu(0); // here!
}
Don't do that since any changes done on this object will have no effect or memory on the next object.
Create one Menu object before the loop, and then call methods on it in the loop
Does "i" can equal to 10 in the following code?
The maximum index in array s should be 9
public void select_case()
{
if(i<=10)
{
switch (menu_select)
{