import java.io.IOException;
import java.io.InputStreamReader;
public class doSwitch {
public static void main(String[] args) throws IOException {
char choice;
do {
System.out.println("Welcome User");
System.out.println("1. Change plan");
System.out.println("2. Pay Bill");
System.out.println("3. Complaints");
System.out.println("4. De-activate account");
System.out.println("Choose one the above option");
choice = (char) System.in.read();
} while (choice < '1' || choice > '4');
System.out.println("User's Choice:" + choice);
///////////////////////////// switch
///////////////////////////// case////////////////////////////////////
switch (choice) {
case '1':
System.out.println("There are different plans than you can opt for");
break;
case '2':
System.out.println("Pay bill using credit card or debit card");
break;
case '3':
System.out.println("In case of complaint call 121");
break;
case '4':
System.out.println("Are you sure you want to discontinue with us");
break;
}
}
}
This codes works properly if i entered values between 1 to 4. But If the value is greater than 4 then its executing the loop 3 times. I figured out its taking the value \n, \r. What i m not getting is how can i avoid it. and why it works for values 1-4
try
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
System.in.read() reads a single byte. In your case it reads the actual inputed character. If the character doesn't equal 1-4, then the loop continues and the next byte will be read, which will be a return character. The scanner objects takes care of this for you.
Related
I need help with a if statement.
What I want to do is after the default, put an if statement that basically says
if name equals Mike or lady
then print out "Type a number between 1-3 to see your prize".
And if you type for example 1, it should print out you won a Bicycle.
I know that not that many Pro-programmers use switch but that's all I know for now :)
import java.util.Scanner;
public class Ifwasif {
public static void main (String [] args) {
System.out.println("Welcome to our Store!");
System.out.println("we hope you will find what you're looking for");
Scanner input = new Scanner (System.in);
System.out.print("To check out, please type your name: ");
String name = input.nextLine();
System.out.print("You need to confirm your age, please type your age: ");
int age = input.nextInt();
Scanner input1 = new Scanner (System.in);
System.out.print("You have an award to collect! To collect it type your name: ");
String namee = input1.nextLine();
switch (namee) {
case ("Mike"):
System.out.println("Congrats, you are the Winner!");
break;
case ("Don"):
System.out.println("Sorry you are not the winner!Better luck next time");
break;
case ("lady"):
System.out.println("Congrats, you are the Winner!");
break;
default:
System.out.println("Your name is not in the list!");
}
}
}
Rather than an if statement after the switch, combine your 2 "winner" cases into a single case:
switch (namee) {
case ("Mike"):
case ("lady"):
System.out.println("Congrats, you are the Winner!");
// insert code here to prompt for input, read result, compare, and award
// or put that code into a new method
break;
case ("Don"):
System.out.println("Sorry you are not the winner!Better luck next time");
break;
default:
System.out.println("Your name is not in the list!");
Should work fine:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Welcome to our Store!");
System.out.println("we hope you will find what you're looking for");
Scanner input = new Scanner(System.in);
System.out.print("To check out, please type your name: ");
String name = input.nextLine();
System.out.print("You need to confirm your age, please type your age: ");
int age = input.nextInt();// variable never used
input.nextLine();
System.out.print("You have an award to collect! To collect it type your name: ");
String namee = input.nextLine();
switch (namee) {
case ("Mike"):
case ("lady"):
System.out.println("Congrats, you are the Winner!");
break;
case ("Don"):
System.out.println("Sorry you are not the winner!Better luck next time");
break;
default:
System.out.println("Your name is not in the list!");
break;
}
if("Mike".equals(name) || "lady".equals(name)){
System.out.println("Type a number between 1-3 to see your prize'");
int number = input.nextInt();
switch (number) {
case 1:
System.out.println("You won a Bicycle");
break;
default:
break;
}
}
}
}
I Want to create a condition that checks were the input is a integer ranging from 1 to 5.
but it keeps saying input matching exception, can you guys help?
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
int choice = scan.nextInt();
System.out.println(">> You have selected ["+choice+"]");
//loops until input is an integer ranging from 1 to 5
while(!scan.hasNextInt() && choice>0 && choice<6){
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
default:
System.out.println(">> You put wrong input");
break;
}
}
}
Try this:
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
//input variable
String in;
//loops until input is an integer ranging from 1 to 5
while (scan.hasNextLine()) { //checks if there is a new line of input
in = scan.nextLine().trim(); //scans that line
if (!in.matches("^[1-5]$")) { //tests if input is a single positive digit 1-5
System.out.println(">> You put wrong input");
continue;
}
int choice = Integer.parseInt(in);
System.out.println(">> You have selected ["+choice+"]");
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
}
}
}
}
I have slightly altered your code to not only keep persisting the user for a valid input, but also correctly parse that input to avoid any errors. I also removed the default part of the switch block, only because the input validation prior eliminates the need for it.
I have not tested this code, but it should work properly :)
You are currently not updating the choice variable for each iteration, but rather only using the initial value. Furthermore, you're iterating until scan DOES NOT have an int, i.e. !scan.hasNextInt() and I guess you're intention is actually the opposite.
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
int choice;
//loops until input is an integer ranging from 1 to 5
while(scan.hasNextInt() && (choice = scan.nextInt()) > 0 && choice < 6){
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
default:
System.out.println(">> You put wrong input");
}
}
}
Hope it helps!
How do I break out of a void method and get back to the switch method?
public static void decrypt() throws FileNotFoundException {
Scanner kbrd = new Scanner(System.in);
System.out.println("Enter Key-file name: ");
String filename = kbrd.nextLine();
System.out.println("Enter Message-filename: ");
String mssgFilename = kbrd.nextLine();
String[] keyArray = loadMessage(filename);
String[] message = loadMessage(mssgFilename);
String[] cipher = xor2(message, keyArray);
String readable = showText(cipher);
System.out.println("The text:" + readable);
return;
}
and then here is the switch method
System.out.println("Encrypt 1.");
System.out.println("Decrypt 2.");
System.out.println("Make Key 3.");
System.out.println("Quit 4.");
Scanner scan = new Scanner(System.in);
String choice = scan.nextLine();
do {
switch (choice) {
case "1":
encrypt();
break;
case "2":
decrypt();
break;
case "3":
makeKey();
break;
}
} while (choice != "4");
Problem is, whatever I choose it stays in that method despite the return statement at the end , shouldn't that bring me back to the switch method?
Put the ability to add another choice into the loop. You're currently entering into an infinite loop because choice does not change.
String choice;
do {
choice = scanner.nextLine();
switch (choice) {
case "1":
encrypt();
break;
case "2":
decrypt();
break;
case "3":
makeKey();
break;
}
} while (!choice.equals("4"));
Observe that this has nothing to do with the methods being called; this is entirely regulated by the do...while loop.
You have a loop that goes in infinite loop as the choice is read only once. You enter 3 once and it goes into a loop with the condition choice != '4', and it is always true, as you dont change your choice. So your function is called over and over again. (It does break out of the function but it is called over and over again) Put the input lines inside the loop.
While writing code for my program I thought of testing the first part before moving on and writing the operations. Although I have the user input, but I want the options to be displayed after each operation (add, deltete..) is done untill the users presses exit. How do I modify my code to do it?
import java.io.*;
import java.util.*;
public class Records {
public static void main(String[] args) {
int choice;
do {
System.out.println("1.Add \n 2.Delete \n 3.Update \n 4.Show \n Exit");
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//int choice;
System.out.println("Enter your Choice : ");
Scanner sc = new Scanner(System.in);
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Getting ready to Add a Record ");
//set();
break;
case 2:
System.out.println("Getting ready to Delete a Record ");
//delete();
break;
case 3:
System.out.println("Getting ready to Update a Record ");
//update();
break;
case 4:
System.out.println("Here is your record ");
//display();
break;
case 5:
System.out.println("Out we go.");
System.exit(0);
//exit();
break;
default:
System.out.println("Try again");
break;
}
} while ( choice > 5 || choice < 1 );
}
}
Simply change your while condition to:
} while ( choice > 0 && choice < 5 );
First make sure your scanner really has an int, use sc.hasNextInt() to validate the user entered a number. To end the do/while loop at "5.Exit", just have it like do{...}while(choice!=5). Code below is not tested.
import java.io.*;
import java.util.*;
public class Records {
public static void main(String[] args) {
int choice;
do {
System.out.println("1.Add \n 2.Delete \n 3.Update \n 4.Show \n 5.Exit");
System.out.println("Enter your Choice : ");
choice = -1;
Scanner sc = new Scanner(System.in);
// validate the next thing in your scanner is an int
// otherwise, sc.nextInt() might cause an exception
if (sc.hasNextInt()){
choice = sc.nextInt();
switch (choice) {
case 1: System.out.println("Getting ready to Add a Record ");
// ...
break;
case 2: System.out.println("Getting ready to Delete a Record ");
// ...
break;
case 3: System.out.println("Getting ready to Update a Record ");
// ...
break;
case 4: System.out.println("Here is your record ");
// ...
break;
case 5: System.out.println("Out we go.");
// skip System.exit(0), your main method ends
// automatically when you leave your do/while loop
break;
default: System.out.println("Try again");
break;
}
}
// if choice == 5 it ends, otherwise, starts over...
} while ( choice != 5 );
}
}
Although I have the user input, but I want the options to be displayed
after each operation (add, deltete..) is done untill the users presses
exit.
You can set int flag=0; and when user selects exit option set flag to 1 to tell loop to exit.As of now you are already breaking out for number > 5 or < 1 in default case so no need to put that condition in while.
int flag=0;//Declare outside the loop
do{
...
case 5: System.out.println("Out we go.");
flag=1;//Set flag to 1 if user enters 5
break;
...
} while ( flag!=1 );//Exit the loop when flag==1
//Or directly while ( choice!=5 );
Serious EDIT
As Java Programmer I should probably suggest you to use boolean primitive type for flagging.
boolean flag=true;//Declare outside the loop
do{
...
case 5: System.out.println("Out we go.");
flag=false;//Set flag to 1 if user enters 5
break;
...
} while (flag);//Exit the loop when flag==false
One More thing:
Surround code with try-catch to leave out invalid inputs and prompt again for input.
Most of the times it's not recommended to swallow the Exception.
do{
try{
....//Your Switch case
}catch(InputMismatchException e){}
} while (choice !=5);//But remove System.exti(0); from your switch statement
Simply make your while loop as:
} while ( choice!=0 );(The Wrong one)
Correction:
} while(choice!=0 && choice<=5)
i wrote a small program in java
the user enter a number to get his multiplication table
and then type the maximum length of that table
but in the third case (case r) i got an error orphaned case
and it seems clean code to me
public class JavaApplication2 {
public static void main(String[] args) throws IOException
{
System.out.println("Multiplication Table v1.0");
System.out.println("Developped By Roy Jalbout");
System.out.println("-------------------------");
System.out.println("Type 'E' To Quit The Program\nType 'H' To Read The Help File\nType 'R' To Run The Program");
char act = (char)System.in.read();
switch (act) {
case 'e':
case 'E':
System.exit(0);
break;
case 'h':
case 'H':
System.out.println("The Multiplication Table Version 1.0 Developped By Roy Jalbout is A Simple Program All you have to do is to choose the number that you want to get his multiplication table and then choose the maximum lenght of that table");
System.out.println("----------------------------------");
System.out.println("Type back to go to the main thread");
String mainthread = scn.next();
if ("back".equals(mainthread)){
JavaApplication2.main(args);
break;
case 'r':
case 'R':
Scanner scn = new Scanner(System.in);
System.out.print("Enter A Number To Get His Multiplication Table : ");
int num = scn.nextInt();
System.out.print("Enter The Max Number Of The Multiplication Table : ");
int max = scn.nextInt();
int b=1;
while (b<=max){
System.out.println(num + " * " + b + " = " + b*num);
b++;
JavaApplication2.main(args);
}
default:
System.out.println(act + " is an Invalid Choice");
}
}
}
}
any help???
if ("back".equals(mainthread)){
JavaApplication2.main(args);// you are not closing the brace here..
break;
The problem with the orphaned case, for me, was there was a couple of not closed curly brackets after I began the switch case.
For example, there was a loop inside a case which I had not closed.
Once I closed there was no obstacles