I have a homework to implement a simple testing application, below is my current code:
import java.util.*;
public class Test{
private static int typing;
public static void main(String argv[]){
Scanner sc = new Scanner(System.in);
System.out.println("Testing starts");
while(sc.hasNextInt()){
typing = sc.nextInt();
switch(typing){
case 0:
break; //Here I want to break the while loop
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
}
System.out.println("Test is done");
}
}
What I want to do now is that when 0 is pressed, it means that the user wants to quit the test, then I break the while loop and print Test is done, but it doesn't work like that, I know the reason might be that the "break" breaks the switch, how can I let it break the while loop instead?
You can label your while loop, and break the labeled loop, which should be like this:
loop: while(sc.hasNextInt()){
typing = sc.nextInt();
switch(typing){
case 0:
break loop;
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
}
And the label can be any word you want, for example "loop1".
You need a boolean variable e.g. shouldBreak.
boolean shouldBreak = false;
switch(typing){
case 0:
shouldBreak = true;
break; //Here I want to break the while loop
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
if (shouldBreak) break;
Put the while inside a function and when you press 0 instead of break just return. For example :
import java.util.*;
public class Test{
private static int typing;
public static void main(String argv[]){
Scanner sc = new Scanner(System.in);
func(sc);
System.out.println("Test is done");
}
}
public static void func(Scanner sc) {
System.out.println("Testing starts");
while(sc.hasNextInt()){
typing = sc.nextInt();
switch(typing){
case 0:
return; //Here I want to break the while loop
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
}
}
}
How to terminate inner menu ?
Example Code :
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //used to get input
int option1, option2 = 0;
boolean loop_terminate = true; //flag used to terminate inner while loop
//Main Menu
while (true) {
//Main Menu options
System.out.println("1.Option 1");
System.out.println("2.Option 2");
System.out.println("3.Option 3");
System.out.println("4.Option 4");
System.out.println("5.Exit main menu");
System.out.print("Please enter your choice : ");
option1 = input.nextInt();
switch (option1) {
case 1:
//do something here
break;
case 2:
//do something here
break;
case 3:
while (loop_terminate) {
//Inner menu options
System.out.println("1.Inner Menu option 1");
System.out.println("2.Inner Menu option 2");
System.out.println("3.Inner Menu option 3");
System.out.println("4.Return to Main Menu");
System.out.print("Please enter your choice : ");
option2 = input.nextInt();
switch (option2) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
loop_terminate = false; //this will terminate inner menu
break;
default:
System.out.println("Invalid option");
break;
}
}
break; //never forget to add this break statement
case 4:
break;
case 5:
return; //terminate outer menu
default:
System.out.println("Invalid option");
}
}
}
}
Related
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.
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");
}
}
I've looked at everything mentioned about this and if I make a do/while loop it will just repeat the selection. If I make them conditionals instead of a switch it gives me "NoSuchElementException: No line found". Now its also giving me a "NoSuchElementException: No line found" even though I am back to a switch. I just want to know what I'm missing in this code that will let the user back out their first selection (while loop) to make a different one. Here is the code:
public class Zoo {
static FileRead fr = new FileRead();
private static final Scanner scnr = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
while (true) {
int userChoice = menu();
while (userChoice == 1) {
// Select Animal
int animal = animalSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Animal - Lion";
break;
case 2:
Name = "Animal - Tiger";
break;
case 3:
Name = "Animal - Bear";
break;
case 4:
Name = "Animal - Giraffe";
break;
default:
userChoice = menu();
break;
} FileRead.readAnimal(Name);
}
while (userChoice == 2) {
// Select Habitat
int animal = habitatSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Habitat - Penguin";
break;
case 2:
Name = "Habitat - Bird";
break;
case 3:
Name = "Habitat - Aquarium";
break;
default:
userChoice = menu();
break;
}
FileRead.readHabitat(Name);
}
// Exit Program
if (userChoice == 3) {
System.out.println("Thank you!");
System.exit(0);
}
// Error for invalid option
else {
System.out.println("ERROR: Invalid Selection");
}
}
}
private static int habitatSelect() {
// Habitat Menu
System.out.println("Which habitat would you like to monitor?");
System.out.println("1. Penguin Habitat");
System.out.println("2. Bird Habitat");
System.out.println("3. Aquarium");
System.out.println("4. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
private static int animalSelect() {
// Animal Menu
System.out.println("Which animal would you like to monitor?");
System.out.println("1. Lion");
System.out.println("2. Tiger");
System.out.println("3. Bear");
System.out.println("4. Giraffe");
System.out.println("5. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
private static int menu() {
// Main Menu
System.out.println("WELCOME! Plese choose from the following");
System.out.println("1. Monitor Animal");
System.out.println("2. Monitor Habitat");
System.out.println("3. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
}
This all reads a from another file in the package. If that code is needed I will also post it.
Tweak your main method as below
public static void main(String[] args) throws FileNotFoundException {
while (true) {
int userChoice = menu();
switch (userChoice) {
case 1: // only for animals
int animal = animalSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Animal - Lion";
break;
case 2:
Name = "Animal - Tiger";
break;
case 3:
Name = "Animal - Bear";
break;
case 4:
Name = "Animal - Giraffe";
break;
default:
System.out.println("ERROR: Invalid Selection");
break;
}
if (Name != null) // read file only if selection is correct
FileReader.readAnimal(Name);
break;
case 2: // only for habitat
int habitat = habitatSelect();
String habitatName = null;
switch (habitat) {
case 1:
habitatName = "Habitat - Penguin";
break;
case 2:
habitatName = "Habitat - Bird";
break;
case 3:
habitatName = "Habitat - Aquarium";
break;
default:
System.out.println("ERROR: Invalid Selection");
break;
}
if (habitatName != null) // read file only if selection is correct
FileRead.readHabitat(habitatName);
break;
case 3 : // only for exit
System.out.println("Thank you!");
System.exit(0);
default:
System.out.println("ERROR: Invalid Selection");
}
}
}
Thus after each sub-menu, the user is returned to the main menu. As for your exception, for now I have added a null check so that the file is read only if the selection is correct.
Also, note that the above code doesn't contain nested loop which increases the performance and also excludes (the slightly messy) recursive call.
I'm trying to make a simple Menu with the switch statement. However i'm having a problem with the switch:
public class main {
public static void main(String[] args) throws IOException {
printMenu();
}
public static void printMenu() throws IOException{
char selection = 0;
do{
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
selection = (char)System.in.read();
switch(selection){
case '1':
System.out.printf("opt1 chosen\n");
break;
case '2':
System.out.printf("opt2 chosen\n");
break;
case '3':
break;
}
}
while(selection != '3');
}
}
For some reason, when selecting either one or two, the result is that print menu gets printed twice, like this:
Program output:
Choose option:
1. opt1.
2. opt2.
3. opt3.
1
opt1 chosen
Choose option:
1. opt1.
2. opt2.
3. opt3.
Choose option:
1. opt1.
2. opt2.
3. opt3.
The question is, what causes this problem?
When you press a number and <Enter> this is two characters not one. i.e. you are typing
1\n
This is unavoidable, but you can chose to parse the input differently with Scanner which handles this differently, or you can ignore it. (or you can expect the user must type a \n after a number...
As Peter pointed out, the problem arises because of the way you are reading the 'selection' input. You can correct the functionality as follows:
public class main {
public static void main(String[] args) throws IOException {
printMenu();
}
public static void printMenu() throws IOException {
char selection = '0';
while (selection != '3') {
if (selection != '\n') {
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
}
selection = (char) System.in.read();
switch (selection) {
case '1':
System.out.printf("opt1 chosen\n");
break;
case '2':
System.out.printf("opt2 chosen\n");
break;
case '3':
break;
default:
break;
}
}
}
}
Peter Lawrey is right
I'm suggest using Scanner class :
public static void printMenu() throws IOException {
Scanner scanner = new Scanner(System.in);
int selection = 0;
do{
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
selection = (char) scanner.nextInt();
switch(selection){
case 1:
System.out.printf("opt1 chosen\n");
break;
case 2:
System.out.printf("opt2 chosen\n");
break;
case 3:
break;
}
scanner.nextLine();
}
while(selection != '3');
}
I created a string vector and I want to store the selected type of coffee in the vector, for example if I choose number 3,4,5 and 1, store them in Vector1 the variables ("LATTE", "AMERICAN", "CAPUCCINO" and "MOKA") and print those stored names, but the problem is that it just prints, number 6 "BLACK", always.
import java.io.*;
class Exercise{
public static void main (String[] args) throws java.io.IOException {
DataInputStream receivedata= new DataInputStream(System.in);
String keyboard;
int seleccafe,n=0,contvector=0;
String []Vector1=new String[200];
do{
System.out.println("\n1. MOKA");
System.out.println("2. EXPRESO");
System.out.println("3. LATTE");
System.out.println("4. AMERICAN");
System.out.println("5. CAPUCCINO");
System.out.println("6. BLACK");
System.out.println("0. OUT");
System.out.print("\nTYPE THE NUMBER: ");
seleccafe=Read_Da("");
SelectCo(Vector1,seleccafe,n);
contvector++;
n++;
if(seleccafe==0) break;
}while(true);
for(int i=0; i<contvector-1; i++){
System.out.println(Vector1[i]);
}
}
public static int Read_Da (String TxtMsg) throws java.io.IOException{
int X=0;
String keyboard;
DataInputStream reveivedata= new DataInputStream(System.in);
do{
System.out.print("");
keyboard=reveivedata.readLine();
try{
X=Integer.parseInt(keyboard);
if(X<0){
System.out.println("SELECT JUST 0+");
continue;
}
return X;
}catch(NumberFormatException e){
System.out.println("JUST NUMBERS");
}
}while(true);
}
public static void SelectCo(String xVector[], int xseleccafe, int xi){
switch(xseleccafe){
case 1:
xVector[xi]= "MOKA";
case 2:
xVector[xi]="EXPRESSO";
case 3:
xVector[xi]="LATE";
case 4:
xVector[xi]="AMERICAN ";
case 5:
xVector[xi]="CAPUCCINO";
case 6:
xVector[xi]="BLACK";
}
}
}
Any help? Thanks!
Your problem is that you are missing the word break; after each case clause in SelectCo, so each case is "falling through" to the one below, and finishing with case 6:.
It should look like this.
switch(xseleccafe){
case 1:
xVector[xi]= "MOKA";
break;
case 2:
xVector[xi]="EXPRESSO";
break;
case 3:
xVector[xi]="LATE";
break;
case 4:
xVector[xi]="AMERICAN ";
break;
case 5:
xVector[xi]="CAPUCCINO";
break;
case 6:
xVector[xi]="BLACK";
break;
default:
xVector[xi]="UNKNOWN";
}
More detail here