How to do a switch menu in java with do while - java

Good day!
This is my switch menu for a project in java!
When I put a diferent letter (letter that it´s not in the switch) I get this error message, and when I try one of the correct letter I get the same error message again:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at teste.menu(teste.java:65)
at teste.main(teste.java:16)
This is my code:
import java.util.Scanner;
public class teste{
public static void main(String[] args){
char ch;
do {
ch = menu();
switch (ch){
case 'a':
//String name ="resultado.csv";
//ReadFile(name);
break;
case 'b':
//WriteFile();
break;
case 'c':
System.out.println("nome");
break;
case 'd':
System.out.println("nome");
break;
case 'e':
System.out.println("nome");
break;
case 'f':
System.out.println("nome");
break;
case 'g':
System.out.println("nome");
break;
case 'h':
System.out.println("nome");
break;
default:
System.out.println("a-k!");
break;
}
}while (ch != 'k');
System.exit(0);
}
public static char menu(){
System.out.println("Chose: ");
System.out.println("a: Show");
System.out.println("b: Write");
System.out.println("c: All Numbers Are the Same");
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("g: Display");
System.out.println("h: Display");
System.out.println("k: Quit");
System.out.println("Insira a opção: ");
Scanner input = new Scanner(System.in);
char ch = input.next().charAt(0);
input.close();
return ch;
}
}
I tryed with numbers and I got the same error message

Don't recreate the scanner each time menu is called. Create it once at start of main and use it, such as:
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// same code...until end of main...
input.close();
System.exit(0);
}
and in menu:
public static char menu() {
// same prompts...
//REMOVE Scanner input = new Scanner(System.in);
char ch = input.next().charAt(0);
//REMOVE input.close();
return ch;
}

Related

Switch Case Validation

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

Use switch case within while loop

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

Query related input of char/int

I'm not able to understand that why is the compiler just shows running(which is forever) when I change char to int in this program. By changing I mean using just int to take the option number and hence using int numbers itself in switch.
This one is normal char 1 which is working-
public static void main(String args[])
throws java.io.IOException{
char option; int i=0;
do{
if(i==1)
System.out.println("\nNotice: Wrong option chosen, pick again.");
i=1;
System.out.println("Help on:");
System.out.println("1. if");
System.out.println("2. switch");
System.out.println("3. while");
System.out.println("4. do-while");
System.out.println("5. for");
System.out.println("Pick any option for brief informatrion.");
option= (char)System.in.read();
}while(option<'1' || option>'5');
switch(option){
case '1':
System.out.println("The If:\n");
System.out.println("If(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The Switch:\n");
System.out.println("switch(expression){");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The While:\n");
System.out.println("while(condition statement;)");
break;
case '4':
System.out.println("The Do-While:\n");
System.out.println("do{");
System.out.println(" statement;");
System.out.println("}while(condition);");
break;
case '5':
System.out.println("The For:\n");
System.out.println("for(init; condition; iteration){");
System.out.println(" statement;");
System.out.println("}");
break;
}
}
}
This is int 1 which just keeps running forver
public static void main(String args[])
throws java.io.IOException{
int option; int i=0;
do{
if(i==1)
System.out.println("\nNotice: Wrong option chosen, pick again.");
i=1;
System.out.println("Help on:");
System.out.println("1. if");
System.out.println("2. switch");
System.out.println("3. while");
System.out.println("4. do-while");
System.out.println("5. for");
System.out.println("Pick any option for brief informatrion.");
option= System.in.read();
}while(option<1 || option>5);
switch(option){
case 1:
System.out.println("The If:\n");
System.out.println("If(condition) statement;");
System.out.println("else statement;");
break;
case 2:
System.out.println("The Switch:\n");
System.out.println("switch(expression){");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case 3:
System.out.println("The While:\n");
System.out.println("while(condition statement;)");
break;
case 4:
System.out.println("The Do-While:\n");
System.out.println("do{");
System.out.println(" statement;");
System.out.println("}while(condition);");
break;
case 5:
System.out.println("The For:\n");
System.out.println("for(init; condition; iteration){");
System.out.println(" statement;");
System.out.println("}");
break;
}
}
}
See https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read%28%29
The System.in.read return an int represent for character.
Let's say you type 1, it will read as 49.
And if you use file to be stdin when it reach EOF it will return -1
Even if the char version, the same error happens.
See this demo: https://ideone.com/Q83qxn

Initialize An Array of Ints with Variables

I want to make an array of integer values that represent counters so I initialized it like this in my main method:
int [] counters = new int [7];
counters [countListAll] = 0;
counters [countEmployeeReport] = 0;
counters [countDivisionReport] = ;
counters [countSalaryReport] = 0;
counters [countRetirementReport] = 0;
counters [countMain] = 0;
counters [countOthers] = 0;
And now I have to pass this array to my menu() method so that I can increment each counter each time any of the options is chosen.
public static void menu(int [] counters)
{
System.out.println("You have accessed Menu()");
System.out.println("Enter 'L' for list of the employee data available. \nEnter 'E' to dislpay information on a particular employee. \nEnter 'D' to display division information. \nEnter 'S' to display salary information. \nEnter 'R' to display retirement information. \nEnter 'Q' to quit Menu and return to Main.");
Scanner scan = new Scanner(System.in);
String first = scan.next();
char first1 = first.charAt(0);
if (first1 == 'L'|| first1 =='l'||first1 =='E'||first1 =='e'||first1 =='D'||first1 =='d'||first1 =='S'||first1 =='s'||first1 =='R'||first1 =='r'||first1 =='Q'||first1 =='q')
{
switch (first1)
{
case 'L':
case 'l':
listAll();
counters [countListAll] ++;
break;
case 'E':
case 'e':
employeeReport();
counters [countEmployeeReport] ++;
break;
case 'D':
case 'd':
divisionReport();
counter [countDivisionReport] ++;
break;
case 'S':
case 's':
salaryReport();
counters [countSalaryReport] ++;
break;
case 'R':
case 'r':
retirementReport();
counters [countRetirementReport] ++;
break;
case 'Q':
case 'q':
counters [countMain] ++;
break;
else
{
menu();
countOthers++;
}
}
Am I initializing the array correctly and passing it into menu() method correctly? And am I allowed to increment the objects like that?
EDIT: I changed the code, and this is the new code
Main method:
int [] counters = new int [7];
counters [L] = 0;//listAll
counters [E] = 0;//employeeReport
counters [D] = 0;//divisionReport
counters [S] = 0;//salaryReport
counters [R] = 0;//retirementReport
counters [Q] = 0;//quit
counters [O] = 0;//others
Menu Method:
public static void menu(int [] counters)
{
System.out.println("You have accessed Menu()");
System.out.println("Enter 'L' for list of the employee data available. \nEnter 'E' to dislpay information on a particular employee. \nEnter 'D' to display division information. \nEnter 'S' to display salary information. \nEnter 'R' to display retirement information. \nEnter 'Q' to quit Menu and return to Main.");
Scanner scan = new Scanner(System.in);
String first = scan.next();
char first1 = first.charAt(0);
if (first1 == 'L'|| first1 =='l'||first1 =='E'||first1 =='e'||first1 =='D'||first1 =='d'||first1 =='S'||first1 =='s'||first1 =='R'||first1 =='r'||first1 =='Q'||first1 =='q')
{
switch (first1)
{
case 'L':
case 'l':
listAll();
counters [L] ++;
break;
case 'E':
case 'e':
employeeReport();
counters[E]++;
break;
case 'D':
case 'd':
divisionReport();
counters [D]++;
break;
case 'S':
case 's':
salaryReport();
counters [S]++;
break;
case 'R':
case 'r':
retirementReport();
counters [R]++;
break;
case 'Q':
case 'q':
counters [Q]++;
break;
}
}
else
{
menu();
counters [O]++;
}
}
And FinalStats Method:
public static void finalStats(int [] counters)
{
System.out.println("Number of times listAll() was accessed from menu() is: " + counters[L]);
System.out.println("Number of times employeeReport() was accessed from menu() is: " + counters[E]);
System.out.println("Number of times divisionReport() was accessed from menu() is: " + counters[D]);
System.out.println("Number of times salaryReport() was accessed from menu() is: " + counters[S]);
System.out.println("Number of times retirementReport() was accessed from menu() is: " + counters[R]);
System.out.println("Number of times 'Quit' was chosen from menu() is: " + counters[Q]);
System.out.println("Number of times any other key was pressed in menu() is: " + counters[O]);
}
Yes, in general. There appears to be a bug with your countOthers logic. although nesting a switch with-in an if seems an odd choice, it would be much more readable with a simple if else-if chain (and you could use Character.toLowerCase(char) to handle mixed case. Something like,
if-else
public static void menu(int[] counters) {
System.out.println("You have accessed Menu()");
System.out.println("Enter 'L' for list of the employee data available.");
System.out.println("Enter 'E' to dislpay information on a particular employee.");
System.out.println("Enter 'D' to display division information.");
System.out.println("Enter 'S' to display salary information.");
System.out.println("Enter 'R' to display retirement information.");
System.out.println("Enter 'Q' to quit Menu and return to Main.");
Scanner scan = new Scanner(System.in);
String first = scan.next();
char first1 = Character.toLowerCase(first.charAt(0));
if (first1 == 'l') {
listAll();
counters[countListAll]++;
} else if (first1 == 'e') {
employeeReport();
counters[countEmployeeReport]++;
} else if (first1 == 'd') {
divisionReport();
counter[countDivisionReport]++;
} else if (first1 == 's') {
salaryReport();
counters[countSalaryReport]++;
} else if (first1 == 'r') {
retirementReport();
counters[countRetirementReport]++;
} else if (first1 == 'q') {
counters[countMain]++;
} else {
menu();
counters[countOthers]++; // <-- instead of countOthers++
}
}
switch-case
It is also possible to express the above if-else chain with switch-case and something like,
switch (Character.toLowerCase(first.charAt(0))) {
case 'l':
listAll();
counters[countListAll]++;
break;
case 'e':
employeeReport();
counters[countEmployeeReport]++;
break;
case 'd':
divisionReport();
counter[countDivisionReport]++;
break;
case 's':
salaryReport();
counters[countSalaryReport]++;
break;
case 'r':
retirementReport();
counters[countRetirementReport]++;
case 'q':
counters[countMain]++;
break;
default:
menu();
countOthers++;
}

How to take character input in java

In C, we are able to take input as character with the keyword char from keyboard as
scanf("%c", &ch);
But In Java how to do this?
I have tried this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a character: ");
char c = scanner.next().charAt(0);
System.out.println("You have entered: "+c);
}
}
you can use a Scanner to read from input :
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0); //charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.
You can simply use (char) System.in.read(); casting to char is necessary to convert int to char
import java.util.Scanner;
class SwiCas {
public static void main(String as[]) {
Scanner s= new Scanner(System.in);
char a=s.next().charAt(0);//this line shows how to take character input in java
switch(a) {
case 'a':
System.out.println("Vowel....");
break;
case 'e':
System.out.println("Vowel....");
break;
case 'i':
System.out.println("Vowel....");
break;
case 'o':
System.out.println("Vowel....");
break;
case 'u':
System.out.println("Vowel....");
break;
case 'A':
System.out.println("Vowel....");
break;
case 'E':
System.out.println("Vowel....");
break;
case 'I':
System.out.println("Vowel....");
break;
case 'O':
System.out.println("Vowel....");
break;
case 'U':
System.out.println("Vowel....");
break;
default:
System.out.println("Consonants....");
}
}
}
use the System class
char yourChar = System.in.read()
Here is the sample program.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadFromConsole {
public static void main(String[] args) {
System.out.println("Enter here : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String value = bufferRead.readLine();
System.out.println(value);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
You can get it easily when you search in Internet. StackExchange recommends to do some research and put some effort before reaching it.
using java you can do this:
Using the Scanner:
Scanner reader = new Scanner(System.in);
String line = reader.nextLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast
Using the BufferedReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast
In the two cases you need to pass you Default input, in my case System.in
use :
char ch=**scanner.nextChar**()
I had the same struggle and I this is what I used:
} public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter the string: ");
String input = scan.next();
System.out.print("Please enter the required symbol: ");
String symbol = scan.next();
char symbolChar = symbol.charAt(0);
This works just fine.
The idea is to get from the string the only char in it.
import java.util.Scanner;
class CheckVowel {
public static void main(String args[]) {
Scanner obj= new Scanner(System.in);
char a=obj.next().charAt(0);
switch(a) {
case 'a': //cases can be used together for the same statement
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
{
System.out.println("Vowel....");
break;
}
default:
System.out.println("Consonants....");
}
}
}
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a character:");
String str = next();
char c = str.charAt(0);
System.out.println(c);
sc.close();
}
[Output of this program.][1]}

Categories

Resources