So I wanted my switch to be if the user chooses the switch(b) No it will go back to switch(a) the previous switch. How can I do it? I'm quite new to Java.
switch(a){
case 1:
System.out.println("Here are the available rooms.");
System.out.println("[1] Room No. 1");
System.out.println("[2] Room No. 2");
System.out.println("[3] Room No. 3");
System.out.println("[4] Room No. 4");
System.out.println("[5] Room No. 5\n");
System.out.print("\nWhich room would you like? [1-5]:");
b= sc.nextInt();
switch(b){
case 1:
System.out.println("Room No. 1 costs $200 per stay.");
System.out.println("[1] Yes");
System.out.println("[2] No");
System.out.print("Do you wish to proceed? :");
c=sc.nextInt();
break;
}
break;
}
You would need to use a labelled loop:
theLabel: while (true) { // whatever condition, whatever kind of loop:
switch (a) {
case 1:
// ...
switch (b) {
case 1:
// ...
continue theLabel;
}
}
}
This will jump back to the start of the outer loop, thus it would execute the switch on a again.
But really, this is not a good way to structure it. There is nearly always a better way than using labelled loops, for example extracting some of the nested logic to a method.
In this case, I'd question the use of a switch for "room 1-room 5". Unless there is specific logic for each of the rooms, just use (for example) an array or list or map to store the prices for each of the rooms.
If your question is about going from moving switch b to switch a. Then you can use the recursion for this purpose.
I don't know about return types. So the prototype is
Write the switch(a) in a method. Let's name this method as method1.
write switch(b) in a method. Let's name this method as method2.
method1(Object a)
{
switch(a):
case 1:
//Your code here
if(condition1)
{
method2(a);
}
}
method2(Object b )
{
switch(b):
if(condition2)
{
method1(b)
}
}
I'm a newbie to code and I'm trying to make a program that tells the user the temperature and how long to cook beef roasts. I decided to use scanner and now I'm getting the no such element exception error. This is what my code looks like, and I can't tell what I'm doing wrong.
import java.util.Scanner;
public class Roasts {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Which Roast are you cooking? 1. Chuck 2. Tenderloin 3. Rib 4. Sirloin 5. Tri-tip 6. Shoulder ");
int numb=0;
numb=input.nextInt();
switch (numb) {
case 1:
System.out.println("300 degrees for 3 hours");
break;
case 2:
System.out.println("350 degrees for 1 hour, then turn off heat and leave roast in oven for 1 additional hour");
break;
case 3:
System.out.println("375 degrees for 1 hour, then turn off heat and leave roast in oven for an additional 2 hours");
break;
case 4:
System.out.println("350 degrees for 45 mins to one hour");
break;
case 5:
System.out.println("375 degrees for 45 mins");
break;
case 6:
System.out.println("325 degrees for 4 hours");
break;
default:
System.out.println("invalid number please choose 1-6");
}
}
}
When NoSuchElementException is thrown (from here):
Thrown by various accessor methods to indicate that the element being requested does not exist.
When Scanner.nextInt() throws NoSuchElementException (from here):
If the input is exhausted
I actually don't see that your program that is crafted in an improper way, but it can be the case that you are supplying input that is causing this problem.
Probably you should consider checking Scanner#hasNextInt() before invoking Scanner#nextInt().
I'd also recommend you to first read javadocs of the classes that you are using to get better understanding of the behavior and make more sense of the errors/exceptions that you are getting as you are a beginner. HTH.
I tried running your code and it seems to me that there is no problem with it at all. Perhaps there is something wrong with your IDE?
The possible reason for this (though seems strange in that particular situation) is that new line character is left in your scanner object. Try to rework your line:
numb=input.nextInt();
to:
numb = Integer.parseInt(input.nextLine());
I have hit another obstacle in my attempt to create a shape calculator and this time it's using a Loop with my Switch/Case statements allowing the user to select the shapes they wish to calculate.
I am trying to make my Calculator like this. User selects 1 for Triangle, they calculate that and say they now wish to select 5 to calculate a Circle right after, then do another circle calculation again and for however many times they wish and then be able to move onto another shape. Say 6 for a sphere.
So far I've tried using a While (True) loop but it seems once I have made a selection I get stuck in that case and can't go on to select another shape to calculate or select the case that closes/exits the program.
I've reduced my program to an example below cutting out the code needed to make a shapes as the shapes themselves are not the program here. It's trying to make my users range of choice flexible I guess you could say.
Scanner scan = new Scanner(System.in); //take user input
int decision = scan.nextInt();
loop: while (true) {
switch (decision) {
case 1:
//example
break;
case 2:
//example and so on
break;
case 3:
break;
case 9:
// Quit
System.out.println("You decided to Quit");
break loop;
default:
// Wrong decision
System.out.println("Select a number between 1 and 8 to make a decision or 9 to Quit");
}
//exit program code here
}
In your loop you need to prompt for and read the next selection. The code you show reads one selection to set decision, but never changes it after that.
Move the scan.nextInt() inside the loop
loop: while (true) {
int decision = scan.nextInt();
switch (decision) {
case 1:
//example
break;
case 2:
//example and so on
break;
case 3:
break;
case 9:
// Quit
System.out.println("You decided to Quit");
break loop;
default:
// Wrong decision
System.out.println("Select a number between 1 and 8 to make a decision or 9 to Quit");
}
//exit program code here
}
Problem:
You are taking decision input only once, since it is written outside the infinite while loop. Therefore during execution of infinite loop, decision will never change and every time same case will get executed, giving an impression that program is stuck within a case, which is not the case any ways.
Solution: Move the input statement withing infinite while loop.
while (true) {
int decision = scan.nextInt();
//rest of the code
....
....
}
You must read the decision input everytime (infinite loop)
This should work:
Scanner scan = new Scanner(System.in); //take user input
loop: while (true) {
int decision = scan.nextInt();
switch (decision) {
case 1:
//example
break;
case 2:
//example and so on
break;
case 3:
break;
case 9:
// Quit
System.out.println("You decided to Quit");
break loop;
default:
// Wrong decision
System.out.println("Select a number between 1 and 8 to make a decision or 9 to Quit");
}
//exit program code here
}
Why doesn't the compiler automatically put break statements after each code block in the switch? Is it for historical reasons? When would you want multiple code blocks to execute?
Sometimes it is helpful to have multiple cases associated with the same code block, such as
case 'A':
case 'B':
case 'C':
doSomething();
break;
case 'D':
case 'E':
doSomethingElse();
break;
etc. Just an example.
In my experience, usually it is bad style to "fall through" and have multiple blocks of code execute for one case, but there may be uses for it in some situations.
Historically, it's because the case was essentially defining a label, also known as the target point of a goto call. The switch statement and its associated cases really just represent a multiway branch with multiple potential entry points into a stream of code.
All that said, it has been noted a nearly infinite number of times that break is almost always the default behavior that you'd rather have at the end of every case.
Java comes from C and that is the syntax from C.
There are times where you want multiple case statements to just have one execution path.
Below is a sample that will tell you how many days in a month.
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = " + numDays);
}
}
I think it is a mistake. As a language construct it is just as easy to have break as the default and instead have a fallthrough keyword. Most of the code I have written and read has a break after every case.
You can do all sorts of interesting things with case fall-through.
For example, lets say you want to do a particular action for all cases, but in a certain case you want to do that action plus something else. Using a switch statement with fall-through would make it quite easy.
switch (someValue)
{
case extendedActionValue:
// do extended action here, falls through to normal action
case normalActionValue:
case otherNormalActionValue:
// do normal action here
break;
}
Of course, it is easy to forget the break statement at the end of a case and cause unexpected behavior. Good compilers will warn you when you omit the break statement.
Why doesn't the compiler automatically put break statements after each code block in the switch?
Leaving aside the good desire to be able to use the identical block for several cases (which could be special-cased)...
Is it for historical reasons? When would you want multiple code blocks to execute?
It's mainly for compatibility with C, and is arguably an ancient hack from the days of old when goto keywords roamed the earth. It does enable some amazing things, of course, such as Duff's Device, but whether that's a point in its favor or against is… argumentative at best.
The break after switch cases is used to avoid the fallthrough in the switch statements. Though interestingly this now can be achieved through the newly formed switch labels as implemented via JEP-325.
With these changes, the break with every switch case can be avoided as demonstrated further :-
public class SwitchExpressionsNoFallThrough {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int value = scanner.nextInt();
/*
* Before JEP-325
*/
switch (value) {
case 1:
System.out.println("one");
case 2:
System.out.println("two");
default:
System.out.println("many");
}
/*
* After JEP-325
*/
switch (value) {
case 1 ->System.out.println("one");
case 2 ->System.out.println("two");
default ->System.out.println("many");
}
}
}
On executing the above code with JDK-12, the comparative output could be seen as
//input
1
// output from the implementation before JEP-325
one
two
many
// output from the implementation after JEP-325
one
and
//input
2
// output from the implementation before JEP-325
two
many
// output from the implementation after JEP-325
two
and of course the thing unchanged
// input
3
many // default case match
many // branches to 'default' as well
So you do not have to repeat code if you need several cases to do the same thing:
case THIS:
case THAT:
{
code;
break;
}
Or you can do things like :
case THIS:
{
do this;
}
case THAT:
{
do that;
}
In a cascade fashion.
Really bug/confusion prone, if you ask me.
As far as the historical record goes, Tony Hoare invented the case statement in the 1960s, during the "structured programming" revolution. Tony's case statement supported multiple labels per case and automatic exit with no stinking break statements. The requirement for an explicit break was something that came out of the BCPL/B/C line. Dennis Ritchie writes (in ACM HOPL-II):
For example, the endcase that escapes from a BCPL switchon statement was not present in the language
when we learned it in the 1960s, and so the overloading of the break keyword to escape
from the B and C switch statement owes to divergent evolution rather than conscious change.
I haven't been able to find any historical writings about BCPL, but Ritchie's comment suggests that the break was more or less a historical accident. BCPL later fixed the problem, but perhaps Ritchie and Thompson were too busy inventing Unix to be bothered with such a detail :-)
Java is derived from C, whose heritage includes a technique known as Duff's Device .
It's an optimization that relies on the fact that control falls through from one case to the next, in the absence of a break; statement. By the time C was standardized, there was plenty of code like that "in the wild", and it would have been counterproductive to change the language to break such constructions.
As people said before, it is to allow fall-through and it is not a mistake, it is a feature.
If too many break statements annoy you, you can easily get rid of them by using return statements instead. This is actually a good practice, because your methods should be as small as possible (for the sake of readability and maintainability), so a switch statement is already big enough for a method, hence, a good method should not contain anything else, this is an example:
public class SwitchTester{
private static final Log log = LogFactory.getLog(SwitchTester.class);
public static void main(String[] args){
log.info(monthsOfTheSeason(Season.WINTER));
log.info(monthsOfTheSeason(Season.SPRING));
log.info(monthsOfTheSeason(Season.SUMMER));
log.info(monthsOfTheSeason(Season.AUTUMN));
}
enum Season{WINTER, SPRING, SUMMER, AUTUMN};
static String monthsOfTheSeason(Season season){
switch(season){
case WINTER:
return "Dec, Jan, Feb";
case SPRING:
return "Mar, Apr, May";
case SUMMER:
return "Jun, Jul, Aug";
case AUTUMN:
return "Sep, Oct, Nov";
default:
//actually a NullPointerException will be thrown before reaching this
throw new IllegalArgumentException("Season must not be null");
}
}
}
The execution prints:
12:37:25.760 [main] INFO lang.SwitchTester - Dec, Jan, Feb
12:37:25.762 [main] INFO lang.SwitchTester - Mar, Apr, May
12:37:25.762 [main] INFO lang.SwitchTester - Jun, Jul, Aug
12:37:25.762 [main] INFO lang.SwitchTester - Sep, Oct, Nov
as expected.
It is an old question but actually I ran into using the case without break statement today. Not using break is actually very useful when you need to combine different functions in sequence.
e.g. using http response codes to authenticate user with time token
server response code 401 - token is outdated -> regenerate token and log user in.
server response code 200 - token is OK -> log user in.
in case statements:
case 404:
case 500:
{
Log.v("Server responses","Unable to respond due to server error");
break;
}
case 401:
{
//regenerate token
}
case 200:
{
// log in user
break;
}
Using this you do not need to call log in user function for 401 response because when the token is regenerated, the runtime jumps into the case 200.
Not having an automatic break added by the compiler makes it possible to use a switch/case to test for conditions like 1 <= a <= 3 by removing the break statement from 1 and 2.
switch(a) {
case 1: //I'm between 1 and 3
case 2: //I'm between 1 and 3
case 3: //I'm between 1 and 3
break;
}
because there are situations where you want to flow through the first block for example to avoid writing the same code in multiple blocks but still be able to divide them for mroe control. There are also a ton of other reasons.
You can makes easily to separate other type of number, month, count.
This is better then if in this case;
public static void spanishNumbers(String span){
span = span.toLowerCase().replace(" ", "");
switch (span){
case "1":
case "jan": System.out.println("uno"); break;
case "2":
case "feb": System.out.println("dos"); break;
case "3":
case "mar": System.out.println("tres"); break;
case "4":
case "apr": System.out.println("cuatro"); break;
case "5":
case "may": System.out.println("cinco"); break;
case "6":
case "jun": System.out.println("seis"); break;
case "7":
case "jul": System.out.println("seite"); break;
case "8":
case "aug": System.out.println("ocho"); break;
case "9":
case "sep": System.out.println("nueve"); break;
case "10":
case "oct": System.out.println("diez"); break;
}
}
I am now working on project where I am in need of break in my switch statement otherwise the code won't work. Bear with me and I will give you a good example of why you need break in your switch statement.
Imagine you have three states, one that waits for the user to enter a number, the second to calculate it and the third to print the sum.
In that case you have:
State1 - Wait for user to enter a number
State2 - Print the sum
state3 - Calculate the sum
Looking at the states, you would want the order of exaction to start on state1, then state3 and finally state2. Otherwise we will only print users input without calculating the sum. Just to clarify it again, we wait for the user to enter a value, then calculate the sum and prints the sum.
Here is an example code:
while(1){
switch(state){
case state1:
// Wait for user input code
state = state3; // Jump to state3
break;
case state2:
//Print the sum code
state = state3; // Jump to state3;
case state3:
// Calculate the sum code
state = wait; // Jump to state1
break;
}
}
If we don't use break, it will execute in this order, state1, state2 and state3. But using break, we avoid this scenario, and can order in the right procedure which is to begin with state1, then state3 and last but not least state2.
Exactly, because with some clever placement you can execute blocks in cascade.