One of the requirements of my project is that the program loops until the user presses the "X" key. I have the method for this, but the program terminates even when the method is not called. Here is my code:
while (terminate == false)
{
// Ask user for input
switch (command)
{
case "I":
{
// Do stuff
}
case "X":
{
terminateProgram();
}
}
}
This is my terminate method:
private static boolean terminateProgram()
{
terminate = true;
return terminate;
}
Even if I enter the "I" key, the loop ends after the case for "I" is completed. "I" works normally if terminateProgram(); is commented. How do I get the loop to stop only when I enter "X"?
You need a break within each case statement.
Read up on fall-through, which is what your current code is doing.
while (!terminate)
{
// Ask user for input
switch (command)
{
case "I":
{
// Do stuff
break;
}
case "X":
{
terminateProgram()
break;
}
default:
// Do something default if no condition is met.
}
}
Then here:
private static void terminateProgram()
{
terminate = true; // if this method simply is to terminate a program
// I'm not quite sure why you need a `terminate` variable
// unless you're using it in another part of the program.
// A simple system.exit(0) would suffice.
System.exit(0);
}
Related
So I'm building an email administration app and although it is working with if statements, I am trying to incorporate switch statements. I am prompting the user using a scanner to select which department they are from while building their email associated with it. Although when I am trying to return this.department, it is saying it is unreachable. I feel like I am missing something very obvious.
// Ask for the department
private String setDepartment() {
Scanner sc = new Scanner(System.in);
int department;
System.out.println("Select your department:\n1. Sales\n2.Accounting\n3.Development\n4.N/A");
department = sc.nextInt();
while (true) {
switch (department) {
case 1:
this.department = "Sales";
break;
case 2:
this.department = "Accounting";
break;
case 3:
this.department = "Development";
break;
case 4:
this.department = "";
break;
default:
System.out.println("Please choose a valid option (1-4)");
break;
}
sc.close();
}
return this.department; <-- Error: Unreachable code
}
problem is your condition inside the while() loop .It set always to true .So code below the while loop never gets executed .Try to have a different condition inside the while loop which terminates in a certain value.Otherwise you need place what ever you want to return inside the while loop.
Extra: Please also place your sc.close(); outside the while loop otherwise you can't use the resource after the first while loop iteration.so closing resource must be done always at the end.
Solution 1:
while(updatedTerminationCondition){//change the termination condition
}
Solution 2:
while(true){
//place your return value inside here but then loop will only run once
}
The problem is your switch-statement is in a while(true) loop that gets never exited. Unless you explicitly exit the loop e.g. by using break the program will never stop to execute the loop, meaning any code below it will never get reached, thats what the compiler is complaining about.
first question:
There is a do while loop, within the do section there is a switch. After selection case 1, some calculations are done, two options can result as shown in the If statement. My problem is code runs until the break; then just goes straight back to the menu loop. My question: how do i get the program to print the output for the user, then continue the menu loop?
Second question:
In case 1 there are two resulting options, the first being a failed response. from here, how do i get the program to loop back to the start of case 1 to ask for user input again? Even back to the main menu would be fine.
public static void showMenu() {
System.out.print('\u000c');
System.out.println("1 - Compute Change \n");
System.out.println("2 - Estimate Feast \n");
System.out.println("3 - \n");
System.out.println("4 - \n");
System.out.println("5 - I'm broke, get me out of here\n");
System.out.println("Select Option:\n");
}
public StackPost() {
System.out.println("Welcome to the Bank of Winterfell");
Scanner in = new Scanner(System.in);
do {
showMenu();
selection = in.nextInt();
switch (selection) {
case 1:
// get input, compute then decision:
if (something<somethingElse) {
// false response -
} else {
// correct response - system prints out some stuff back to user, back to main
// menu loop
}
break;
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
You could print "Press enter to continue" (or whatever you want to give notice of before locking the program), and add a call to Scanner#nextLine() before your break. This will lock the progression 'till user presses enter.
case 2:
// Some code here...
// Done, now show result and tell user to press any key to continue
System.out.println("Some fancy result from case handle code");
System.out.println("Press enter to continue...");
in.nextLine();
break;
You could add a while-loop that won't let the code continue 'till whatever input is expected in the first case is acceptable.
case 1:
System.out.println("Some handle that tells user to input something, and what is acceptable");
String input = null;
while(!(input = in.nextLine()).equals("something")) {
System.out.println("Wrong input, try again...");
}
// Input is acceptable, now do something with it...
System.out.println(input);
System.out.println("Press enter to continue...");
in.nextLine();
break;
Be aware, in your code, you call Scanner#nextInt(), and #nextInt doesn't consume the \n from pressing enter, and will thus be transferred into the switch case's usage of #nextLine(). You could avoid this with selection = Integer.parseInt(in.nextLine()).
You can use achieve it by:
For First question: Using return statement in case of correct response.
For Second question: Using while loop in case 1
After implementaing the proposed solution the StackPost() method will look like following. You can see the complete working code here:
public static void StackPost()
{
System.out.println("Welcome to the Bank of Winterfell");
try(Scanner in = new Scanner(System.in))
{
int selection;
do
{
showMenu();
selection = in.nextInt();
switch (selection)
{
case 1:
// get input, compute then decision:
while(true)
{
int something = in.nextInt();
int somethingElse = in.nextInt();
if (!(something<somethingElse)) {
// correct response - system prints out some stuff back to user, back to main
System.out.println("Print here the result");
// menu loop
return;
}
// false response - continue for next iteration in while-loop
}
//No need of 'break;' here
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
}
Note: It is best practice to use try-with-resources while handling system resources which implements AutoCloseable interface.
I'm trying to make a "choice" menu, where I am using a switch/case function to make the user choose. The problem in my code is that I want it to keep asking for input until the user types in "sair" which means "exit" in portuguese. When they type "ajuda" which means "help" they get a list of available commands to execute, but if the user types "ajuda" then the "sout" is executed and build is finished, the program ends there...
My goal is to make it run until we choose to stop, I think there was a ways using readln or similar.
Anyways, here's the chunk of code regarding to the choice:
public static String escolha() {
Scanner userInput = new Scanner(System.in);
String strEscolha = userInput.next();
boolean sair = false;
do {
switch (strEscolha) {
case "ajuda":
System.out.println("Comandos disponiveis:");
System.out.println("Ajuda; Fogo; Jogo; Resposta; Estado; Acaso; Reset; Sair;");
break;
case "Ajuda":
System.out.println("Comandos disponiveis:");
System.out.println("Ajuda; Fogo; Jogo; Resposta; Estado; Acaso; Reset; Sair;");
break;
case "sair":
System.out.println("Obrigado por jogar!");
sair = true;
break;
default:
System.out.println("Comando Invalido!");
continue;
}
} while (sair == false);
return null;
}
If anyone has a simple way to make it keep asking for commands, please let me know :(
Thanks in advance!!
PS: I just started, plese don't judge, my knowledge on java is neglectable :\
The main problem of your code is that you do not request user input in the 'ajuda' case.
Here is the code with some minor changes and some comments and recommendations:
// if your method isn't supposed to return anything, simply make it void
public static void escolha() {
Scanner userInput = new Scanner(System.in);
// print some useful information when the application starts, so that the user knows
// what to do
System.out.println("Comandos disponiveis:");
System.out
.println("Ajuda; Fogo; Jogo; Resposta; Estado; Acaso; Reset; Sair;");
String strEscolha = userInput.next();
boolean sair = false;
do {
// remove duplicate case by converting the input to lower letters
switch (strEscolha.toLowerCase()) {
case "ajuda":
System.out.println("Comandos disponiveis:");
System.out
.println("Ajuda; Fogo; Jogo; Resposta; Estado; Acaso; Reset; Sair;");
// read the user input
strEscolha = userInput.next();
System.out.println(strEscolha);
break;
case "sair":
System.out.println("Obrigado por jogar!");
sair = true;
break;
default:
System.out.println("Comando Invalido!");
}
} while (sair == false);
// do not forget to close the scanner, it might cause a memory leak
userInput.close();
}
Firstly, remove the System.exit, or you will shut down the entire JVM without executing the subsequent code (your IDE may have given you a dead code warning about this).
Secondly, you need to use sair == false (or, better, !sair) instead of sair = false. The former is a comparison; the latter is an assignment, making sair false.
do { ... } while (false) will execute the loop body once, but will not repeat.
Thirdly, the return strEscolha; immediately before while will cause the method to return before it attempts to loop, so it should be removed.
I have an assignment for my Java class to program a Magic 8-ball. It is supposed to generate a random number for the response, contain a "while(true)" statement, and a switch statement for the replies. This is what I have so far. I can't seem to figure out how to work the "while(true)" statement in without it repeating infinitely.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String question;
int retry;
int q1;
System.out.print("What is your question for the Magic 8-bit 8-ball? ");
question = input.next();
System.out.print(process());
/*This is where I am having the problem. How do I work a "while(true)" in
* to where this won't infinitely repeat?
*/
}
public static int process() {
Random rand1 = new Random();
int random = rand1.nextInt(9);
int ans = random;
switch (ans) {
default: System.out.println("Does not compute!! Error! Error!");break;
case 1: System.out.println("The answer is.............. 42");break;
case 2: System.out.println("To get to the other side!!!");break;
case 3: System.out.println("Out of memory! Try again!");break;
case 4: System.out.println("Who do you think I am, IBM's Watson?");break;
case 5: System.out.println("Danger Will Robinson!! Danger!!");break;
case 6: System.out.println("What do you think?");break;
case 7: System.out.println("Fatal error.....nahhh just kidding");break;
case 8: System.out.println("Well, this is fun....NOT!");break;
case 9: System.out.println("Um...... 1,000,000,000,000,000,000,000?");break;
}
return ans;
}
}
Hum, the point of a while (true) loop is to be infinite, unless you add a break statement in it.
while (true) {
doStuff();
// if someCondition is true, this will exit the loop
if (someCondition)
break;
}
Note that this is equivalent to
do {
doStuff();
} while (!someCondition);
or
boolean someCondition = false;
while (!someCondition) {
doStuff();
}
It is usually preferrable to not have an infinite loop (while (true) for example) and have an explicit condition instead. Some exceptions exist, for example if the condition is complicated to express or if you want to break the loop at a particular position of the loop and not at the beginning or at the end :
while (true) {
doStuff();
if (someCondition)
break;
doSomeOtherStuff();
}
One of the many possible ways:
Create a a char and assign it to 'Y' (i.e. char continueLoop = 'Y').
Use this to control the while statement (i.e. while(char == 'Y') ).
Ask the user for input and process the input (i.e. System.out.println("Continue? Y/N") and then use Scanner to read the input and assign it to continueLoop.
You can create something similar using booleans.
I have written following method in Java. But I get error message unreachable code on the line containing return (Constants.SUCCESS);
If I comment that line, I do not get error message. Now my doubt is why I do not get error message if I comment that line? There is no return value of SUCCESS to the calling portion if I comment the line. I thought there should be one return statement and there are none if all "if loops" and default is not getting executed. I thought last return statement will execute in any case. I tried return (Constants.SUCCESS) statement at the end also (Commented line), but no luck.
So for returning success, do I need to return success after each "if" loop under every case statements (creating "else" part for each).
static int validateStartAndEndStringOrder(String startStr, String endStr, ArrayList<String> swaraPool, Constants.PatternType ptrnType) {
switch (ptrnType) {
case AROHA_INCREASING: {
if (swaraPool.indexOf(endStr) < swaraPool.indexOf(startStr)) {
System.out.println("End string is before the start String");
return (-1);
}
}
case AROHA_DECREASING: {
if (swaraPool.indexOf(startStr) < swaraPool.indexOf(endStr)) {
System.out.println("End string is before the start String");
return (-1);
}
}
case AVAROHA_INCREASING: {
if (swaraPool.indexOf(endStr) < swaraPool.indexOf(startStr)) {
System.out.println("End string is before the start String");
return (-1);
}
}
case AVAROHA_DECREASING: {
if (swaraPool.indexOf(startStr) < swaraPool.indexOf(endStr)) {
System.out.println("End string is before the start String");
return (-1);
}
}
default: {
System.out.println("Invalid Enumeration Type");
return(-1);
}
return (Constants.SUCCESS);
}
//return (Constants.SUCCESS);
}
switch ... case 1 ... case n ... default covers all control paths (the default will catch all remaining cases). Since you return explicitly out of each one, there's no way program control can go beyond that switch block.
Your compiler is being helpful in emitting the error.
Use break; statements between each case in the switch block to move control flow to the end of the block.
I suspect you want to add a break; at the end of your case blocks. Otherwise the code just runs from top to bottom (like anywhere else in your code)
If you place a break; it will jump outside the switch block which appears to be what you want.
e.g.
case AROHA_INCREASING: {
if (swaraPool.indexOf(endStr) < swaraPool.indexOf(startStr)) {
System.out.println("End string is before the start String");
return (-1);
}
break; // without this, the thread will run the next case: block.
}
You default section contains
{
System.out.println("Invalid Enumeration Type");
return(-1);
}
return (Constants.SUCCESS);
What do you expect?