I do not why eclipse markes the switch-case statement with red squiggle, an says Syntax error on token "{", SwitchLabels expected after this token I tried both of the below posted code and i receive the same complain.
Code_1
switch (Test.h1.size()) {
int size = Test.h1.size();
case 1:
break;
case 2:
break;
}
Code_2
switch (Test.h1.size()) {
int size = Test.h1.size();
case size == 1:
break;
case size == 2:
for (int i=1; i<=Test.h1.size()-1; i++) {
for (int j=i+1; j<=Test.h1.size(); j++) {
System.out.println( Test.h1.get(i)+"+"+Test.h1.get(j)+"= "+((Test.h1.get(i))+(Test.h1.get(j))) );
}
}
break;
}
All your code needs to be in cases. Did you read the docs? http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Try this:
int size = Test.h1.size();
switch (size) {
case 1:
break;
case 2:
....;
}
To solve your problem in code 1 you only have to remove the line int size = Test.h1.size();.
For code 2 you should know, that in Java you cannot use boolean expressions in switch cases.
Related
How can I call a method or a variable in switch statement from another case
for example :
case 0:
//I have a FOR loop in here to store int values in an ARRAY
case 1:
// here I want to print the values of the ARRAY from case 0
FYI:
the variables used in the FOR loop are all STATIC and the "i" variable that checks the length of the ARRAY is static too.
2- myRandomArray is not Static (I know it's an Object lol)
case 0:
for(i = 0 ; i < myRandomArray.length ; i++)
{
myRandomArray[i] = myRandomObj.nextInt(MAXINT);
}
break;
case 1:
System.out.print(myRandomArray[i] + " ");
break;
Typically SWITCH allows to execute only one case at time. You can bring your Print block inside case 0 for loop itself.
case 0:
for(i = 0 ; i < myRandomArray.length ; i++)
{
myRandomArray[i] = myRandomObj.nextInt(MAXINT);
System.out.print(myRandomArray[i] + " ");
}
break;
case 1:
......
break;
Why don't you just create a function and call it ?
case 0:
for(i = 0 ; i < myRandomArray.length ; i++)
{
myRandomArray[i] = myRandomObj.nextInt(MAXINT);
Print(i);
}
break;
case 1:
Print(i - 1);
break;
.
.
.
}
private static void Print(int index){
System.out.print(myRandomArray[index] + " ");
}
I created a code to generate a random credit card number and I'm using this method to return a credit card number based in the user input. For some reason I am having a problem returning a value. Help please.
public String getIssuerCode(String issuerSymbol) {
String creditCardNumber = null;
for (int i = 0; i < 15; i++) {
switch (issuerSymbol) {
case ISSUER_MASTER_CARD:
creditCardNumber = generateMasterCard();
break;
case ISSUER_AMER_EXPRESS:
creditCardNumber = generateAmericanExpress();
break;
case ISSUER_VISA:
creditCardNumber = generateVisa();
break;
// System.out.println("error");
default:
break;
}
}
return creditCardNumber;
}
You have a couple of things going on here.
First and foremost, you have a simple typo in your code, as #brycem in his answer already told you. Secondly, it is possible that, after the for-loop and switch statements, creditCardNumber hasn't been initialized. This means that no value has been assigned to it. Now this may be impossible to happen, but your compiler doesn't know that. Thus, a simple fix is to assign it to null in the beginning:
public String getIssuerCode(String issuerSymbol) {
String creditCardNumber = null;
for (int i = 0; i < 15; i++) {
switch (issuerSymbol) {
case ISSUER_MASTER_CARD :
creditCardNumber = generateMasterCard();
break;
case ISSUER_AMER_EXPRESS :
creditCardNumber = generateAmericanExpress();
break;
case ISSUER_VISA:
creditCardNumber = generateVisa();
break;
default:
break;
}
}
return creditCardNumber;
}
Edit:
From your comment below I drew the conclusion that the class that has this method also has the issuerNumber. In this case, you should definitely do this:
public String getIssuerCode() {
String creditCardNumber = null;
for (int i = 0; i < 15; i++) {
switch (this.getIssuerSymbol()) {
case ISSUER_MASTER_CARD :
creditCardNumber = generateMasterCard();
break;
case ISSUER_AMER_EXPRESS :
creditCardNumber = generateAmericanExpress();
break;
case ISSUER_VISA:
creditCardNumber = generateVisa();
break;
default:
break;
}
}
return creditCardNumber;
}
The problem in your case is that there is one path in your program that might return an uninitialized String. If "issuerSymbol" is none of the three cases, you will fall in your "default case", which don't initialize your creditCardNumber variable.
The solution is to give a default value to the variable creditCardNumber at line 2:
public String getIssuerCode(String issuerSymbol) {
String creditCardNumber = null;
...
}
OR update your default case
switch (issuerSymbol) {
case ISSUER_MASTER_CARD :
creditCradNumber = generateMasterCard();
break;
case ISSUER_AMER_EXPRESS :
creditCardNumber = generateAmericanExpress();
break;
case ISSUER_VISA:
creditCardNumber = generateVisa();
break;
default:
creditCardNumber = "000-000-000";
break;
}
Feel free to put any value as the default value. Personnally "null" is a good candidate as it shows immediately that something wrong happened, but it might make you crash later on if don't handle it correctly. Therefore a safer choice could be any String value, like "000-000-000".
Yeah, well. In case you didn't notice by now, you simply mispelled "card" and wrote "crad".
Concretely, you created a variable String creditCradNumber; <- Notice the "Crad" instead of "Card".
But you spelled it differently in the return statement return creditCardNumber; <- NOW it's Card.
That's most likely your problem. Take another look at your code now and be sure to check your variable's name spelling now so it remains the same every time you want to use it. :)
Cheers.
Edit: As shown in other answers, your code ALSO has the problem of not initializing the String creditCardNumber if none of the cases are met on your switch. Initializing it to null:
String creditCardNumber = null;
or using a default case on your switch:
default:
creditCardNumber="000-000-000";
break;
may solve the problem.
Okay, just to debug your "null", you should try to add more debug lines:
public String getIssuerCode(String issuerSymbol) {
String creditCardNumber = null;
System.out.println(issuerSymbol);
switch (issuerSymbol) {
case ISSUER_MASTER_CARD:
System.out.println("Card was of type: " + ISSUER_MASTER_CARD);
creditCardNumber = generateMasterCard();
break;
case ISSUER_AMER_EXPRESS:
System.out.println("Card was of type: " + ISSUER_AMER_EXPRESS);
creditCardNumber = generateAmericanExpress();
break;
case ISSUER_VISA:
System.out.println("Card was of type: " + ISSUER_VISA);
creditCardNumber = generateVisa();
break;
default:
System.out.println("Card is NOT one of the expected type!");
break;
}
}
System.out.println("Generated credit card number is : " + creditCardNumber);
return creditCardNumber;
}
If you have "null", then you must see "Card is NOT one of the expected type!". If not, this means that there is a problem in your function generatedAmericanExpress() and this is what returns null.
You've used a variable named "creditCradNumber" when setting in several instances rather than "creditCardNumber".
I was wondering if anyone can see what is wrong with my code. It works except that the program is not acknowledging my switch statement - I searched lots of questions but as I am a novice I am clearly missing something.
import java.util.Scanner;
class Calmlr1 {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String anotherOption = "y", operatorOpt= "a";
int no1=0, no2=0;
double result= 0;
System.out.println ("Welcome to the online calculator! Let's begin...");
while (anotherOption.equalsIgnoreCase ("y")) {
System.out.println ("Please enter your 1st number: ");
no1 = input.nextInt();
System.out.println ("Please confirm your operator:\n1 = +\n2 = - \n3 = *\n4 = /");
operatorOpt = input.next ();
System.out.println ("Please enter your 2nd number: ");
no2 = input.nextInt();
switch(no1) {
case 1:
result=no1+no2;
break;
case 2:
result=no1-no2;
break;
case 3:
result=no1*no2;
break;
case 4:
result=no1/no2;
default:
result = 0 ;
break;
}
System.out.println("Your total calculation is: "+result);
System.out.println("Would you like to do another sum? y/n ");
anotherOption=input.next();
}
}
}
You should be using switch(operatorOpt). Right now you are switching on the first number.
You also need to change:
int operatorOpt= 0;
operatorOpt = input.nextInt();
That is, if you want to keep your switch statement the same. Please also see #Daniel Imms answer for an additional bug fix.
Try adding a break at the end of case 4
case 4:
result=no1/no2;
break;
EDIT J L's answer is the main issue, but this is another problem that will break division.
Your switch should be on the operatorOpt and not on no1.
Also, you're missing a break in the case 4. So, if you want to do a division, you'll get 0 as result.
The input from the user for operatorOpt should be done with input.nextLine(). Or, if you want to keep the same switch statement, with input.nextInt().
It should be like this:
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}
Your switch statement should be on "operatorOpt" and not on "no1" as you suppose to check the operator and based on that you want to do the calculation. However, you must use JDK1.7 to use String in Switch statement since previous versions of JDK do not support String Switch.
Also, you should use "break" in case 4.
Your switch should be on the operatorOpt and not on no1.
You can use like this
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}
I was doing my homework (Generate Roman Numerals from numerical input from 1-10), and in doing so, I made a switch statement. My question is how do I return to the top of a switch statement if none of the input is selected in a case? There was nothing about it in our textbook nor could I find anything in the java documentation. Is this just something that cannot happen?
Personally I prefer the while loop to do this:
just to explain the basic idea: you initialize a boolean that will be the criteria whether the loop has to be repeated, you start the while loop and put the boolean at false because in most cases you only want to run it once, you start the switch and for all cases where you want to repeat the loop you put the boolean again equal to true.
boolean again= true;
while (again){
again= false;
switch(number){
case 1:
break;
case 2:
break;
default: again=true;
break;
}
}
you can break from in case or can write return statement if it is method.
public int method(int i){
int j=0;
switch(i){
case 1: ... return j;
....
}
}
Here is how to do it but I highly recommend you to restructure your code to avoid doing it.
public class Main {
public static void main(String[] args) {
int i = 0;
loop: for (;;) {
switch (i) {
case 1: System.out.println(i);
break loop;
case 2: // more stuff
break loop;
default:
System.out.println(i);
i = 1;
break;
}
}
}
}
public class Main {
public static void main(String[] args) {
int i=3;
switch (i) {
default:
i=1;
case 1:
System.out.println(i);
break;
case 2:
break;
}
}
}
How can I add conditions into a switch statement?(ex:-Displaying the grade for the average marks)
I recommend using if-else... switch statements can only compare on equality.
With an integer score, you COULD do something like...
switch (score)
{
case 100:
case 99:
case 98:
case 97:
case 96:
case 95:
case 94:
case 93:
case 92:
case 91:
case 90:
grade = 'A';
break;
case 89:
/* ... */
}
See the problem? :-)
You can't. Use an if-else-if-else.
Here is how I use less than greater than in a switch statement. The following is in actionscript 3...
var unknown1:Number = 8;
var unknown2:Number = 2;
var lowerBoundary = 1;
var upperBoundary = 5
switch(true){
case (unknown2 < lowerBoundary || unknown2 > upperBoundary):
trace("value is out of bounds");
break;
case (unknown2 > lowerBoundary && unknown2 < upperBoundary):
trace("value is between bounds");
break;
default:
trace("Out of Luck");
break;
}
Output...
value is between bounds
This question is listed with a Java tag so...
Generic switch statement:
// ... within class scope
private final int CONSTANT_1 = 1;
private final int CONSTANT_2 = 2;
private final int CONSTANT_3 = 3;
// ...
public void doStuff(MyObject myObject){
int variable = myObject.getIntValue();
switch(variable){
case CONSTANT_1:
System.out.println(variable + " is equal to " + CONSTANT_1);
// use a break statement to tell the switch to stop here
// or else it will execute all subsequent cases:
break;
case CONSTANT_2:
System.out.println(variable + " is equal to " + CONSTANT_2);
// what happens if I leave out the break?
case CONSTANT_3:
System.out.println(variable + " is equal to " + CONSTANT_2);
break;
default:
System.out.println(variable + " wasn't equal to anything!");
}
Let's say I run through this 3 times and "myObject.getIntValue()" returns these values in this order; 3, 1, 2, and finally 42. Then the following output would be generated:
First time through using the value '3'...
3 is equal to 3
Second time through using the value '1'...
1 is equal to 1
Third time through using the value '2'...
2 is equal to 2
2 is equal to 3
Fourth time through using the value '42' ...
42 wasn't equal to anything!
Notice the third run has two lines (and one incorrect one) because I left out the break keyword for the second case.
Now in Java 1.5 and up, you can also switch on the Enum type:
public void doStuff(MyObject myObject){
MyEnumType varType = myObject.getEnum();
switch(varType){
case MyTypeOne:
// everything else is the same -- nothing special here.
// put whatever code you want in.
break;
case MyTypeTwo:
// everything else is the same -- nothing special here.
// put whatever code you want in.
break;
case MyTypeThree:
// everything else is the same -- nothing special here.
// put whatever code you want in.
break;
default:
// code for unknown case goes here
}
}
Depending on what your ranges are you can use a formula.
e.g.
switch(score/10) {
case 10: case 9: case 8: return 'A';
case 7: return 'B';
case 6: return 'C';
case 5: return 'D';
default: return 'U';
}
In this example, does the code generate a random number and do something if it's that number or that number.
int num; //Just declares a variable
Random r = new Random(); //This makes an object that generates random numbers.
num = r.nextInt(2); //This "Choose" the random number. The possible numbers are 0 and 1. and the sets the the num variable to the number.
switch(num){
case 0: //This says if the number is 0 then do this.
//put code here.
break;
case 1: //This says if the number is 1 then do this.
//put code here
break;
}
And this is a switch statement that do different things based on the number that randomly gets chosen.