Switch cases are not getting executed properly - java

case 1 and default cases are not working properly print statement is not getting executed. I'm unable to identify the error. I don't know if there is problem with the scanner implementation it seems fine to me.
import java.util.*;
public class StartApp {
public static void main(String[] args) {
try {
String categoryName="";
int ch=0;
Scanner sc1=new Scanner(System.in);
Scanner sc2=new Scanner(System.in);
Logger.getInstance().log("Starting task manager", 1);
while(ch!=7)
{
System.out.println("press 1 to create category");
System.out.println("press 2 to load category");
System.out.println("press 3 to remove catergory");
System.out.println("press 4 to list category");
System.out.println("press 5 to search category");
System.out.println("press 6 to export");
System.out.println("press 7 to exit");
ch=sc1.nextInt();
}
switch(ch)
{
case 1:{
System.out.println("enter category name");
categoryName=sc2.nextLine();
sc2.nextLine();
while(!ProjectUtility.validateName(categoryName))
{
System.out.println("category name must be one word. It cannot contain a numbers,spaces and Alpanumerics.");
categoryName=sc2.nextLine();
}
break;}
case 7:
System.out.println("exiting...");
break;
default:
System.out.println("option not supported");
break;
}
}
catch(Throwable t)
{
t.printStackTrace();
}
}
}

You will only get out of your while loop if the condition while(ch!=7){...} turns false. So your switch label '7' is the only reachable in the whole switch. The Solution is to put your switch in your while loop.
You only need one Scanner and you should close it at the end
public static void main(String[] args) {
try {
String categoryName = "";
int ch = 0;
Scanner sc = new Scanner(System.in);
Logger.getInstance().log("Starting task manager", 1);
while (ch != 7) {
System.out.println("press 1 to create category");
System.out.println("press 2 to load category");
System.out.println("press 3 to remove catergory");
System.out.println("press 4 to list category");
System.out.println("press 5 to search category");
System.out.println("press 6 to export");
System.out.println("press 7 to exit");
System.out.println();
System.out.print("input: ");
ch = sc.nextInt();
switch (ch) {
case 1: {
System.out.print("enter category name: ");
categoryName = sc.nextLine();
sc.nextLine();
while (!ProjectUtility.validateName(categoryName)) {
System.out.println("category name must be one word. It cannot contain a numbers,spaces and Alpanumerics.");
System.out.print("enter category name: ");
categoryName = sc.nextLine();
}
break;
}
case 7:
System.out.println("exiting...");
break;
default:
System.out.println("option not supported");
break;
}
}
sc.close();
} catch (Throwable t) {
t.printStackTrace();
}
}

Related

Java if else with nested loop

I am having some problem with my java assignment and currently am stuck at the nested if else statement.I am actually trying to get an input age from the user and store in as a variable.After executing my code i am getting error when i run the program.Am i doing this correctly or is there some other way to program this?
Error message that i got
Enter your selection:
1
You have selected No.1
Please enter your age**Exception in thread "main"
java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Assignment.main(Assignment.java:48)**
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println(
"1. Add player" + "\n" +
"2.Display transaction" + "\n" +
"3.Begin the ride");
System.out.println("");
System.out.println("Enter your selection: ");
char selection = sc.findInLine(".").charAt(0);
sc.close();
switch(selection) {
case '1' :
System.out.println("You have selected No.1");
break;
case '2' :
System.out.println("You have selected No.2" );
break;
case '3' :
System.out.println("You have selected No.3" );
break;
default:
System.out.println("Please make a selection");
break;
}
if (selection=='1') {
int age=0;
System.out.print("Please enter your age");
age = sc.nextInt();
while (age<100) {
age+=age;
}
}
else if (selection=='2') {
System.out.println("Display daily transaction");
}
else if (selection=='3') {
System.out.println("Begin the ride");
}
else {
System.out.println("Please enter a valid input");
}
}
Please read basic Java so that you can learn programs better.
you can reduce this code to a very good extent, i haven't removed nested-if statements, which you can by moving all execution under case statements.
This program will terminate if option entered is not a number, this can also be improved by reading it as a string and checking is its one of the valid options (map's key set).
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class SwitchCase {
public static Map<Integer, String> options = new LinkedHashMap<Integer, String>();
static {
options.put(1, "Add player");
options.put(2, "Display transaction");
options.put(3, "Begin the ride");
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
for (Integer option : options.keySet()) {
System.out.println(option + ". " + options.get(option));
}
System.out.println("Enter your selection: ");
int selection = sc.nextInt();
switch (selection) {
case 1:
case 2:
case 3:
System.out.println("You have selected No." + selection);
break;
default:
System.out.println("Please make a selection");
break;
}
if (selection == 1) {
int age = 0;
System.out.print("Please enter your age : ");
age = sc.nextInt();
while (age < 100) {
age += age;
}
System.out.println(age);
} else if (selection == 2) {
System.out.println(options.get(selection));
} else if (selection == 3) {
System.out.println(options.get(selection));
} else {
System.out.println("Please enter a valid input!");
}
}
}
switch case is a type of nested if else.we can use switch in place of nested if else.you need not to use both switch case and nested if else simultaneously.
you can write your code like this.
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("1. Add player" + "\n" +
"2.Display transaction" + "\n" +
"3.Begin the ride");
System.out.println("");
System.out.println("Enter your selection: ");
char selection = sc.findInLine(".").charAt(0);
switch(selection) {
case '1' :
System.out.println("You have selected No.1");
int age=0;
System.out.print("Please enter your age");
age = sc.nextInt();
while (age<100) {
age+=age;
}
System.out.print(age);
break;
case '2' :
System.out.println("You have selected No.2" );
System.out.println("Display daily transaction");
break;
case '3' :
System.out.println("You have selected No.3" );
System.out.println("Begin the ride");
break;
default:
System.out.println("Please make a selection");
System.out.println("Please enter a valid input");
break;
}
sc.close();
}
The exception is pretty clear on the problem: java.lang.IllegalStateException: Scanner closed
Before your code enters the switch, you're closing the scanner with sc.close();. But later on you're trying to read from it again:
if (selection=='1') {
int age=0;
System.out.print("Please enter your age");
age = sc.nextInt(); // <---- Here
while (age<100) {
age+=age;
}
}
But this will fail if the scanner is already closed. To solve this, you can simply put the line sc.close() to the end of your main.
As an alternative you could wrap everything into a try-with-resources block, so that you don't have to care about closing the scanner anymore because it will be closed automatically after leaving the block.

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

switch case in implementation of stack using array in java

import java.io.*;
import java.util.*;
public class Stack1{
static final int MAX=100;
int top=-1;
int[] stack=new int[MAX];
public static void main(String args[])
{
Stack1 s1=new Stack1();
int opt, val;
System.out.println("1. PUSH ");
System.out.println("2. POP ");
System.out.println("3. PEEP ");
System.out.println("4. DISPLAY STACK ");
System.out.println("5. EXIT ");
System.out.println("\n Enter Your Option: ");
Scanner s=new Scanner(System.in);
opt=s.nextInt();
do{
switch(opt)
{
case 1: System.out.println("Enter the value to be added to the stack: ");
val=s.nextInt();
s1.push(val);
break;
case 2: s1.pop();
break;
/*
case 3: s1.peep();
break; */
case 4: s1.display();
break;
}
}while(opt!=5);
}
public void push(int val)
{
if(top==MAX-1)
{
System.out.println("Stack is FULL!");
}
else
{
top++;
stack[top]=val;
System.out.println("Element added to the stack is: "+val);
display();
}
}
public void pop()
{
int x;
if(top==-1)
{
System.out.println("Stack is EMPTY!");
}
else
{
x=stack[top];
System.out.println("The element deleted from the stack is: "+x);
top--;
display();
}
}
public void peep()
{
int n;
n=stack[top];
System.out.println("The value at the top of the stack is: "+n);
}
public void display()
{
int i;
if(top==-1)
System.out.println("STACK IS EMPTY!");
else
{
for(i=0; i<=top; i++)
System.out.println("The elements in the stack are: "+stack[i]);
}
}
}
I wrote this java code to implement stack. But once I select any option, only that method gets executed and the program ends. I want the program to provide me to enter another option once the current method is executed. What should I do?
As #LordWilmore pointed out in his comment, the opt value will be set just once causing program to spin forever in a corresponding case (unless the value is 5). Moving opt = s.nextInt(); inside loop will fix the issue.
do {
System.out.println("Enter Your Option: ");
opt = s.nextInt();
switch(opt) {
//...
}
} while (opt != 5);
You can modify your main method in a manner like this:
public static void main(String args[]){
int option;
Scanner sc = new Scanner(System.in);
MyStack1 s = new MyStack1();
while(true){
System.out.println("Enter the choice You want to perform on the stack: ");
System.out.println(" 1. push \n 2. Pop \n 3. Display \n 4. peep \n 5. Exit");
System.out.println("Enter your option: ");
option = sc.nextInt();
switch(option){
case 1: System.out.println("Enter the element you want to push into the stack: ");
s.push(sc.nextInt());
break;
case 2: s.pop();
break;
case 3: System.out.println("Displaying the stack contents: ");
s.display();
break;
case 4: System.out.println("The top element in the stack is: ");
s.peek();
break;
case 5: System.out.println("You selected Exit!!");
break;
default: System.out.println("Wrong choice!! Please enter a valid option!!");
return;
}
}
}

Using Scanner inside a for loop for system input

I have been struggling with this for a while. I essentially want to loop through and read in as many strings as determined by num_choices. The following code only executes the else condition.
Scanner s2 = new Scanner(System.in);
for(int i=0; i < this.num_choices; i++)
{
if(s2.hasNext())
{
System.out.println("Enter choice " + (i+1) +":");
String ch = s2.next();
//this.choices.addElement(ch);
}
else
{
System.out.println("Lets end this");
}
}
`
I am getting this: Exception in thread "main" java.util.NoSuchElementException. In the main class, this is where the error points to
choice2 = Integer.parseInt(read_choice2.next());
which is inside a while loop as well. Here is the code for that:
public class Main
{
public static void main(String args[]) throws IOException
{
Vector<Survey> mysurveys = new Vector<Survey>();
boolean carry_on = true;
int choice = 0;
Scanner read_choice = new Scanner(System.in);
System.out.println("Let's begin the Survey/Test application!");
while(carry_on)
{
System.out.println("What would you like to do?");
System.out.println("1. Create a new Survey");
System.out.println("2. Create a new Test");
System.out.println("3. Display a Survey");
System.out.println("4. Display a Test");
System.out.println("5. Save a Survey");
System.out.println("6. Save a Test");
System.out.println("7. Load a Survey");
System.out.println("8. Load a Test");
System.out.println("9. Quit");
System.out.println();
System.out.println("Please enter a number for the operation you want to perform: ");
choice = Integer.parseInt(read_choice.next());
/*try
{
choice = Integer.parseInt(buffer.readLine());
}
catch(InputMismatchException e)
{
System.out.println("Invalid input. Please Enter again.");
System.out.println();
//read_choice.nextInt();
}*/
switch(choice)
{
case 1:
System.out.println("Please Enter a Name for your Survey");
String in = buffer.readLine();
Survey s1 = new Survey();
s1.CreateNew(in);
mysurveys.add(s1);
////
add_question(s1.type);
break;
case 2:
System.out.println("Please Enter a Name for your Test");
//String in = buffer.readLine();
Test t1 = new Test();
//t1.CreateNew(in);
mysurveys.add(t1);
break;
////
//add_question(t1.type);
case 3:
break;
// call Survey.display()
case 4:
break;
case 5:
Survey s = new Survey();
ReadWriteFiles x = new ReadWriteFiles();
x.SaveSurvey(s);
break;
case 6:
Test t = new Test();
//ReadWriteFiles x = new ReadWriteFiles();
//x.SaveSurvey(t);
break;
case 7:
carry_on = false;
break;
default:
System.out.println("Incorrect Input. Try Again");
System.out.println();
break;
}
}
read_choice.close();
}
public static void add_question(String type) throws IOException, NullPointerException
{
Questions q = null;
boolean carry_on2 = true;
int choice2 = 0;
Scanner read_choice2 = new Scanner(System.in);
//BufferedReader buffer2=new BufferedReader(new InputStreamReader(System.in));
while (carry_on2)
{
//
System.out.println("1. Add a new T/F Question");
System.out.println("2. Add a new Multiple Choice Question");
System.out.println("3. Add a new Short Answer Question");
System.out.println("4. Add a new Essay Question");
System.out.println("5. Add a new Ranking Question");
System.out.println("6. Add a new Matching Question");
System.out.println("7. If you want to stop adding more questions, and go back to the main menu.");
System.out.println("Please enter a number for the operation you want to perform: ");
choice2 = Integer.parseInt(read_choice2.next());
/*try
{
choice2 = Integer.parseInt(buffer2.readLine());
}
catch(InputMismatchException e)
{
System.out.println("Invalid input. Please Enter again.");
System.out.println();
//read_choice2.nextInt();
}*/
switch(choice2)
{
case 1:
q = new TrueFalse();
break;
case 2:
q = new MultipleChoice();
break;
case 3:
q = new ShortAnswer();
break;
case 4:
q = new Essay();
break;
case 5:
q = new Ranking();
break;
case 6:
q = new Matching();
break;
case 7:
carry_on2 = false;
break;
default:
System.out.println("Incorrect Input.");
break;
}
q.createQuestion(type);
}
}
}
I realize there is a lot of messy code, and I apologize for that. I just wanted to show the entire thing, so it's easier to spot the problem. Help would be appreciated.
In general way, you should add if(read_choice.hasNext()) before invoking read_choice.next(); You have the exception java.util.NoSuchElementException because no elements found to be read. this is a good habit.
About your problem, you are getting error because you has closed scanner before finish reading. Put read_choice.close() outside of loop.
Moreover, for simplify, if you want to read integer, just simple : scanner.nextInt().
read_choice.close();
Don't close the scanner as long as you are not done reading all the inputs. Doing also closes the underlying input stream (System.in), check the documention;
You don't need to initialize the Scanner multiple times. Just create one instance and pass it around (keep using it).
Also,
for(int i=0; i < this.num_choices; i++)
{
//if(s2.hasNext())
//{
System.out.println("Enter choice " + (i+1) +":");
String ch = s2.next();
//this.choices.addElement(ch);
you don't need that condition check. The next() will block until the input is entered.

Exception in thread "main" java.lang.NullPointerException cann't write to a class

So I have this code :
package Firstpack;
import java.io.*;
import java.util.*;
public class Main {
public static void menu() {
System.out.println("Welcome");
System.out.println("1. Add a record ");
System.out.println("2. See all records ");
System.out.println("3. See a category");
System.out.println("4. Total spend(Year)");
System.out.println("5. Spend in a month");
System.out.println("6. Chose by index");
System.out.println("7. Exit ");
System.out.print(">");
Scanner in = new Scanner(System.in);
int enteredInt = in.nextInt();
in.close();
switch (enteredInt) {
case 1:
recording();
break;
case 2:
System.out.print(" You have chosen -> See all records");
break;
case 3:
System.out.print(" You have chosen -> See a category");
break;
case 4:
System.out.print(" You have chosen -> Total spend(Year)");
break;
case 5:
System.out.print(" You have chosen -> Spend in a month");
break;
case 6:
System.out.print(" You have chosen -> Chose by index");
break;
case 7:
System.out.print(" Bye! ");
break;
default:
menu();
}
}
public static void recording() {
System.out.println(" You have chosen -> Add a record");
record rec = new record();
Scanner in = new Scanner(System.in);
System.out.print("Enter Amount > ");
rec.amount = in.nextDouble();
System.out.print("Enter Category > ");
rec.category = in.next();
System.out.print("Enter Details > ");
rec.details = in.next();
try {
FileWriter fw = new FileWriter("findme.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(String.valueOf(rec.amount));
bw.write(rec.category);
bw.write(rec.details);
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
menu();
}
}
And it throws me this:
Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Unknown Source)
at Firstpack.Main.recording(Main.java:68)
at Firstpack.Main.menu(Main.java:25)
at Firstpack.Main.main(Main.java:82)
And I have no idea how to solve this. What is wrong here?
The problem is because of the call to in.close() in your menu method. Not only does in.close() close the Scanner object, but it also happens to close System.in as well. When you enter 1 as the menu selection your recording() method gets called which creates a new Scanner which tries to use the now closed System.in.
This is a post that addresses a similar issue:
Trying to write a method that checks user input in JAVA, getting NoSuchElementException

Categories

Resources