Java: Switch statement not calling methods properly - java

I am having trouble getting my menu below to run from my driver. The program will execute, however it will not display my menu until I enter a number. After that it will display properly, and it reads selection properly, but will not call the methods I have listed in the case statement.
For instance, if I input a '1', the menu will recognize I input a 1 and will display the menu again with "You entered 1". instead of calling dec.getDec(), as it should according to the case statement. Any helpful hints or advice would be appreciated. This is a homework assignment, and I am not trying to get someone to write the code for me or anything. I just need to be pointed in the right direction please.
import java.io.IOException;
import java.io.*;
import java.util.Scanner;
public class Menu {
Scanner scan = new Scanner(System.in);
int selection;
public int GetSelection()
{
selection = scan.nextInt();
return selection;
}
public void display()
{
System.out.println("Please choose an option from the following:");
System.out.println("[1] Convert Decimal to Binary");
System.out.println("[2] Convert Decimal to Hexadecimal");
System.out.println("[3] Convert Binary to Decimal");
System.out.println("[4] Convert Binary to Hexadecimal");
System.out.println("[5] Convert Hexadecimal to Decimal");
System.out.println("[6] Convert Hexadecimal to Binary");
System.out.println("[0] Exit");
System.out.println("\n");
System.out.println("You entered: " + selection);
}
}
----------------------------
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)throws IOException {
LineWriter lw = new LineWriter("csis.txt");
int selection;
Decimal dec = new Decimal();
Binary bin = new Binary();
Hexadecimal hex = new Hexadecimal();
Menu menu = new Menu();
do{
menu.display();
selection=menu.GetSelection();
switch (selection){
case '1':{ dec.getDec();
break;}
case '2':{ dec.getHex();
break;}
case '3':{ bin.getBin();
break;}
case '4':{ bin.getHex();
break;}
case '5':{ hex.getHex();
break;}
case '6': { hex.getDec();
break; }
//default: System.out.println("Error: Unrecognized Selection");
// break;
}
}while (selection !=0);
}
}

As this is homework, I won't give you the whole solution, but I'll help get you there...
Your problem is coming from your use of Scanner, the helpful part of this page is A scanning operation may block waiting for input.
Using that you should be able to see where the problem is, if you need more help comment on this answer and I'll see if there's more I can do.

Don't use case 'n':, just use case n. You don't need the single quote. Also have a look at this tutorial on Switch Statements in Java to get an idea of how to use this in your code.
The problem with your current implementation is because you're trying to compare an int value (that you've in your selection variable) with char (which is internally getting converted to its corresponding int value i.e. int value of '1' is not the same as 1).
You can see the difference with the following code:
switch(selection){
case '1':
System.out.println("Hello World from char");
break;
case 1:
System.out.println("Hello World from int");
break;
}
So when you set selection = 1, you would find the output from the int block however if you set selection = '1', you would find the output from the char block
Note that I'm assuming that you're not running in Java 7
Note: There's another issue with your code. #Shaded has given you the perfect hint. Think about it with reference to how your control flows through your logic for setting the value of selection variable.

Related

Create user interface with while loop

I currently have an assignment on creating a user interface with while loop, here is my code so far:
import java.util.Scanner;
public class Part3{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Welcome dear user!");
System.out.println("Would you like to:");
System.out.println("a) sum gain");
System.out.println("b) exit");
System.out.print("Option: ");
String optionString = input.next();
char option = optionString.charAt(0);
while (option == ("a")){
System.out.println("Helo");
}
}
}
I'm stuck with the while loop, when I compile, it is error say a bad operand types for binary operator. I'm new to java so can you guys help me out with this. Thanks a lot
You might be facing the following issue:
Part3.java:14: error: incomparable types: char and String
while (option == ("a")){
Because you're trying to compare a char (option) and a String ("a"). So do use 'a' instead of "a".
Even when you'll resolve this issue, it seems that your code will stuck into a infinite loop when user will choose option a.
If you wanna print it only one time use break; statement inside loop.
while (option == ("a")){
System.out.println("Helo");
break;
}

Printing contents of file based on user input

Trying to print a file based off the user's input as mentioned in the title. Basically, my program has been altered from one that I previously created which reads data from a file, so I know that the file has been imported correctly (not the problem).
The problem I have is that I'm trying to make the program print the entirety of the .txt file if the user chooses a specific number, in this case '1'. My current code so far is:
import java.io.FileReader;
import java.util.Scanner;
public class InputOutput {
public static void main(String[] args) throws Exception {
// these will never change (be re-assigned)
final Scanner S = new Scanner(System.in);
final Scanner INPUT = new Scanner(new FileReader("C:\\Users\\JakeWork\\workspace\\Coursework\\input.txt"));
System.out.print("-- MENU -- \n");
System.out.print("1: Blahblahblah \n");
System.out.print("2: Blahblahblah \n");
System.out.print("Q: Blahblahblah \n");
System.out.print("Pick an option: ");
if (S.nextInt() == 1) {
String num = INPUT.nextLine();
System.out.println(num);
}
I feel as if my if statement is totally off and I'm heading in the entire wrong direction, could anyone point me in the right and give me a helping hand?
You're close, but not quite there.
You a reading the user input correctly, but now you need the file contents in a loop.
if(S.nextInt() == 1) {
while (INPUT.hasNextLine()) {
System.out.println(INPUT.nextLine());
}
}
This will keep looking as long as the file contents hasNextLine
You can safely remove the String option = S.next();
Also, just a small bit of naming convention nitpicking, don't use all upper case letters for variable names unless they are meant to be static. Also, the first letter of a variable is generally lower case.
if (S.nextInt() == 1) {
// check if there is input ,if true print it
while((INPUT.hasNextLine())
System.out.println(INPUT.nextLine());
}
Also, for menu scenarios like this, consider using a switch statement, then place a call to the menu-printing (that you move to a separate method) in the default case, so that if you enter something wrong, you can reprint the menu choices. Also, the switch statement is more readable (arguably) than a bunch of if's, like this:
int option = S.nextInt();
switch(option) {
case 1 :
while(INPUT.hasNextLine()) {
System.out.println(INPUT.nextLine());
}
break;
case 2 :
//Do stuff
break;
default :
//Default case, reprint menu?
}
}

Using switch statements in a while loop

I'm trying to use switch statements in a while loop in Java, but there is something going wrong. Please have a look at a sample code below which explains my problem:
Scanner input=new Scanner(System.in);
int selection = input.nextInt();
while (selection<4)
{ switch(selection){
case 1:
System.out.println("Please enter amount");
double amount=input.nextDouble(); //object of scanner class
break;
case 2:
System.out.println("Enter ID number");
break;
case 3:
System.out.println("Enter amount to be credited");
break;
}
System.out.println("1. Transfer\n2.Check balance\n3.Recharge");
}
If I run this code, the output is as follows:
1
Please enter amount
2000
1. Transfer
2.Check balance
3.Recharge
Please enter amount
2
1. Transfer
2.Check balance
3.Recharge
Please enter amount
When I enter the amount, I would then like to choose another option - and the output should be according to the option chosen (you should probably be knowing what I want this code to do). Could someone please help correct the code?
Thanks
You currently get and set the selection value once and before the while loop, and so there is no way to change this from within the loop. The solution: Get your next selection value from the Scanner object inside of the while loop. To understand this, think the problem out logically and be sure to walk through your code mentally and on paper as the issue is not really a programming issue but rather a basic logic issue.
Regarding:
Could someone please help correct the code?
Please don't ask us to do this and for several reasons.
This is not a homework completion service
You're harming yourself by asking others to change the code for you, as you learn how to code by writing code.
Really this is a basic simple issue that you have the ability to fix on your own. Please give it a try, and only if the attempt doesn't work, then show us your attempt.
You're forgetting to ask for the selection again. It's not going to change once it's been entered.
Scanner input=new Scanner(System.in);
int selection = input.nextInt();
while (selection<4)
{
switch(selection){
case 1:
System.out.println("Please enter amount");
double amount=input.nextDouble(); //object of scanner class
break;
case 2:
System.out.println("Enter ID number");
break;
case 3:
System.out.println("Enter amount to be credited");
break;
}
System.out.println("1. Transfer\n2.Check balance\n3.Recharge");
selection = input.nextInt(); // add this
}
You could even use a do...while loop instead to avoid writing input.nextInt(); twice
Scanner input=new Scanner(System.in);
int selection;
do
{
selection = input.nextInt();
switch(selection){
case 1:
System.out.println("Please enter amount");
double amount=input.nextDouble(); //object of scanner class
break;
case 2:
System.out.println("Enter ID number");
break;
case 3:
System.out.println("Enter amount to be credited");
break;
}
System.out.println("1. Transfer\n2.Check balance\n3.Recharge");
}
while(selection < 4);
Case must be bigger than 4, in your case the cases are less than 4. so you won't quit the loop, basically the break statement breaks the switch and jumps to loop, but than the loop is again less than 4 so it jumps again into the switch and so on. Fix the Sizes of your cases, maybe just make an
(selection != 1 || selection != 2 || selection !=3 || selection !=4)

Java use user input to determine enum value

I'm currently hardcoding an enum value, which is running through a switch statement. Is it possible to determine the enum based on user input.
Choice month = Choice.D;
Instead of hardcoding the value D, can I use the user input here?
package partyAffil;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class partyAffil {
public static void main(String[] args) {
System.out.println("Choose from the following menu");
System.out.println("D, R, or I");
String choice = getInput("please choose a letter.");
Choice month = Choice.D;
switch(month){
case D:
System.out.println("You get a Democratic Donkey");
break;
case R:
System.out.println("You get a Republican Elephant");
break;
case I:
System.out.println("You get an Independent Person");
break;
default:
System.out.println("You get a unicorn");
break;
}
}
public enum Choice{
D, R, I;
}
private static String getInput(String prompt)
{
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
System.out.print(prompt);
System.out.flush();
try{
return stdin.readLine();
} catch (Exception e){
return "Error: " + e.getMessage();
}
}
}
Each enum constant have its own name as declared in its declaration. Static method valueOf of particular enum returns the enum constant of this type by name.
Thus, instead:
Choice month = Choice.D;
just use this:
Choice month = Choice.valueOf(choice);
What if you create the switch on the input rather than the month (or both, if they must be implemented separately)?:
Choice month;
switch(choice.toUpperCase()){
case 'D':
month = Choice.D
System.out.println("You get a Democratic Donkey");
break;
...
}
Better yet, I believe you could even set the character values in the enum:
public enum Choice{
D('D'), R('R'), I('I');
}
This way, instead of case 'D': you can still use case D:
(Not sure about that one, I am more used to C-based languages)
Above given answers might help.
If you are not an expert, use following code that will you understand the steps.
public void run() throws Exception
{
switch (menu() ) //calling a menu method to get user input.
{
case 1:
//fyi, make sure you have all the methods in your code that is given for each menu choice.
//you can have print statement in your method.
// e.g. System.out.println("You get a Democratic Donkey");
method1();
break;
case 2:
method2();
break;
case 3:
method3();
break;
case 0:
return;
//following default clause executes in case invalid input is received.
default:
System.out.println ( "Unrecognized option" );
break;
}
}
private int menu()
{
//list of menu items.
System.out.println ("1. insert appropriate description for your menu choice 1.");
System.out.println ("2. ");
System.out.println ("3. ");
System.out.println ("4. ");
return IO_Support.getInteger(">> Select Option: ", "Unrecognized option"); //you can use scanner to get user input. I have user separate class IO_Support that has getInteger methods to validate int user input. the text "unrecognized option" is what the message that i want to print if the option is integer but not valid choice.
}

Creating a console menu for user to make a selection

Doing a program in Eclipse with Java. What I want to do is when I execute the program I want present the user with a choice. I have all the calculations etc. done, I'm just unsure as to how to make this menu to offer the user choices. Example of what I'm looking for:
To enter an original number: Press 1
To encrypt a number: Press 2
To decrypt a number: Press 3
To quit: Press 4
Enter choice:
public static void main(String[] args) {
Data data = new Data();
data.menu(); }
}
For simplicity's sake I would recommend using a static method that returns an integer value of the option.
public static int menu() {
int selection;
Scanner input = new Scanner(System.in);
/***************************************************/
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Enter an original number");
System.out.println("2 - Encrypt a number");
System.out.println("3 - Decrypt a number");
System.out.println("4 - Quit");
selection = input.nextInt();
return selection;
}
Once you have the method complete you would display it accordingly in your main method as follows:
public static void main(String[] args) {
int userChoice;
/*********************************************************/
userChoice = menu();
//from here you can either use a switch statement on the userchoice
//or you use a while loop (while userChoice != the fourth selection)
//using if/else statements to do your actually functions for your choices.
}
hope this helps.
You can use a scanner to read input from System.in, as follows:
public static void main(String[] args) {
Data data = new Data();
data.menu();
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
// Perform "original number" case.
break;
case 2:
// Perform "encrypt number" case.
break;
case 3:
// Perform "decrypt number" case.
break;
case 4:
// Perform "quit" case.
break;
default:
// The user input an unexpected choice.
}
}
Note that this will require the user to input a number and press enter, before continuing execution. If they enter invalid input, this will halt; if you want it to prompt them again, you will need to wrap this in a loop of some sort, depending on how you want the system to behave.
Scanner#nextInt may very well throw an exception, should the user input something that cannot be parsed to an integer. You can catch this exception and handle it appropriately. If the user enters an integer that is out of the range of valid options (i.e. it is not in the range of 1-4), it will fall to the default branch of the switch statement, where you can again handle the error case however you wish.

Categories

Resources