How to break out of loop when case is selected - java

I have a code that has 4 cases and I am trying to break the loop and if the 'f' case is chosen. and then choose from that case. When i try to do the if statement with the break over 30 errors but when I take it away the code is fine.
String one = "";
boolean yea = true;
Scanner sw = new Scanner(System.in);
while (yea == true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
switch(choice)
{
case 'f':
friendsList();
break;
case 'w':
wall();
break;
case 'p':
network();
break;
case 'q' :
yea = false;
break;
default:
System.out.println("Error: You have entered " + choice +
". Please try again");
}
}
if (case == 'f')
{
break;
}
}

You would use a Java label (see this code example named BreakWithLabelDemo.java) to tell your code where to break.
myloop:
while ( true ){
switch( choice ){
case 'f':
friendsList();
break myloop;
}
}

For your implementation, it would make sense to break on a specific case before even entering the switch statement. For example:
char choice = one.charAt(0);
if (choice == 'f') break;
switch(choice)
This seems to be a pretty simple way to exit the while loop without conflicting with the break statements of the switch statement.
Or if you still need to call the friendsList method when choice is 'f' you can move that if statement to after the switch statement.
Note: With this you should also remove the if statement at the bottom of your code example.

if (case == 'f')
What is case in this statement? You should replace that with choice.
if (choice == 'f')

you need to put if inside while loop.
String one = "";
boolean yea = true;
Scanner sw = new Scanner(System.in);
while (yea == true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
switch(choice)
{
case 'f':
friendsList();
break;
case 'w':
wall();
break;
case 'p':
network();
break;
case 'q' :
yea = false;
break;
default:
System.out.println("Error: You have entered " + choice +
". Please try again");
}
if (choice == 'f')
{
break;
}
}

The if statement should be moved inside of the while loop to be effective, and case inside the if statement should be changed to choice.
so
While(yea==true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
if(choice == 'F')
{
break;
}
switch(choice)
{
//cases
}
}

Related

How to choose and write a loop for this specific task?

I am pretty new to Java. Sorry if this is a lame question. I have this chunk of code. It is not the whole thing obviously.
char option = scan.next().charAt(0);
for (option !='a'||option !='b'||option !='c'||option !='d'||option !='e'||option !='f'||option !='q') {
System.out.println("Please pick an option from the menu above");
}
int lengthOne = stringOne.length(); //Getting the lengths for each string
int lengthTwo = stringTwo.length();
if (option == 'a'|| option == 'A') { //If the user inputs a
if (lengthOne == lengthTwo) { //If both lengths are equal
System.out.println("The strings are the same length");
}
Looking for some advice on which loop i should use for this code. The options will be A-F and then Q to quit.
The while loop can seem messy for what you are trying to accomplish. I would use a Switch statement inside a 'do while' loop.
If the user input doesn't match a 'case' then it will go to the default.
When a user enters 'q' to quit then boolean validSelection turns to true and you will exit the 'do while' loop.
public static void main( String[] args )
{
Scanner scan = new Scanner( System.in );
boolean validSelection = false;
do
{
System.out.println( "Please pick an option from the menu above" );
char option = scan.next().charAt( 0 );
switch( option )
{
case 'a':
break;
case 'b':
break;
case 'c':
break;
case 'd':
break;
case 'e':
break;
case 'f':
break;
case 'q':
validSelection = true;
break;
default:
System.out.println( "Choice invalid." );
break;
}
}
while( validSelection == false );
}
}
Add a scan inside the loop.
char option = scan.next().charAt(0);
while (option !='a'||option !='b'||option !='c'||option !='d'||option !='e'||option !='f'||option !='q') {
System.out.println("Please pick an option from the menu above");
option = scan.next().charAt(0);
}
Try this
Scanner scan = new Scanner(System.in);
char option = scan.next().charAt(0);
while (option != 'a' && option !='b' && option != 'c'&& option !='d'&& option !='e'&& option !='f'&& option !='q') {
System.out.println("Please pick an option from the menu above");
option = scan.next().charAt(0);
}
You will need the ANDs instead of the ORs or it wont work

Is it possible to exit from a main method without terminating the program?

I know about the return statement and have tried it. System.exit(0) also does the same. But using it here terminates the program. Is there any way i can use so that if the user types other input except 1-7 , the program doesn't terminate , so that i don't have to recompile and rerun the program ? Or is it not possible in Java ?
import java.util.Scanner;
public class NewShoppingCart{
public static void main(String args[]) {
boolean flag = true;
long code;
String choice;
NewShop aShop = new NewShop();
Scanner sc = new Scanner(System.in);
Integer parse = 0;
System.out.println("-----ITEM------");
do {
System.out.println("1. Display all items");
System.out.println("2. Search items");
System.out.println("3. Add items to list");
System.out.println("4. Add items to cart");
System.out.println("5. Display cart");
System.out.println("6. Issue item");
System.out.println("7. Exit");
System.out.println("Choice:");
choice = sc.nextLine();
try{
parse = Integer.parseInt(choice);
}
catch(Exception e){
System.out.println("Please enter a valid integer");
return;
}
if (parse >=1 && parse <= 7 )
{
switch (parse) {
case 1:
aShop.display();
break;
case 2:
aShop.searchItem();
break;
case 3:
aShop.addItem();
break;
case 4:
aShop.addItemtoCart();
break;
case 5:
aShop.displayCart();
break;
case 6:
aShop.issueItem();
break;
case 7:
System.out.println("Thank you!\n");
flag = false;
break;
default :
System.out.println("Please enter choice relevant to context");
}
}
else return;
}
while (flag != false);
sc.close();
}
}
Change this
catch(Exception e){
System.out.println("Please enter a valid integer");
return;
}
to
catch(Exception e){
System.out.println("Please enter a valid integer");
continue;
}
also in your else block have continue instead of return.
You can never go out of main with just one thread. This is likely an XY problem. What you really want is to go back to the start of the loop if the user inputs something invalid.
The continue keyword will stop executing the current iteration of the enclosing loop and start a new iteration immediately. This is what you should use in place of return.
try{
parse = Integer.parseInt(choice);
}
catch(Exception e){
System.out.println("Please enter a valid integer");
return; // <--- change this to "continue;"
}
Also, this:
if (parse >=1 && parse <= 7 )
{
switch (parse) {
case 1:
aShop.display();
break;
case 2:
aShop.searchItem();
break;
case 3:
aShop.addItem();
break;
case 4:
aShop.addItemtoCart();
break;
case 5:
aShop.displayCart();
break;
case 6:
aShop.issueItem();
break;
case 7:
System.out.println("Thank you!\n");
flag = false;
break;
default :
System.out.println("Please enter choice relevant to context");
}
}
else return;
should really be:
if (parse >=1 && parse <= 7 )
{
switch (parse) {
case 1:
aShop.display();
break;
case 2:
aShop.searchItem();
break;
case 3:
aShop.addItem();
break;
case 4:
aShop.addItemtoCart();
break;
case 5:
aShop.displayCart();
break;
case 6:
aShop.issueItem();
break;
case 7:
System.out.println("Thank you!\n");
flag = false;
break;
}
}
else {
System.out.println("Please enter choice relevant to context");
continue;
}
The "Please enter choice relevant to context" message should really be printed in the else statement. Because in your if, you already checked whether parse is between 1 and 7, so in the switch, parse can't be anything else so the default branch is never reached. After you print the message, you continue; in order to go back to the start of the loop.

String/Case programing error

I was able to get invalid major when I put a letter that is not listed major, but if I put t2, I would only get invalid major and not (invalid major, sophomore). Can someone detect the code and tell me where I went wrong.
// Enter two characters
System.out.print("Enter two characters: ");
String status = in.next();
char major = Character.toUpperCase(status.charAt(0));
char year = status.charAt(1);
String courseName = "";
String yearName = "";
// majors
if (major == 'B' || major == 'I' || major == 'C')
{
switch(major)
{
case 'B':
courseName = "Biology"; break;
case 'C':
courseName = "Computer Science"; break;
case 'I':
courseName = "Information Technology"; break;
default:System.out.println("Invaild major"); break;
}
// year
switch(year)
{
case '1':
yearName = "Freshman"; break;
case '2':
yearName = "Sophmore"; break;
case '3':
yearName = "Junior"; break;
case '4':
yearName = "Senior"; break;
default: System.out.println("Invalid year status"); break;
}
System.out.printf("%s %s%n", courseName, yearName);
}
else{
System.out.printf("Invalid input.%n");
}
}
}
Remove:
if (major == 'B' || major == 'I' || major == 'C')
{
and
else{
System.out.printf("Invalid input.%n");
}
Your 'if statement' is preventing you from getting the desired output.

Switch statment within Loop not working correctly

New to Java and I'm having troubles with my code, it's a switch statement within a while loop. I like to use letters or "char" instead of numbered cases "int" and I have 'q' to quit. Thanks for your input. This is the main code.
import java.util.Scanner;
import java.util.*;
public class supraCritters {
public static void main(String [] arguments) {
Critter nastybat = new Critter();
nastybat.health = 100;
nastybat.mood = 50;
nastybat.hunger = 25;
System.out.println("Your critter has just been born,");
System.out.println("here are the stats of your critter.");
nastybat.checkStats();
System.out.println("\nPlease choose a letter");
System.out.println("[c]heck stats \n[f]eed \n[p]lay \n[r]ead \n[t]rain");
System.out.println("[q]uit");
Scanner sChoice = new Scanner(System.in);
char choice = ' ';
while (choice != 'q') {
switch (choice) {
case 'c':
nastybat.checkStats();
break;
case 'f':
nastybat.feed();
break;
case 'p':
nastybat.play();
break;
case 'r':
nastybat.read();
break;
case 't':
nastybat.train();
break;
case 'q':
System.out.println("good bye");
break;
default:
System.out.println("invalid entry");
break;
}
choice = sChoice.next().charAt(0);
}
}
}
When I enter corresponding letter the loop doesn't show Input method or repeat and 'q' does nothing. Default displays "invalid entry" before input.
Code edited and still have problems.
The input is taken only once, the first time! Therefore the loop always returns the same result. You should duplicate the getting input code inside the loop!
Scanner sChoice = new Scanner(System.in);
char choice = '';
while (choice != 'q') {
switch (choice) {
case 'c':
nastybat.checkStats();
break;
.
.
.
.
.
choice = sChoice.next().charAt(0);
The first line gets input for the first switch run, and the one inside the loop gets the rest.
UPDATE:
The choice = sChoice.next().charAt(0); should be place at the final of the loop, if not, as #proskor says, when user hits 'q' the program will return an 'invalid entry'.
I finished the code and it seems to work. Testing out the methods the object can use now.
Final
import java.util.Scanner;
import java.util.*;
public class supraCritters {
public static void main(String [] arguments) {
Critter nastybat = new Critter();
nastybat.health = 100;
nastybat.mood = 50;
nastybat.hunger = 25;
System.out.println("Your critter has just been born,");
System.out.println("here are the stats of your critter.");
nastybat.checkStats();
Scanner sChoice = new Scanner(System.in);
char choice = ' ';
while (choice != 'q') {
switch (choice) {
case 'c': case 'C':
nastybat.checkStats();
break;
case 'f': case 'F':
nastybat.feed();
break;
case 'p': case 'P':
nastybat.play();
break;
case 'r': case 'R':
nastybat.read();
break;
case 't': case 'T':
nastybat.train();
break;
case 'q': case 'Q':
System.out.println("good bye");
break;
default:
System.out.println("invalid entry");
break;
}
System.out.println("\nPlease choose a letter");
System.out.println("[c]heck stats \n[f]eed \n[p]lay \n[r]ead \n[t]rain");
System.out.println("[q]uit");
choice = sChoice.next().charAt(0);
}
}
}

sorting by first character

The question at hand is each policy No. is a string of 9 characters of which indicates the type of insurance policy
B for building policy
C for Contents Policy
L for Life policy
V for car policy
Each of the remaining 8 characters of the policy number is a decimal digit.
I have tried using charAt but somebody told me there was a slightly better way
public String getpolicyNo(String initpolicyNo) {
/**
* Access method to find the first character of the policy to then
* determine what type of policy it is.
*/
String b = "B";
String C = "C";
String L = "L";
String V = "V";
char c1 = b.charAt(0);
char c2 = C.charAt(0);
char c3 = L.charAt(0);
char c4 = V.charAt(0);
if (c1 == 0) {
System.out.println("Its building" + c1);
return initpolicyNo;
} else {
if (c2 == 0) {
System.out.println("Its Content");
return initpolicyNo;
} else {
if (c3 == 0) {
System.out.println("Its life");
return initpolicyNo;
} else {
if (c4 == 0) {
System.out.println("Its car");
return initpolicyNo;
}
}
}
}
throw new IllegalArgumentException();
}
I'm not looking for you to provide an answer for me, I'm just looking for any possible alternatives and possible suggestions.
Many thanks
Dan
I'm not really sure what you are trying to achieve, but I would write this way:
public String getpolicyNo(String initpolicyNo) {
switch(initPolicyNo.charAt(0))
{
case 'B':
System.out.println("Its building B");
return initpolicyNo;
case 'C':
System.out.println("Its building C");
return initpolicyNo;
case 'L':
System.out.println("Its building L");
return initpolicyNo;
case 'V':
System.out.println("Its building V");
return initpolicyNo;
}
throw new IllegalArgumentException();
}
I recommend you using an Enum. Each value for an Enum has an ordinal value, which you can sort by.
If you want to read an introduction to Enums, the following site will help: Enum Types - The Java Tutorials
enum Policy {
BUILDING_POLICY, CONTENTS_POLICY, LIFE_POLICY, CAR_POLICY
}
For each enum value, you can assign a custom value, with which you can sort.
public void whatItIs(String s){
if(s.length() < 1){
//-- nothing to see here ---
return;
}
//-- case insensitive --
char c = Character.toUpperCase(s.charAt(0));
switch(c){
case 'B':
//-- its a building !--
break;
case 'C':
//-- its a c........ !--
break;
case 'L':
//-- its a l........ !--
break;
case 'V':
//-- its a v........ !--
break;
default:
//-- its something else :(--
}
}
public String getpolicyNo(String initpolicyNo) {
switch (initpolicyNo.charAt(0)) {
case 'B':
System.out.println("Its building" );
break;
case 'C':
System.out.println("Its Content");
break;
case 'L':
System.out.println("Its life");
break;
case 'V':
System.out.println("Its car");
break;
default:
throw new IllegalArgumentException();
break;
}
return initpolicyNo;
}
You could add enums to your code, or you could use a switch statement instead of the if/else block you currently have:
char type = initpolicyNo.charAt(0);
switch (type) {
case 'B':
// do stuff
break;
case 'C':
// do stuff
break;
}
Note: I think you may have a problem in your code in that it seems to me you should be switching on the initpolicyNo, not the actual types?
I have tried using charAt but somebody told me there was a slightly
better way
there is no better way to get the first letter of a string than using charAt.
And rather than having lots of if's/switches and what not, get a bit more OOPs up side your head.
Map<Character, String> myMap = new HashMap<Character, String>() {{
put('B', "Its building");
put('C', "Its content");
put('L', "its life");
put('V', "its vehicle");
}} ;
public void iShouldBeDoingMyOwnWork(String initpolicyNo) {
System.out.println(myMap.get(initpolicyNo.charAt(0)));
}

Categories