Switch statment within Loop not working correctly - java

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);
}
}
}

Related

How can I make the program stop after entering a value from a user?

I am trying to write a program that receives the number of sides from the
user and determines the type of figure using switch structure and a while sentinel-controlled loop, but every time I get an infinite loop. How can that be fixed?
import java.util.Scanner;
public class P1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of sides:");
int s = input.nextInt();
while ( s!=-1)
{
switch (s)
{
case 1: System.out.println("Line");
break;
case 2:System.out.println("Angle");
break;
case 3:System.out.println("Triangle");
break;
case 4:System.out.println("Quadrilateral");
break;
case 5:System.out.println("Pentagon ");
break;
case 6:System.out.println("Hexagon");
break;
case 7:System.out.println("Heptagon");
break;
case 8:System.out.println("Octagon");
break;
case 9:System.out.println("Nonagon");
break;
case 10:System.out.println("Decagon");
break;
default: System.out.println("Enter a valid value:");
}
}
}
}
The while loop is written to continue as long as s!=-1; so you need to change s so that this expression is no longer true.

How to fix my do while loop in order to have the menu appear again and again until the user presses Letter 'Q'?

Here's my code:
import java.util.Scanner;
// I want to call the menu function in my driver class and in a do while loop .
public class Driver {
public static void main(String[] args) {
do {
Scanner scanner = new Scanner(System.in);
char choice = scanner.next().charAt(0);
} while (choice == 'Q');// How to exit the menue
}
static void createNewEmployee() {
System.out.println("What is the name of employee?");
}
static void process() {
char choice;
switch (choice) {
case 'N':
System.out.println("new employee");
createNewEmployee();
break;
case 'P':
System.out.println("Compute paychecks");
break;
case 'R':
System.out.println("Raise Wages ");
break;
case 'L':
System.out.println("List Employees ");
break;
default:
System.out.println("Error");
}
}
}
Change while (choice == 'q') into while (choice != 'q'). Think of it like "if the user presses anything apart from 'q', carry on".
I think this will help you!!
public static void main(String[] args) {
char choice;
do {
Scanner scanner = new Scanner(System.in) ;
System.out.print("Press Any Key: N -- New, P -- Paycheck, R -- Raise Wages,-- List Employee, Q -- Quit: ");
choice = scanner.next().charAt(0);
process(choice);
} while(choice !='Q');
}
static void process(char choice) {
switch (choice) {
case 'N':
System.out.println("new employee");
break;
case 'P':
System.out.println("Compute paychecks");
break;
case 'R':
System.out.println("Raise Wages ");
break;
case 'L':
System.out.println("List Employees ");
break;
case 'Q':
System.out.println("Thanks!!");
break;
default:
System.out.println("Error");
}
}

Java Program print student Grade

I wanna Write a program to print out the user's grade ("Excellent if grade is A, Very Good if grade is B, Good if grade is C, Fair if grade is D, Fail if grade is F"). using Switch Statement
But When User input a or b or c or d or f in lowercase Apply the Grade
I mean I wanna char = A or a Match the Grade "Excellent"
and char = B or b Match the Grade " Very Good " and so on
Thanks and I hope to Find a Quick Solution
I tried this But it doesn't Make anything
public static void main(String[] args)
{
char Grade = 'A';
switch (Grade)
{
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Very Good");
break;
case 'C':
System.out.println("Good");
break;
case 'D':
System.out.println("Fair");
break;
case 'F':
System.out.println("Fail");
break;
}
}
You have two ways:
Multiple case statements:
switch (Grade) {
case 'A':
case 'a':
System.out.println("Excellent");
break;
case 'B':
case 'b':
System.out.println("Very Good");
break;
case 'C':
case 'c':
System.out.println("Good");
break;
case 'D':
case 'd':
System.out.println("Fair");
break;
case 'F':
case 'f':
System.out.println("Fail");
break;
}
}
Converting the character to upper case:
char Grade = 'A';
Grade = Character.toUpperCase(Grade);
switch (Grade) {
...
}
You can simply covert the character entered by the user to either lower case or lower case and compare accordingly.

How to break out of loop when case is selected

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
}
}

DO.. WHILE.. with SWITCH menu

Here is a do..while loop with switch menu..
I am trying to make the user be able to return to the menu which is
System.out.println("Options: (C)reate, (R)ead, (W)rite, (L)ist, (S)ave or (E)xit. (*****)");
But after much trial and errors, I still cant get back to the main menu after choosing C, R, W, L or S.
Below is a short snippet of the codes..
do {
System.out.println("Options: (C)reate, (R)ead, (W)rite, (L)ist, (S)ave or (E)xit.
(*****)");
Scanner switchC = new Scanner(System.in);
System.out.println("Please enter your choice: ");
choice = switchC.next().charAt(0);
switch (Character.toUpperCase(choice)) {
case 'C':
System.out.println("C");
break;
case 'R':
break;
case 'W':
break;
case 'L':
break;
case 'S':
break;
case 'E':
System.exit(1);
default:
System.out.println("Options: (C)reate, (R)ead, (W)rite, (L)ist, (S)ave or (E)xit. (*****)");
}
} while(choice!='E');
try
do{
}
while(Character.toUpperCase(choice) !='E')

Categories