I want to activate disabled buttons called tglBtnLevel1, tglBtnLevel2, tglBtnLevel3... from 1 till the integer received with a method.
They only way I achieve it is using switch case, but I guess there must be a way using loops. I have tried a For loop, but I cannot find the way to include the counter (i) in the line "tglBtnLevel(i).setEnabled(true)".
I would thank you any hint or help. This is the beginning of the switch case I use to make it work, but only the first buttons, there are more:
private void checkEnabledLevels(){
switch (d.sendPlayerStats().getWeekTournamentLevel()){
case 1:
tglBtnLevel1.setEnabled(true);
break;
case 2:
tglBtnLevel1.setEnabled(true);
tglBtnLevel2.setEnabled(true);
break;
case 3:
glBtnLevel1.setEnabled(true);
tglBtnLevel2.setEnabled(true);
tglBtnLevel3.setEnabled(true);
break;
case 4:
glBtnLevel1.setEnabled(true);
tglBtnLevel2.setEnabled(true);
tglBtnLevel3.setEnabled(true);
tglBtnLevel4.setEnabled(true);
break;
One way of doing this could be to have all the buttons in an array like this:
Button[] buttonArray = {tglBtnLevel1, tglBtnLevel2, tglBtnLevel3, tglBtnLevel4}
And then simply iterator over them depending upon the tournament level you get:
int tournamentLevel = d.sendPlayerStats().getWeekTournamentLevel()
for (int i = 0; i < tournamentLevel; i++) {
buttonArray[i].setEnabled(true);
}
A slightly different but simple way of doing this could be like:
int tournamentLevel = d.sendPlayerStats().getWeekTournamentLevel()
tglBtnLevel1.setEnabled(tournamentLevel <= 1);
tglBtnLevel2.setEnabled(tournamentLevel <= 2);
tglBtnLevel3.setEnabled(tournamentLevel <= 3);
tglBtnLevel4.setEnabled(tournamentLevel <= 4);
Related
Good Evening,
I created this method for a class. I used a switch/case to execute depending on the value of expression. I included an if-else method for each case. I do get an error on case 1-> switch rules are a preview feature and are disabled by default. I attempted to add a : after case 1 and case 2but my results reached high numbers for the sets. I changed the : to -> and it worked appropriately. Now I am wondering if this was a proper way to set the case statements or should it be written differently.
private void playGame()
{
double winCheck = Math.random();
switch (matchServer) {
case 1 ->{
if (winCheck <= player1WinProb)
player1GamesWon++;
else
player2GamesWon++;
matchServer = 2;
}
case 2 ->{
if (winCheck <= player2WinProb)
player2GamesWon++;
else
player1GamesWon++;
matchServer = 1;
A correct switch statement must use ':'
Also, 'break' is missing. This to avoid executing next cases.
You can add 'default' that means that case 1 and case 2 were not presented.
switch (matchServer) {
case 1:
if (winCheck <= player1WinProb)
player1GamesWon++;
else
player2GamesWon++;
matchServer = 2;
break;
case 2:
if (winCheck <= player2WinProb)
player2GamesWon++;
else
player1GamesWon++;
matchServer = 1;
break;
default:
//If it was not 1 or 2
//Printing the values can help
}
Is there a way to grab the resulting number from each iteration of this loop and compare it to the next?
This is a Slot Machine Sim in Java,
I'm trying to find a way to see how many of the results match.
so I thought I would capture the number that is resulted from each round of the For loop and compare it to the previous one.
but I have no idea how to write that?
is there a better way to do this?
what I have so far:
for (int count=1; count<= 3 ; ++count)
{
number = slotM.nextInt(6);
switch (number)
{
case 0:
System.out.print("-cherries-");
break;
case 1:
System.out.print("-Oranges-");
break;
case 2:
System.out.print("-Palms-");
break;
case 3:
System.out.print("-Bells-");
break;
case 4:
System.out.print("-Melones-");
break;
default:
System.out.print("-Bars-");
break;
}
System.out.print(number);
}
Yep there are several better ways. If you have a fixed number of options (6 in your case) an enum might be a good option:
enum Picture {
CHERRIES, ORANGES, PALMS, BELLS, MELONS, BARS;
public String getName() {
return "-" + name().substring(0, 1) + name().substring(1).toLowerCase() + "-";
}
That way you can store your numbers as pictures rather than numbers.
Picture pictures[3];
Random random = new Random();
for (int i = 0; i < pictures.length; i++)
picture[i] = Picture.values[random.nextInt(pictures.length)];
To get the printed version:
for (Picture picture: picture)
System.out.print(picture.getName());
You’ll need some kind of storage outside of the loop so that each iteration can reference it.
int[] results Look in to arrays - you can put the results of each round into a part of the array, and look up the value.
You are declaring your count variable in the for loop, just declare outside and make a comparison with it
I try to create a Java program with GUI and I want one button to generate random numbers and other buttons just do some operations on those random numbers. Currently the size of random number are fixed but in the future the size will be determined by user input. So I decide to use switch-case. It looks like each case has own scope. If I create an array in case 1. I can not reach the array in case 2. I wonder if there are other solutions except creating a globe array. Thanks for the time.
int [] data = new int[100];
switch (index){
case "1":
//create array full fill with random number
for (int i = 0; i< 100; i++){
data[i] = (int)(Math.random()*(10*100));
}
break;
case "2":
//sort the array
sort.(data);
break;
default:
System.exit(0);
}
as you described,the array must exist during two operations, push one button and push another one,which means you have to store the array. Apart from store it in a global array, u can persist it in your files or dbs.
You'll need static int[] data = null;, or create it outside loop. So your switch statement always has access to data array.
switch (index){
case "1":
//create array full fill with random number
int size = 100;
data = new int[size];
for (int i = 0; i< size; i++){
data[i] = (int)(Math.random()*(10*100));
}
break;
case "2":
//sort the array
if(data != null)
sort.(data);
break;
default:
System.exit(0);
}
Additionally, on else conditions of if(data != null) you may want to inform user of You must create array first!.
I have a 9 names that I need to display in a rotation sequence. Like the image:
rotation schedule
As you can see, the names go one position down in the list, with the 9th name taking top of it at each rotation.
The variable that controls the rotation is the integer iName. Theres a method that just reads an user input (an imagebutton touch) and adds or decreases the value of iName. It starts at 0 (list is displayed Adams to Ida), and when the user gives the command it assumes 1 (so the list is displayed from Ida to Henry).
Actually, the user can go back in time and turn iName from 5 to 4, so the list changes from Easy-Denver, to Frank-Easy.
I have 9 TextViews doing this job, and it's updated inside a loop, as follows:
int[] arrNames_Ids = {R.id.Name1, R.id.Name2, R.id.Name3, R.id.Name4, R.id.Name5, R.id.Name6, R.id.Name7, R.id.Name8, R.id.Name9};
String[] arrPeople = new String {"Adams","Boston","Chicago","Denver","Easy","Frank","George","Henry","Ida"}
String sAlternative_Name = "";
for (iCounter = 0; iCounter < 9; iCounter++){
// iName is a global variable, stars at 0, but it changes upon user request:
sName = arrPeople[iName];
// this "if" statement is the problematic piece of code.......
if (((iCounter == 1)||(iCounter == 3)||(iCounter == 5))&& (sName.equals("Adams")){
sAlternative_Name = mtAlternative_Name();
sName = sAlternative_Name;
} else {
if ((sAlternative_Name != "") && (sName.equals(sAlternative_Name))){
sName = "Adams";
}
}
// without the previous "if" the following part works properly, so the list rotates accordingly;
tvNames = (TextView) getView().findViewById(arrNames_Ids[iCounter]);
tvNames.setText(sName);
iName = iName + 1;
if (iName > 8){
iName = 0;
}
}
public String mtAlternative_Name(){
int iCycle;
String sName_Aux = "";
// iCurrent_Cycle is a global variable, assumes values from 0 to 73, and it controls the order in which arrPeople is supposed to be shown:
iCycle = iCurrent_Cycle % 18;
switch (iCycle){
case 1: sName_aux = "George"; break;
case 3: sName_aux = "Easy"; break;
case 5: sName_aux = "Chicago"; break;
case 10: sName_aux = "Henry"; break;
case 12: sName_aux = "Frank"; break;
case 14: sName_aux = "Denver"; break;
}
return sName_Aux;
}
The idea is to prevent "Adams" from occupying the positions 1, 3 and 5.
Everytime he's in those positions someone else (sAlternative_Name) takes the place, and "Adams" goes to the position that person was supposed to take.
The array arrPeople doesn't change, example:
If "Adams" was supposed to be in position 4, "Easy" takes the place and "Adams" goes to position 8.
But when the list rotates agains (going foward), "Adams" takes position 5 and "Easy" takes position 9.
I'm new to Java and don't have much experience in programming either, but I can't see what's wrong with this code...
The % operator I use it's to make the names in green to take place in "Adams" position. As you can see, "Boston" and "Ida" are not in the game... but were supposed to be......... this is ok, and I'll manage to think something later, but right now I'd wish I could understand why my code isn't working...
Thanks a lot...
The logic I used is that created a 2 dimensional array that held the entire round table (Without Adams being removed from positions 1,3 or 5). Then, another nested loop is run to substitute "Adams" in each row with "Chicago". Finally, the 2 dimensional array is printed. This gives you the output.
(I took Chicago as the alternate name instead of Easy because at times, Easy can also be at position 1,3 or 5 with respect to Adam's position so the interchange would still cause the exception to persist.)
String[] arrPeople={"Adams","Boston","Chicago","Denver","Easy","Frank","George","Henry","Ida"};
String[][] roundtable=new String[9][9];
int i,j,p;
for(i=0;i<9;i++){
p=i;
for(j=0;j<9;j++){
roundtable[i][j]=arrPeople[p++];
if(p==9)
p=0;
}
}
for(i=0;i<9;i++){
for(j=0;j<5;j+=2){
if(roundtable[i][j].equals("Adams")){
roundtable[i][j+2]="Adams";
roundtable[i][j]="Chicago";
break;
}
}
}
for(i=0;i<9;i++){
for(j=0;j<9;j++)
System.out.print(roundtable[i][j]+"\t");
System.out.println("\n");
}
I have a chunk of code that needs to determine if a given integer is between a set of other integers. I'd also like to have this in a case statement so as to not have a surplus of if..else statements everywhere. Here's a bit of the code:
switch (copies) {
case copies >= 0 && copies <= 99: copyPrice = 0.30; break;
case copies >= 100 && copies <= 499: copyPrice = 0.28; break;
case copies >= 500 && copies <= 749: copyPrice = 0.27; break;
case copies >= 750 && copies <= 1000: copyPrice = 0.26; break;
case copies > 1000: copies = 0.25; break;
}
where copies is an integer and copyPrice is a double. I get several errors saying that it expects to receive a integer but gets a boolean instead. What is the best (or optimal) way of setting this up? Any help is greatly appreciated!
This line (and similar):
case copies >= 0 && copies <= 99:
Returns a compiler error since it gives a boolean but the compiler expects an int since copy is declared as int.
One way to solve this is using an array with the desired ranks, and have a switch statement for the index found:
public double calculateCopyPrice(int copies) {
int[] range = { 99, 499, 749, 1000 };
double copyPrice = 0;
int index = -1;
for (int i = 0; i < range.length; i++) {
if (range[i] >= copies) {
index = i;
break;
}
}
switch (index) {
case 0: copyPrice = 0.30; break;
case 1: copyPrice = 0.28; break;
case 2: copyPrice = 0.27; break;
case 3: copyPrice = 0.26; break;
default: copyPrice = 0.25; break;
}
//probably more logic here...
return copyPrice;
}
After some tests, I've found a more flexible solution using a TreeMap<Integer, Double> which allows you to have a specie of range (what you're looking for) and ease the search by using TreeMap#ceilingEntry:
//TreeMap to store the "ranges"
TreeMap<Integer, Double> theMap = new TreeMap<Integer, Double>();
//add the data
theMap.put(99, 0.3);
theMap.put(499, 0.28);
theMap.put(749, 0.27);
theMap.put(1000, 0.26);
//the "default" value for max entries
theMap.put(Integer.MAX_VALUE, 0.25);
//testing the solution
Double ex1 = theMap.ceilingEntry(50).getValue();
Double ex2 = theMap.ceilingEntry(500).getValue();
Double ex3 = theMap.ceilingEntry(5000).getValue();
Double ex4 = theMap.ceilingEntry(100).getValue();
System.out.println(ex1);
System.out.println(ex2);
System.out.println(ex3);
System.out.println(ex4);
java has no native concept of "ranges", let alone support for them in case statements.
usually, when faced with this kind of logic i personally would do one of 2 things:
just have a chain of if-else statements. doesnt even habe to be a chain:
public static double calculateCopyPrice(int copies) {
if (copies > 1000) return 0.25;
if (copies >= 750) return 0.26;
//etc
}
this code has no "else" branches and is just as much typing as the switch syntax you'd like. possibly even less (i only check a single bound every time)
you could use an enum, say:
public enum Division {UNDER_100, 100_to_500, ... }
and then :
Division division = categorize(copies);
switch (division) {
case UNDER_100:
//etc
}
but this is serious overkill for what youre trying to do. i'd use that if this division is also useful elsewhere in your code.
Switch case function must have an exact number in case. For example:
case 0:
case 1:
You're trying to use case from some value to some value and it's not implemented that way in Java. For your problem, you must use if-else statement since it's impossible to do it with switch case. Hope it helped.
Look the problem is very basic..
In a switch statement it allows only the following datatypes and wrapper classes
Byte,short,char,int,Byte,Short,Character,Integer,enum,String..
If you are passing anything other than that will give you an error.
In your case the condition which you are evaluating will give you result which is a Boolean value.
NavigableMap.seilingEntry() may be a good solution in many cases,
but in other cases the following may be clearer:
double getPrice(int copies){
return copies>1000 ? 0.25
: copies>750 ? 0.26
: copies>500 ? 0.27
: copies>100 ? 0.28
: copies>0 ? 0.30
: 0; // or check this condition first, throwing an exception
}