Does break in a switch-statement terminates a for-loop? - java

I am trying to understand return, break and continue.
I know that break will stop the (inner) for loop. For example:
for (int i = 1; i <= 3; i++) {
// inner loop
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
// using break statement inside the inner loop
break;
}
System.out.println(i + " " + j);
}
}
I know the outer loop will go on.
What I don't understand is this here:
for (int i = 0; i < 3; i++) {
String line = null;
switch (a) {
case 0:
line = "Hello";
break;
case 1:
line = "How are you?";
break;
case 2:
line = "What are you doing?";
break;
So it goes to case 0 and then break and the for-loop continues, why? I thought it will break the loop since it's not nested.
Or is it because of the switch-statement - it's different than if-statements?
And in this case, it will terminate the whole while-loop... I can't see the difference.
while(winner == false){
input = menuInput.nextInt();
try {
if(input == 0 || input >= 9){
System.out.println("Ungültige Nummer, versuche nochmal!");
break;
}

You can break a switch. You can't break an if. break is applied to the closest statement that could be breaked, so
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
// using break statement inside the inner loop
break;
}
System.out.println(i + " " + j);
}
Here break refers to the for.
While here:
for (int i = 0; i < 3; i++) {
String line = null;
switch (a) {
case 0:
line = "Hello";
break;
It refers to the switch.
Statements that can be breaked are for, while, do...while, switch.
For further info, you can see the spec.

The break applies to the inner-most thing which can be break'd (without a label). In this case, it's the switch - because the default switch behavior falls through. First, your code. Change,
for (int i = 0; i < 3; i++) {
String line = null;
switch (a) {
case 0:
line = "Hello";
break;
case 1:
line = "How are you?";
break;
case 2:
line = "What are you doing?";
break;
Could be changed to
loop: for (int i = 0; i < 3; i++) {
String line = null;
switch (a) {
case 0:
line = "Hello";
break loop;
case 1:
line = "How are you?";
break loop;
case 2:
line = "What are you doing?";
break loop;
Now, the second behavior would be fall-through. And that might look something like,
switch (a) {
case 0: case 2: case 4: case 6: case 8:
System.out.println("even < 10");
break;
case 1: case 3: case 5: case 7: case 9:
System.out.println("odd < 10");
break;
}

In switch, statement break means to end switch statement. Take a look at fall trough example.
In the loop, statement break means to end a loop.
Stop looping after using switch statement example:
for (int i = 0; i < 3; i++) {
Boolean shouldBreak = false;
String line = null;
switch (a) {
case 0:
line = "Hello";
shouldBreak = true;
break;
case 1:
line = "How are you?";
shouldBreak = true;
break;
}
if (shouldBreak){
break;
}
}

Related

How to convert If statement to switch statement?

how can I convert this if statement to switch statement by considering that I am using two variables here and I tried to solve it but not working
int child;
char gender;
int temp;
child=console.nextInt();
gender=console.next().charat(0);
if(gender=='m' && children>=4)
temp =1;
else if(gender=='m' && children<4)
temp =2;
else if(gender=='f' && children<4)
temp =3;
else
temp=4;
}
this is my code
int children;
double temp;
char gender;
children=console.nextInt();
switch(children , gender )
{
case < 4, 'm':
temp=1;
break;
default : salary=600;
}
You should start by having a look at The switch Statement
The switch statement is basically evaluating a single condition per case. You can use drop through conditions, but that's a lot of additional code.
For example, something like...
switch (gender) {
case 'm':
temp = 0;
if (children >= 4) {
temp += 1;
} else {
temp += 2;
}
break;
case 'f':
temp = 2;
if (children >= 4) {
temp += 2;
} else {
temp += 1;
}
break;
}
would generate the same results as your if statements
If you preferred to use pure switch statements, you could do something like...
switch (gender) {
case 'm':
temp = 0;
switch (children) {
case 0:
case 1:
case 2:
case 3:
temp += 2;
break;
default:
temp += 1;
}
break;
case 'f':
temp = 2;
switch (children) {
case 0:
case 1:
case 2:
case 3:
temp += 1;
break;
default:
temp += 2;
}
break;
}
Java's switch statement doesn't support ranges :(
switch (gender) {
case 'm':
temp = (children >= 4)? 1:2;
break;
case 'f':
temp = (children >= 4)? 4:3;
break;
default:
temp = 4;
break;
}

Figure out Odd Even or Zero by entering the value

My teacher asked me a question and I was really confused how to write it out as a code. I understood what I had to do, but just couldn't write in Java. So the question was that: Design and implement an application that determines and prints the number of odd even and zero digits. Input could be anything from the user/keyboard. I just don't know how to start. So can someone help me here with an answer and an explanation with that?(without using string)
Thank you so much for your time.
Application? It's three lines:
int odds = str.replaceAll("[^13579]", "").length();
int evens = str.replaceAll("[^2468]", "").length();
int zeroes = str.replaceAll("[^0]", "").length();
If the input is not a string, make it one:
long number;
String str = number + "";
I would use a for loop to traverse the input string. Within the for loop would be a switch statement that increments either the 'odd' variable, the 'even' variable,' the 'zero' variable, or does nothing.
This way the string is only traversed once instead of three times.
The code would look something like:
int numOdds = 0;
int numEvens = 0;
int numZeroes = 0;
for(int i = 0; i < inputString.length(); i++) {
switch(inputString.charAt(i)) {
case '1':
case '3':
case '5':
case '7':
case '9': numOdds++;
break;
case '2':
case '4':
case '6':
case '8': numEvens++;
break;
case '0': numZeroes++;
default: break;
}
}
Looks like you have a couple answers. Here is another you may like more because you probably can understand it:
int odds, evens, zeroes;
public void setOddsEvensZereos(String str) {
for(char c:str) {
try {
int i = Integer.parseInt(c + "");
if(i == 0)
zereos++;
else if(i % 2 == 0)
evens++;
else
odds++;
} catch (Exception e){/*the character isn't a number*/}
}
}

Java - Sharing int values between cases in a switch statment

I'm new to java and not sure how do I share values between cases in a switch statement? When I try to use a variable which i created in the previous case it tells me "variable might not have been initialized"
Code:
case 6:
String stringCopy = stringInput;
String lowerCase = stringCopy.toLowerCase();
int vowelCount = 0;
int stringLength = lowerCase.length();
for (int i = 0; i <= stringLength - 1; ++i){
switch(stringInput.charAt(i)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vowelCount++;
}
System.out.println(vowelCount);
break;
}
case 7:
int noofConstants = 0;
noofConstants = (stringLength - vowelCount);
Declare and initialize value before the switch statement.
int value = 0;
switch (key) {
case 3:
value = 1 + 1;
break;
case 4:
value = 1;
break;
you cannot access a variable that you initialize in a separate code block which is case .
declare it outside/before the code block
int stringLength = 0;
switch(){
case 6:
stringLength = 1;
break;
case 7:
stringLength = 2;
break;
}

Switch statement + user input

Thanks for taking your time to help me. I need this switch statement to only accept ints 1-4. Any others entered will ask for input again. Entering 5 will quit the system.
System.out.println("A random numbers list has been generated for you:\n ");
System.out.println("Choose an option:\n1)Form list to be heapified.\n2)Enqueue the integer 10" +
"\n3)Dequeue the integer 10.\n4)Print the updated heap.\n5)Quit the system \n>>");
Scanner scanner = new Scanner( System.in );
int var = 0;
String input = scanner.next();
int answer = Integer.parseInt(input);
do{
input = scanner.next();
answer = Integer.parseInt(input);
var = answer;
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
}
}while(var ==1 || var==2 || var==3
|| var==4);
I cant seem to get it right. Keep making it worse.
Edited:
do{
String input = scanner.next();
int answer = Integer.parseInt(input);
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
h.pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
h.dequeue();//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default: input = scanner.next();
break;
}
}while(var!=5)
;
Try adding a "default:" statement, like this:
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default:
*Add whatever code you want to execute if its greater then or equal to 5 here!*
}while(var ==1 || var==2 || var==3
|| var==4);
You can set a 'default' case.
default: doSomething();
break;
This will be invoked when a user enters a value that isn't one of your cases.
} while (answer != 5);
This should make the loop break when 5 is entered.
EDIT:
Also, you need to switch on the answer variable instead of 'var'
switch(answer) {
You don't need to put it in a loop. The use case is simple:
For 1-4 : do something and then return
For 5: quit/return Everything
else: ask for input again
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int answer = Integer.parseInt(scanner.next());
switch(answer) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
return; // System.exit(0) or quit however you want to
default:
answer = Integer.parseInt(scanner.next());
}
}

Switch statement for some reason does not like case 8. Compiler is acting real weird

Here is the code:
public static void main(String args[])
{
int i=0;
int m=0;
double scale;
boolean exit;
Shape[] s = new Shape[10];
while(exit !=true)
{
System.out.print("\nChoose 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");
Scanner input = new Scanner(System.in);
m=input.nextInt();
if(i<=9)
{
switch (m)
{
case 1: Circle c = new Circle(0);
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: for(i=0; i<s.length; i++)
{
s[i].scaleShape();
}
break;
case 5: for(i=0; i<s.length; i++)
{
if(s[i] != null)
{
System.out.println(s[i].getPerimeter());
}
}
break;
case 6: for(i=0; i<s.length; i++)
{
if(s[i] != null)
{
System.out.println(s[i].getArea());
}
}
break;
case 7: do
{
System.out.println("\nEnter scale factor");
scale=input.nextDouble();
}
while(scale<0);
Shape.setScaleFactor(scale);
}
break;
case 8: System.out.println("Do you want to quit?");
break; //Nothing here since loop should terminate it.
//default: System.out.println("Number must be 1-8");
// break;
}
}
}
}
Oddly the compiler is giving me an error on case 8 saying:
Type mismatch can't convert from int to boolean.
But Im not converting anything to boolean
-syntax error on token "case" assert expected
-syntax error on token :, ; expected
But all the commands there have semi-colons
expression must return a value
Why is the compiler acting so funny? Normally errors like that are easy to find. What is going on?
Your problem is in the case for 7:
case 7: do
{
System.out.println("\nEnter scale factor");
scale=input.nextDouble();
}
while(scale<0);
Shape.setScaleFactor(scale);
}
Notice the extra close brace: that's closing your switch statement, orphaning your case 8.
} // <-- Why is this here?
break;
case 8: System.out.println("Do you want to quit?");
You're ending the switch statement with an extra }. Remove it and things may work.
Every one has pointed out that you have an extra parenthesis in your code, what we've failed to point out is where it's coming from...
while(scale<0); // <-- This isn't going to work....
Shape.setScaleFactor(scale);
}
It should be...
while(scale<0) {
Shape.setScaleFactor(scale);
}
The next question is, how is scale decremented? Cause this could cause an infinite loop if you're not careful.
while(scale<0);
Shape.setScaleFactor(scale);
} // Remove this parenthesis.
break;

Categories

Resources