This question is regarding switch statement. These are a few similar posts on this (below) but I am still having trouble understanding.
Using user-inputted characters in If/Switch statements
How do I used a char as the case in a switch-case?
Multiple characters in a switch statement?
Please consider the following:
public class main
{
public int selection;
public main()
{
System.out.println("MENU");
Scanner in = new Scanner(System.in);
do {
showMenu();
selection = in.nextInt();
switch (selection)
{
case 1:
doSomething();
break;
case 2:
case 3:
default:
System.out.println("Instruction is invalid");
}
}
while (selection !=7);
{ System.exit(0); }
}
public static void showMenu()
{
System.out.print('\u000c');
System.out.println("option 1 \n");
System.out.println("option 2 \n");
System.out.println("7 - exit.\n");
System.out.println("Select Option:\n");
}
}
So this is a switch statement is for the user to choose options within the do while loop. The user enters an integer from the printed list to choose an option, after completion of the case, it loops back to menu.
My teacher informs me that its better practice to use char instead of int to get user input for the switch. I expect it to look something like this, but it doesn't work and I'm not sure why.
public class main
{
public int selection;
public main()
{
System.out.println("MENU");
Scanner in = new Scanner(System.in);
do {
showMenu();
String menu = "";
char selection = menu.charAt();
switch (selection)
{
case 'A':
doSomething();
break;
case 2, 3, 4, 5, 6
default:
System.out.println("Instruction is invalid");
}
}
while (selection != 'QQ');
{ System.exit(0); }
}
In the second link posted there was an answer which i think suggested using
hello.charAt(0)
as the switch condition?
switch (hello.charAt(0))
{
case 'a': ... break;
}
I have three specific questions on this code:
1) My code doesn't work. Should my condition be hello.charAt(0) ?
2) I would like to use QQ as the quit option on the switch. Is possible with the code above? From the second link, I think it should be fine.
3) It is also shown here (switch statement using char in the case condition?) that the case statement should have double quotations. Could someone please clarify this as well?
Something like this should work better:
do {
showMenu();
String menu = in.nextLine(); // read a line of input
char selection;
if (menu.length>0) selection = menu.charAt(0); // extract the first char of the line read
else selection = '\0'; // special char when input is empty...
switch (selection) {
case 'A': case 'a':
doSomething();
break;
case 'Q': case 'q':
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 'Q' && selection != 'q');
menu stores the full input line. selection would be the first char (if it exists) of the line.
To use .charAt() you need to supply the index - so if you want to use the first character then use 0, etc.
In general one read an entire line instead of a single keystroke:
The first char of a String is gotten by charAt(0). However the string
could have length 0. There is the if-expression CONDITION ? TRUEVALUE : FALSEVALUE.
String menu = in.readLine();
char selection = menu.isEmpty() ? ' ' : menu.charAt(0);
switch (selection) {
case 'A':
doSomething();
break;
case '2':
case '3':
case '4':
...
break;
default:
System.out.println("Instruction is invalid");
}
There is an even more succint solution:
String menuSelection = in.readLine();
switch (menuSelection) {
case "A":
doSomething();
break;
case "2":
case "3":
case "4":
...
break;
default:
System.out.println("Instruction is invalid");
}
Related
I'm making a looping user input program and my problem is that it cannot loop, it always end after displaying the statement "Again?" without asking for an user input again.
Here's the code:
public static void main(String[] args){
String yes;
do{
Scanner scan = new Scanner (System.in);
System.out.print("Enter a number from 1 to 10: ");
int num = scan.nextInt();
switch(num){
case 1:
System.out.print("One");
break;
case 2:
System.out.print("Two");
break;
case 3:
System.out.print("Three");
break;
case 4:
System.out.print("Four");
break;
case 5:
System.out.print("Five");
break;
case 6:
System.out.print("Six");
break;
case 7:
System.out.print("Seven");
break;
case 8:
System.out.print("Eight");
break;
case 9:
System.out.print("Nine");
break;
case 10:
System.out.print("Ten");
break;
default:
System.out.print ("Invalid Number!");
break;
}
System.out.print("\nAgain? y/n");
yes = scan.nextLine();
}while(yes.equals('y'));
}
}
try to use scanner.next() instead of nextLine.
And at the loop. You defined 'y'. The single quotes there means that this is a char and not a string. For that reason the loop condition is never 'true'.
See the equal of String
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String aString = (String)anObject;
if (coder() == aString.coder()) {
return isLatin1() ? StringLatin1.equals(value, aString.value)
: StringUTF16.equals(value, aString.value);
}
}
return false;
}
The given value is not instance of String => false
PS: You should also try not to define the scanner on every loop cycle ;)
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
hope i can found help here , in fact im design program to make user enter string values contains 0s or 1s and then menu appear to help user to chose from 4 option put my problem i cant return the menu to display after first use because the program cannot run any choices after fist select ...
Thank you again
Scanner input = new Scanner(System.in);
System.out.print("Enter 0s or 1s Numbers ");
String binaryString = input.nextLine();// user must enter string value contains 0 or 1
convert.displayMenu();// call the display menu which contains 4 choices
Scanner input2 = new Scanner(System.in);// the user select the 1 option from 4
int select = input2.nextInt(); // to save what user enter it
// here is the switch statement im use it
switch (select) {
case 1:
input2.equals(1);
convert.getBinary(binaryString);
convert.displayMenu();
break;
case 2:
input2.equals(2);
convert.convertBtD(binaryString);
convert.displayMenu();
break;
case 3:
input2.equals(2);
convert.convertBtO(binaryString);
convert.displayMenu();
break ;
case 4:
break;
}
while(select != 4);
}
This loop restarts the switch/case statement:
inputloop: while(true) {
int select = input2.nextInt();
switch (select) {
case 1:
input2.equals(1);
convert.getBinary(binaryString);
break;
case 2:
input2.equals(2);
convert.convertBtD(binaryString);
break;
case 3:
input2.equals(2);
convert.convertBtO(binaryString);
break ;
case 4:
break inputloop;
}
convert.displayMenu();
}
This code could be rewritten in a way that the loop condition is select != 4 but this one is more concise (from my point of view)
boolean startLoop = true;
While(startLoop) {
switch(choice) {
case 1:
break;
case 2:
break;
case 3://exitChoice
startLoop = false;
break;
}
}
A simple solution can be implemented like this:
while(1){
Scanner input2 = new Scanner(System.in);// the user select the 1 option from 4
int select = input2.nextInt(); // to save what user enter it
switch(select)
{
case 1:
input2.equals(1);
convert.getBinary(binaryString);
convert.displayMenu();
break;
case 2:
input2.equals(2);
convert.convertBtD(binaryString);
convert.displayMenu();
break;
case 3:
input2.equals(2);
convert.convertBtO(binaryString);
convert.displayMenu();
break ;
case 4:
break;
}
if(select == 4)
break;
}
You should call this method by itself like:
public void menu(){
Scanner input = new Scanner(System.in);
System.out.print("Enter 0s or 1s Numbers ");
String binaryString = input.nextLine();// user must enter string value contains 0 or 1
convert.displayMenu();// call the display menu which contains 4 choices
Scanner input2 = new Scanner(System.in);// the user select the 1 option from 4
int select = input2.nextInt(); // to save what user enter it
// here is the switch statement im use it switch (select) {
case 1:
input2.equals(1);
convert.getBinary(binaryString);
convert.displayMenu();
break;
case 2:
input2.equals(2);
convert.convertBtD(binaryString);
convert.displayMenu();
break;
case 3:
input2.equals(2);
convert.convertBtO(binaryString);
convert.displayMenu();
break ;
case 4:
break;
case 5:
System.out.println("Exit Point");
System.exit(0);
}
menu();
}
I just add this code into a method and add a call menu() at the end of the method. I also create case 5 in order to exit the application. Its your logic how to do it right but you got main outline to achieve this :)
So I am making a program in Java on a BlueJ environment that computes Binary expansion. However, I can't seem to figure out how to add powers more than 9 in the output.
If I have an input power of anything more than 9 the program goes haywire, presumably because there are no cases after 9.
Also, I personally feel my program in general is extremely inefficient but I just did it this morning and this was the first approach I saw, so if you see a way to make it more efficient than using switch case, that'd be great too.
This is my code so far. It's not all mine, but I'm not sure if intellectual property and stuff applies on here, so just putting it out there.
import java.util.*;
class Binomial_Theorem_Expansion
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the value of x in (x+a)^n");
int x=s.nextInt();
System.out.println("Enter the value of a in (x+a)^n");
int a=s.nextInt();
System.out.println("Enter the value of n in (x+a)^n");
int n=s.nextInt();
System.out.println ("The expanded answer is");
int r=0;
int powx=n;
while (r<=n)
{
long nCr=calculatenCr(n,r);
if(nCr!=-1)
{
double y=Math.pow((double)x,(double)n-r);
double z=Math.pow((double)a,(double)r);
switch (powx)
{
case 0: System.out.print ("("+nCr*y*z);
break;
case 1: System.out.print ("("+nCr*y*z+"x");
break;
case 2: System.out.print ("("+nCr*y*z+"x\u00B2");
break;
case 3: System.out.print ("("+nCr*y*z+"x\u00B3");
break;
case 4: System.out.print ("("+nCr*y*z+"x\u2074");
break;
case 5: System.out.print ("("+nCr*y*z+"x\u2075");
break;
case 6: System.out.print ("("+nCr*y*z+"x\u2076");
break;
case 7: System.out.print ("("+nCr*y*z+"x\u2077");
break;
case 8: System.out.print ("("+nCr*y*z+"x\u2078");
break;
case 9: System.out.print ("("+nCr*y*z+"x\u2079");
break;
case 10: System.out.print ("("+nCr*y*z+"x\u2071\u00B2");
break;
}
switch (r) {
case 0: System.out.print (")");
break;
case 1: System.out.print ("y"+")");
break;
case 2: System.out.print ("y\u00B2"+")");
break;
case 3: System.out.print ("y\u00B3"+")");
break;
case 4: System.out.print ("y\u2074"+")");
break;
case 5: System.out.print ("y\u2075"+")");
break;
case 6: System.out.print ("y\u2076"+")");
break;
case 7: System.out.print ("y\u2077"+")");
break;
case 8: System.out.print ("y\u2078"+")");
break;
case 9: System.out.print ("y\u2079"+")");
break;
}
r++;
if (r<=n)
{
System.out.print ("+");
}
powx--;
}
}
}
public static long calculatenCr(int n,int r)
{
long res=1;
if(n>=r)
{
res=getFact(n)/(getFact(n-r)*getFact(r));
return res;
}
else return -1;
}
public static long getFact(int n)
{
long f=1;
for(int i=n;i>=1;i--)
{
f*=i;
}
return f;
}
}
Thanks for any constructive input. :)
presumably because there are no cases after 9.
Your code is using UNICODE superscript characters, and the cases that you have cover only numbers zero through ten for x and zero through nine for y.
You can fix this by defining a method that produces a superscript UNICODE conversion of a multidigit number, and calling it from both places where you need to produce such representation:
switch (powx) {
case 0: System.out.print ("("+nCr*y*z);
break;
case 1: System.out.print ("("+nCr*y*z+"x");
break;
default: System.out.print ("("+nCr*y*z+"x"+toSuperscript(powx));
break;
}
The other switch (i.e. switch (r)) should be converted in a similar way.
You can implement String toSuperscript(int n) by producing a decimal representation of n, and then replacing '0' with '\u2070', '1' with '\u00B9', and so on.
Here I have some problem when I use while loop in switch statement using dialog boxes. Some statements are unreachable and dialog boxes not appeared. Please help me! And also can do some correction on my code.
This the simple code that I made:
public static void main(String[] args)
{
// prompt and read first number from user
String no = JOptionPane.showInputDialog(null, "Enter the number");
int num = Integer.parseInt(no); //convert string to number
switch (num)
{
//display result
default: JOptionPane.showMessageDialog(null,"fail"); break;
case 1: JOptionPane.showMessageDialog(null,"c=a+b"); break;
case 2: JOptionPane.showMessageDialog(null,"c=a/b"); break;
case 3: JOptionPane.showMessageDialog(null,"c=a*b"); break;
case 4: JOptionPane.showMessageDialog(null,"c=a-b"); break;
}
}
The cases in a switch/case are evaluated in the order you put them. default matches all cases. Since you have that first and that case does something before breaking out of it, the other cases will never be reached. Try this instead:
case 1: JOptionPane.showMessageDialog(null,"c=a+b"); break;
case 2: JOptionPane.showMessageDialog(null,"c=a/b"); break;
case 3: JOptionPane.showMessageDialog(null,"c=a*b"); break;
case 4: JOptionPane.showMessageDialog(null,"c=a-b"); break;
default: JOptionPane.showMessageDialog(null,"fail"); break;
Your code does not show a while loop anywhere. Perhaps you can update with the code you attempted.
switch (num)
{
case 1:
while(!your condition)
{
JOptionPane.showMessageDialog(null,"c=a+b");
}
break;
case 2: JOptionPane.showMessageDialog(null,"c=a/b"); break;
case 3: JOptionPane.showMessageDialog(null,"c=a*b"); break;
case 4: JOptionPane.showMessageDialog(null,"c=a-b"); break;
default: JOptionPane.showMessageDialog(null,"fail"); break;
}
Retype the code:
// prompt and read first number from user
String no = JOptionPane.showInputDialog(null, "Enter the number");
int num = Integer.parseInt(no); //convert string to number
while (num<=4)
{
if
switch (num)
{
//display result
case 1: JOptionPane.showMessageDialog(null,"c=a+b"); break;
case 2: JOptionPane.showMessageDialog(null,"c=a/b"); break;
case 3: JOptionPane.showMessageDialog(null,"c=a*b"); break;
case 4: JOptionPane.showMessageDialog(null,"c=a-b"); break;
default: JOptionPane.showMessageDialog(null,"fail"); continue;
}
}// end method main
}// end class abc