Switch java for loop

Java switch case statement with 4 examples and code

In Java programming language, the switch is a decision-making statement that evaluates its expression.

This is how the switch statement in Java works:

  • The switch block, which is the body of switch statement may contain one or more case labeled statements.
  • It may also contain a default label.
  • After evaluating the expression, the statements in the matched case are executed.
  • You may use different data types in switch Java statement. It may work with primitive data types including int, char, byte and short.
  • The switch statement also works with the String class of Java, enumerated types, and a few special classes.
  • Each case contains a break statement. The break statement is necessary to exit the switch statement (see explanation in the first example).

See the following section for structure and examples of using the switch case statement. After that, I will explain the difference between the if and switch statement and which one to use depending on the scenario.

Structure of switch case statement in Java

The general way of using the switch case is:

switch (expression)

case 1 :

// Java statement here if case 1 is evaluated as true

break; // It will terminate the switch statement

case 2 :

// Java statement here if case 2 is evaluated as true

brerak;

default: // It will execute if none of the case is true

// Java statement here

>

An example of using switch case and default statements

In this example, the switch statement is used with seven cases. A variable is assigned a value (number of the day in Week) which is used as an expression in the switch statement. After that, seven case statements are used; one for each day of the Week. For example, if the value of numDay variable is 1, the output will be Monday and for the value of 7, it should be Sunday. If any other value than 1 to 7 is assigned, the default case will execute:

The Java code for switch example:

Источник

Java for loop switch case java

Solution: You can try infinite loop where you can break it from switch block as shown below: Sample code : Hint: increment a counter for a valid input and break the loop if 5 is chosen after accepting all valid inputs move the code for accepting the user input in the loop at the beginning. Having 13 switch cases of if-else statements can be hard to read, so it would be nice to extract method to handle each or Second approach (a little bit too complex maybe, but still): Create a map of actions: Now you can check if your action map holds desired controlName:

Loop a Switch case

I’m attempting to write code for a user menu. Put simply the user is given a menu of 5 options to input exam scores. Each option runs a method from a class. Once the method is done it will prompt the menu once more, and continue to loop until the user selects option 5, which will terminate the program. Though I am not sure how I can get this switch case to loop.

 prof1.menu(); choice = console.nextInt(); do < switch(choice) < case 1: prof1.inputExamScore(); break; case 2: prof1.modifyExam(); break; case 3: prof1.displayExamScores(); break; case 4: case 5: default: System.out.println("That is not a valid input."); >>while (choice < 1 || choice >4); 

You can try infinite loop where you can break it from switch block as shown below:

  • increment a counter for a valid input and break the loop if 5 is chosen after accepting all valid inputs
  • move the code for accepting the user input in the loop at the beginning.

Loops — Looping switch case in java, Sorted by: 1. Assuming you only want the loop to go back if the default case is executed, you can do it in different ways. Using a label. LOOP: for (;;) < // forever loop System.out.print ("Level code :"); levelCode = input.next ().charAt (0); switch (levelCode) < case 'F': // code here break LOOP; //

Java Class 3

For loop inside the Switch-Case

I want to determine some port writings for area1, area2, and so on.

 void controlEvent(CallbackEvent event) < if (event.getAction() == ControlP5.ACTION_CLICK) < for (int i=1; i> > > 

But I got «case expressions must be constant expressions» error. Is there a way to use a for loop in switch-case? If not, what would be the most logical way to rewrite the codes above?

As it is mentioned switch expects constants only, so the value must be known in compilation time, not dynamic. So

case "Area1": case "Area2": . etc 

If you want to be more dynamic, then use either if and else-if statements;

void controlEvent(CallbackEvent event) < if (event.getAction() == ControlP5.ACTION_CLICK) < for (int i=1; ibreak; > . >>> 

It is a good idea to normalize the action name and extract blocks of code. Having 13 switch cases of if-else statements can be hard to read, so it would be nice to extract method to handle each ControlP5 or conrtolName

Second approach (a little bit too complex maybe, but still): Create a map of actions:

Map> actionMap = new HashMap<>(); actionMap.put("Area1", i -> < println("Button" + i + " Pressed"); if (port != null) < port.write(i + "\n"); >>); actionMap.put("Area2", i ->< println("Button" + i + " Pressed"); . >); .. etc 

Now you can check if your action map holds desired controlName:

 void controlEvent(CallbackEvent event) < if (event.getAction() == ControlP5.ACTION_CLICK) < final String controlName = event.getController().getName(); if(actionMap.hasKey(controlName))< actionMap.get(controlName).apply(. ) break; >> > > 

Java — Using switch statements inside a for loop, The switch/case statement inside of a for loop is fine, the problem is that switch isn’t a function call. Try something like this: string obj; switch (n) < … Usage exampleprintln("He played knick-knack on my" + switch(n));Feedback

Java- For loop with a switch statement containing default case. How can I get the default case to print the output only once?

The following default statement does exactly what its supposed to: catching all characters not mentioned in the above cases, AND notifying me (after running through the string), that there was an invalid character entered somewhere in there. However, if there was two invalid characters: the println statement will print twice. If there were three: three times, etc. In a string of 100,000 characters, it would be inefficient to print the line so many times.

How would I be able to get it to print only once, no matter how many invalid characters were entered? Please advise and thank you in advance for helping a Java novice!

 //for loop to calculate how many A's, G's, T's, and C's in the string //default statement at the end of the switch statements to weed out //invalid characters. for(int i=0; i < length; i++) < ch = dna.charAt(i); switch (ch) < case 'A': aCount++; break; case 'C': cCount++; break; case 'G': gCount++; break; case 'T': tCount++; break; default: System.out.println("An invalid character was entered."); >> 
 import java.util.Scanner; //done by Nadim Baraky //this program calculates the number of A's, C's, G's & T's; //it prints a statement once as you wished in case invalid characters where entered public class ACGT_DNA < public static void main (String[] args) < //the counter is set to be 1; int length, counter=1; int aCount =0, cCount=0, gCount =0, tCount=0; char ch; Scanner scan = new Scanner(System.in); System.out.print("Enter your string: "); String dna = scan.next(); scan.close(); length = dna.length(); for(int i=0; i < length; i++) < ch = dna.charAt(i); switch (ch) < case 'A': aCount++; break; case 'C': cCount++; break; case 'G': gCount++; break; case 'T': tCount++; break; default: if(counter==1) < System.out.println("An invalid character was entered."); counter++; //after counter is being incremented, the if statement won't be true; so no matter how invalid characters you enter, the statement will be just be printed once. >> > System.out.println("A's " + aCount); System.out.println("C's " + cCount); System.out.println("G's " + gCount); System.out.println("T's " + tCount); > 

Java Looping a switch-case statement on «invalid input», 1. You are using the run variable in a very odd way. Since you set the run to false at the end of the loop, the loop will never repeat. If you change it …

Источник

Switch statement

Assume you have built a website and a user is trying to log into it. You are asking the user to enter his email. Then you are checking whether that email is stored in your database and if so you are fetching his user role (admin, blog writer, reader). If mail is not found the user is a guest. After that you want to print this user roles. To implement this you can easily use switch statements.
Look at the code block given below (Assume you have already fetched the user role from the database into a String variable named userole ).

switch (userRole)  case "admin": System.out.println("Hi you are an admin"); break; case "blog writer": System.out.println("Hi you are a blog writer"); break; case "reader": System.out.println("Hi you are a reader"); break; default: System.out.println("Hi you are a guest. Please register to log in."); > 

In here the first case checks whether the value of the userRole is ‘admin’. If so it will print «Hi you are an admin». You can see that I have added break after the print statement. What break does is that going out of the switch statements. Which means once a particular case is achieved, no other cases will be evaluated. You will simply go out of the switch block. Same process goes to the cases ‘blog writer’ and ‘reader’.
Next comes the case where you were unable to find the email in the database. Therefore that email does not have a userRole yet. SO by default the last case will print the ‘guest’ statement. There we have not used break . This is because, default is the last case in the switch block. So it will automatically go out of the switch block. No break statement is required here. This might be a bit messy to understand but once you get used to it applying switch statements will become handy.

Loops

for Loop

Think that you want to print numbers from 1 to 5. Then you will think that you have to write pritln() line 5 times. But what if you have an opportunity to write just one println() and iterate it 5 times? Sounds great right. Let’s see how we can do that.

for (int i = 1; i  5; i++) System.out.println(i); 

Let’s evaluate the code. We have use iterations here by using a ‘for loop’. As you can see I have declared a variable i inside the parenthesis of the for() . After that we have give the range for ‘i’. Here we want to print numbers from 1 to 5. Therefore i has to be iterated from 1 to 5. So I have mentioned as i = 1 and after a semi colon (;) I have stated that i

Task

String[] books = "Twilight", "New moon", "Eclipse", "Breaking dawn", "Safe Heaven", "Kite Runner", "Hunger Games">; for (String book : books) System.out.println(book); 

Here the string book in the parenthesis refers to a single element in the array books . Therefore, this will print all the elements in the books array accurately. The negative side of this method is that you can only iterate from beginning to the end. Like you cannot get the output as Hunger Games, Kite Runner, . Twilight (from right to left) order. And also since you do not have access to index, you won’t be able to know the index value of a particular element when you use this method.

While Loop

What if you do not know the number of the iterations beforehand? Then you can use ‘while loop’. Check the below code;

int i = 0; while(i  10)  System.out.println(i); i++; > 

In the above code we first declared an integer variable i and initialized it into zero. The code line while(i<10) ensures that the value of i is always less than 10. Which means the code inside the while() loop will only execute if the i is less than 10. Then we print i and increment it by one.

Assume in a case where you want user to add subject names, but you do not know number of subjects that are available. What can you do in such a scenario? You have to use a ‘while loop’ as you do not know the number of iterations here. You can ask the user to enter some word like ‘quit’ or ‘finish’, if he has entered all the subjects. Then you can make the loop run only when the input word is not equal to the termination word. Go through the below code.

Scanner userInput = new Scanner(System.in); String input = ""; int count = 0; while (!input.equals("quit"))  System.out.print("Subject: "); input = userInput.nextLine().toLowerCase(); count += 1; > int subjectCount = count - 1; System.out.println("Number of subjects o">+ subjectCount); 

In above code we have taken user input as a Scanner class object, and then has read the line and has stored into the string input . Here you can see that I have used the method toLowerCase() . Why do we need that? Look at the condition inside the parenthesis of the while loop. What it means that the value stored in input string cannot be equal to ‘quit’. All the letters in ‘quit’ is in lowercase. Therefore, if user entered like ‘Quit’ or ‘QUIT’ the loop will not terminate. So to avoid those disconcerts we have to convert the user input into lowercase.

do while loops

There is only one deference in ‘do-while’ loop when compared to ‘while’ loops. In while loop, statements will execute if and only if the condition given in the loop is true. But in ‘do-while’ loops statements gets executed once before checking the conditions given for the loop. Check the following code.

int i = 0; do  System.out.println(i); i++; > while(i  10); 

Here, first println() method gets executed and print ‘0’. After that it will increment it value to 1. Then only the condition in while loop is taken under consideration. Because of this we can say that ‘do-while’ loops will definitely execute ‘at least’ only once. And with that we can wrap up this article 🙂

Источник

Читайте также:  Сохранить html страницу чтобы открывалась
Оцените статью