I am writing a program which contains ComboBox where you choose text and this text will be converted to coefficient using switch statment in program. The problem is that I can't use varible outside switch statment. I really appreciate if someone could help.
Code sample:
double Cst1;
String s = Cst.getSelectedItem().toString();
switch (s) {
case "ABC":
Cst1 = -25;
break;
case "CBA":
Cst1 = -10;
break;
case "BCA":
Cst1 = 0;
break;
case "ACB":
Cst1 = 10;
break;
default:
answer.setText("ERROR");
break;
}
double C14 = 9 * Cst1;
If you get an error which says that the variable is not initialized, try this:
double Cst1 = 0.;
If you have a string value that isn't explicitly covered in your switch, Cst1 will never be initialized. For example, the string "AAA" will fall into the default case.
There are two possible fixes:
Initialize Cst1 like
double Cst1 = 0.
Set Cst1 in your default case like
default:
Cst1 = 0.;
// Display your error
break;
Related
I have a java switch function that is:
while(i < 1) {
switch(hi) {
case "Hi":
case "hi":
case "Hi!":
case "hi!":
case "Hello!":
case "hello!":
case "Hello":
case "hello":
System.out.println("Hi!");
break;
case "How are you?":
x = Math.random() * Emotion.length;
Feeling = (int)x;
System.out.println(Emotion[Feeling] + " How are you?");
break;
default:
break;
} Hi.nextLine();
}
There are no errors in debug, but the output is this:
"Me: Hi,
Computer: Hi!,
Me: How are you?,
Computer: Hi!,"
How do I make it so I can use switch loop many times without getting the same result every time?
All help would be appreciated.
The problem is that you assign the hi variable before the loop, and never re-assign it later. You should assign the value of Hi.nextLine(); to hi within the loop as follows:
hi = Hi.nextLine();
Can I use the same number for 2 cases in a switch statement in old versions in Java?
int rand = 3;
switch(rand)
{
case 3: System.out.print("***");
case 3: System.out.print("###");
default: System.out.println("&&&");
}
I am using the Java version 15.0.1 and it is not working.
This will not be possible as switch needs a single option for a particular input. You can either use one option like below.
int rand = 3;
switch(rand)
{
case 3: System.out.print("***");
default: System.out.println("&&&");
}
or concatenate both together like below
int rand = 3;
switch(rand)
{
case 3: System.out.print("***###");
default: System.out.println("&&&");
}
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
}
If we take this code as an example :
switch (PeriodEnum.getEnum(month).getValue()) {
case 0: // Calendar.JANUARY
case 2: // Calendar.MARCH
case 4: // Calendar.MAY
case 6: // Calendar.JULY
case 7: // Calendar.AUGUST
case 9: // Calendar.OCTOBER
case 11: // Calendar.DECEMBER
nbDays = 31;
break;
case 3: // Calendar.APRIL
case 5: // Calendar.JUNE
case 8: // Calendar.SEPTEMBER
case 10: // Calendar.NOVEMBER
nbDays = 30;
break;
What is the difference between the previous code and the code below?
switch (PeriodEnum.getEnum(month).getValue()) {
case 0: // Calendar.JANUARY
nbDays = 30;
break;
case 2: // Calendar.MARCH
nbDays = 30;
break;
case 4: // Calendar.MAY
nbDays = 30;
break;
....
}
As a beginner in java , I would love to understand the difference . The main thing I don't understand is how the IDE will detect the case based on the month and associate it?
Thank you
The simple answer is that the compiler is stupid :)
In the first code snippet, the generated JVM code will happily stuff all cases you bundled together into the same branch, and in the second snippet it would, equally happily, stuff each case into its own branch. And even if a set of branches did exactly the same, the compiler doesn't care and won't do the analysis for you.
Now, there is something else to consider in Java, which is that enums are objects like any other... Which means they can have instance variables. Therefore you can do this, and avoid that switch statement altogether:
public enum Calendar
{
JANUARY(30),
FEBRUARY(28),
// etc etc
;
private final int daysInMonth;
Calendar(final int daysInMonth)
{
this.daysInMonth = daysInMonth;
}
public int getDaysInMonth()
{
return daysInMonth;
}
}
In the first part execution will come out of switch statement after break statement, while in second part the program will continue till the last case.
So for the first part whether the value will be 0, 2, 4.... or whatever the assignment nbdays = 31 will be executed and nbdays = 30 will be executed for 1, 3, 5.... Basically it is a way to minimize writing codes for multiple similar statements.
There is no grouping for switch statements.
Consider this arbitrary example:
switch (PeriodEnum.getEnum(month).getValue()) {
case 0: // Calendar.JANUARY
jan();
case 2: // Calendar.MARCH
mar();
case 4: // Calendar.MAY
may();
case 6: // Calendar.JULY
jul();
case 7: // Calendar.AUGUST
aug();
case 9: // Calendar.OCTOBER
oct();
case 11: // Calendar.DECEMBER
dec();
break;
If the switch value is 0, then jan(), mar(), may(), jul(), aug(), oct(), and dec() ALL execute.
If the switch value is 9, then only oct(), and dec() execute.
See what I mean about it not being grouping?
Just like if, while, and for, switch statements were a way of avoiding goto statements.
We idiomatically use them as a map, or a grouping or whatever, but that's not what they literally are. They are literally: Start where the case matches, then exit at break/continue/return/throw. The process of continuing from one case to the next is called "falling through"
To save some code, wrap your switch in a method and instead of assigning a variable and breaking, just return the value and skip the intermediate variable.
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
}