I am trying to validate switch case statement to make sure user do not enter any character or string types. How do i achieve that? I have been trying using while statement but i am unable to validate it.
public static boolean showMenu()
{
// Print welcome message
System.out.println("\nApplication Menu : ");
System.out.println("[1] Help");
System.out.println("[2] Add");
System.out.println("[3] Subtract");
System.out.println("[4] Multiply");
System.out.println("[5] Divide");
System.out.println("[6] Quit");
int SelectMenu = jin.nextInt();
switch(SelectMenu)
{
case 1:
showChoice();
break;
case 2:
add();
break;
case 3:
subtract();
break;
case 4:
multiply();
break;
case 5:
divide();
break;
case 6:
return false;
}
return true;
}
You can use a loop as follows :
String line = jin.nextLine();
while(!line.matches("\\d")){
System.out.println("Nope, please enter a digit");
line = jin.nextLine();
}
int selectMenu = Integer.parseInt(line);
Take a look at this simple example and adapt it to your code:
/**
*
* #author Momir Sarac
*/
public class SwitchExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("\nApplication Menu : ");
System.out.println("[1] Help");
System.out.println("[2] Add");
System.out.println("[3] Subtract");
System.out.println("[4] Multiply");
System.out.println("[5] Divide");
System.out.println("[6] Quit");
while (!scanner.hasNextInt()) scanner.next();
int number = scanner.nextInt();
switch (number) {
case 1:
clickedHelp();
break;
case 2:
clickedAdd();
break;
case 3:
clickedSubtract();
break;
case 4:
clickedMultiply();
break;
case 5:
clickedDivide();
break;
default:
clickedSomething();
}
}
public static void clickedHelp(){
System.out.println("Help!");
}
public static void clickedAdd(){
System.out.println("Add");
}
public static void clickedSubtract(){
System.out.println("Subtract");
}
public static void clickedMultiply(){
System.out.println("Multiply");
}
public static void clickedDivide(){
System.out.println("Divide");
}
public static void clickedSomething(){
System.out.println("Exit");
System.exit(0);
}
}
Hope you need to do something like this
public static boolean showMenu()
{
while(true) {
// Print welcome message
System.out.println("\nApplication Menu : ");
System.out.println("[1] Help");
System.out.println("[2] Add");
System.out.println("[3] Subtract");
System.out.println("[4] Multiply");
System.out.println("[5] Divide");
System.out.println("[6] Quit");
int SelectMenu = jin.nextInt();
switch(SelectMenu)
{
case 1:
showChoice();
break;
case 2:
add();
break;
case 3:
subtract();
break;
case 4:
multiply();
break;
case 5:
divide();
break;
case 6:
return false;
}
}
}
Related
So I was working on a project for university, and I decided to use the classic do-while loop with a switch case in it to make a selector menu, but I want it instead of it asking the user for another case immediately after performing one, I want kind of like a back menu button, I searched the web but couldn't find a similar question to mine.
I included my code down below, so for example if I chose case 1, it will print "case 1" and then reprint the menu, but I want it to hold until the user enter an input then it will loop to the menu again.
Any help would be appreciated and thank you in advance.
My code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean repeat = true;
int operator;
do {
System.out.println("1 - menu");
System.out.println("2 - menu");
System.out.println("3 - menu");
System.out.println("4 - menu");
System.out.println("5 - menu");
System.out.println("Enter the Menu Number you want to Enter: ");
operator = input.nextInt();
switch (operator) {
case 1:
System.out.println("case 1");
break;
case 2:
System.out.println("case 2");
break;
case 3:
System.out.println("case 3");
break;
case 4:
System.out.println("case 4");
break;
case 5:
System.out.println("Exiting in process...");
System.exit(0);
break;
default:
System.out.println(operator + " is not a valid Menu Option! Please Select Another.");
break;
}
} while (operator != 5);
input.close();
}
}
Here is the answer to your question:
import java.util.Scanner;
// Import java.util for TimeUnit
import java.util.concurrent.TimeUnit;
public class Main {
// Create the wait function
public static void wait(int ms){
try {
Thread.sleep(ms);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean repeat = true;
int operator;
do {
System.out.println("1 - menu");
System.out.println("2 - menu");
System.out.println("3 - menu");
System.out.println("4 - menu");
System.out.println("5 - menu");
System.out.println("Enter the Menu Number you want to Enter: ");
operator = input.nextInt();
switch (operator) {
case 1:
System.out.println("case 1");
/** Add wait(3000); to every line! This will allow
the code to hold 3 seconds before returning back to the menu**/
wait(3000);
break;
case 2:
System.out.println("case 2");
wait(3000);
break;
case 3:
System.out.println("case 3");
wait(3000);
break;
case 4:
System.out.println("case 4");
wait(3000);
break;
case 5:
System.out.println("Exiting in process...");
wait(1000);
System.exit(0);
break;
default:
System.out.println(operator + " is not a valid Menu Option! Please Select Another.");
wait(3000);
break;
}
} while (operator != 5);
input.close();
}
}
I used a TimeUnit util to create a wait function. This wait function works as:
wait(int ms)
I have created a display menu and want to add a loop to continuously display the menu until the last option is selected. Not sure if I am doing it right.
Let me know if there is anywhere I can add on thanks!
import java.util.Scanner;
public class loopTest
{
public void displayMenu()
{
System.out.println("A. Option #A");
System.out.println("B. Option #B");
System.out.println("C. Option #C");
System.out.println("D. Option #D");
System.out.println("X. Exit");
System.out.println("Please enter your choice: ");
}
public void start()
{
Scanner console = new Scanner(System.in);
String s = "";
while(s < size())
{
displayMenu();
console.nextLine();
switch (s.charAt(0))
{
case 'A': System.out.println("A. Option #A"); break;
case 'B': System.out.println("B. Option #B"); break;
case 'C': System.out.println("C. Option #C"); break;
case 'D': System.out.println("D. Option #D"); break;
case 'X': System.out.println("X. Exit"); break;
default: System.out.println("Error, please enter a valid
character");
}
}
s++;
}
}
consider using a boolean variable
boolean wantToExit = false;
while (!wantToExit ) {
.... // switch
case 'X':
wantToExit = true;
System.out.println("X. Exit");
break;
}
note
s is a string, there is no < comparator nor s++ incrementor
Also, you are not assign a value to s from the Console input
I'm trying to code simple calculator (all in one) using Switch cases in java. I came up with following code so far. However I'm stuck with while loop. I want to keep showing main menu after each case execution until user decides to exit the program.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result=0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is "+result);
}
}
Above code works fine. Program ends itself after execution of user selected choice. I want to put main menu on a repeat.
Add a while loop like this:
public static void main(String[] args) {
// Moved this outside the while loop as davidxxx pointed out +1
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i = s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;//'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is " + result);
System.out.println("Go again?");
String goAgain = s.next();
if (!goAgain.equals("y")) {
break;
}
}
}
Try this:
import java.util.Scanner;
public class Calculator {
private static final String EXIT = "EXIT";
public static void main(String[] args) {
Calculator calc = new Calculator();
Scanner s = new Scanner(System.in);
while (true) {
String res = calc.runCalc(s);
if (res.equals(EXIT)) {
break;
} else {
System.out.println(res);
}
}
}
private String runCalc(Scanner s) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.println("Enter your choice: ");
int i = s.nextInt();
if (i == 5) {
return EXIT;
}
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;// 'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
return "Wrong Choice.";
}
return "Answer is " + result;
}
}
There is more than one way to achieve this, you can use
while loop.
do-while loop.
for loop.
I think do-while loop is better for your situation. Because either user wants to continue or not you have to proceed one time(before loop false). And you do not want to use another variable for quit the loop.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int result=0;
do{
System.out.println("Main Menu:");
System.out.println("-1. complete and calculate");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
if(i ==-1){
System.out.println("Answer is "+result);
return;
}
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
break;
}
}while(true);
}
Code:
public static void main(String args[]){
DBConnectionPool.ConnectionPool();
int scelta = 0;
Scanner sc = new Scanner(System.in);
for(;;) {
System.out.println("Selezionare il tipo di operazione da eseguire:");
System.out.println("1: Inserimento");
System.out.println("2: Modifica");
System.out.println("3: Cancellazione");
System.out.println("4: Altre");
System.out.println("5: Liste");
System.out.println("98: TEST");
System.out.println("99: Esci");
scelta = sc.nextInt();
sc.nextLine();
switch (scelta) {
case 1: opInserimento(sc);
break;
case 2: opModifica(sc);
break;
case 3: opCancella(sc);
break;
case 4: altreOp(sc);
break;
case 5: liste(sc);
break;
case 98: testSuite.testStart();
case 99:
System.out.println("Uscita");
sc.close();
return;
}
}
}
This cycle works for the first time, but after the selected method returns, once it gets to the nextInt() it throws NoSuchElementException. The inside of one of those methods (they're all the same pretty much)
static private void opInserimento(Scanner sc) {
int selezione = 0;
System.out.println("Selezionare l'operazione: ");
System.out.println("1: Inserisci allievo");
System.out.println("2: Inserisci corso");
System.out.println("3: Inserisci esame");
System.out.println("4: Inserisci gara");
System.out.println("5: Inserisci istruttore");
System.out.println("6: Inserisci lezione");
System.out.println("7: Inserisci sede");
System.out.println("8: Inserisci numero di telefono di un allievo");
System.out.println("9: Inserisci numero di telefono di un'istruttore");
System.out.println("99: Indietro");
selezione = sc.nextInt();
sc.nextLine();
switch(selezione) {
case 1: QueryInserimento.inserireAllievo();
break;
case 2: QueryInserimento.inserireCorso();
break;
case 3: QueryInserimento.inserireEsame();
break;
case 4: QueryInserimento.inserireGara();
break;
case 5: QueryInserimento.inserireIstruttore();
break;
case 6: QueryInserimento.inserireLezione();
break;
case 7: QueryInserimento.inserireSede();
break;
case 8: QueryUtenti.aggiungiTelefonoAllievo();
break;
case 9: QueryUtenti.aggiungiTelefonoIstruttore();
break;
case 99: return;
}
}
It's a sub-menu basically. If I skip the switch block the cycle works fine, so I'm assuming it must be a problem that happens in the sub-menu. Any ideas?
here is the method class
import java.util.Scanner;
public class Methods extends Basic {
Scanner keyboard = new Scanner(System.in);
public void Nome(){
String name = keyboard .nextLine();
System.out.println("what is your name");
switch(name){
case "john":
if(name.length() < 5){
System.out.println("your name is average");
break;
}
case "jason":
if(name.length()>5){
System.out.println("your name is not average");
break;
}
}
}
public void Dates(){
System.out.println("Enter a number and we will tell you what month it is:");
int jay = keyboard.nextInt();
switch(jay){
case 1:
System.out.println("january");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
default:
System.out.println("that aint in the month dawg");
}
}
}
and here is the main class
public class Basic {
public static void main(String args[]) {
Methods dateo = new Methods();
Methods nomalo = new Methods();
nomalo.Nome();
dateo.Dates();
}
}
so yea, I am a complete noob. and I am really struggling when learning Java :( A lot of my friends who started learning java can now make their own 2 games and here I am struggling with a basic concept...
so what is the problem in this code?
Edit - Forget what I said here. Your code is working fine aparently. Just put your
println before you make the scan.
System.out.println("what is your name");
String name = keyboard.nextLine();
So problems is you are reading the data from keyboard before you printed 'what is your name'
The Methods class does not need to extend Basic. the name method does not need to have switch case.
So the Methods class would look like below,
public class Methods {
Scanner keyboard = new Scanner(System.in);
public void name(){
System.out.println("what is your name");
String name = keyboard.nextLine();
if(name.length() < 5){
System.out.println("your name is average");
} else {
System.out.println("your name is not average");
}
}
public void Dates(){
System.out.println("Enter a number and we will tell you what month it is:");
int jay = keyboard.nextInt();
switch(jay){
case 1:
System.out.println("january");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
default:
System.out.println("that aint in the month dawg");
}
}
}