Thanks for taking your time to help me. I need this switch statement to only accept ints 1-4. Any others entered will ask for input again. Entering 5 will quit the system.
System.out.println("A random numbers list has been generated for you:\n ");
System.out.println("Choose an option:\n1)Form list to be heapified.\n2)Enqueue the integer 10" +
"\n3)Dequeue the integer 10.\n4)Print the updated heap.\n5)Quit the system \n>>");
Scanner scanner = new Scanner( System.in );
int var = 0;
String input = scanner.next();
int answer = Integer.parseInt(input);
do{
input = scanner.next();
answer = Integer.parseInt(input);
var = answer;
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
}
}while(var ==1 || var==2 || var==3
|| var==4);
I cant seem to get it right. Keep making it worse.
Edited:
do{
String input = scanner.next();
int answer = Integer.parseInt(input);
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
h.pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
h.dequeue();//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default: input = scanner.next();
break;
}
}while(var!=5)
;
Try adding a "default:" statement, like this:
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default:
*Add whatever code you want to execute if its greater then or equal to 5 here!*
}while(var ==1 || var==2 || var==3
|| var==4);
You can set a 'default' case.
default: doSomething();
break;
This will be invoked when a user enters a value that isn't one of your cases.
} while (answer != 5);
This should make the loop break when 5 is entered.
EDIT:
Also, you need to switch on the answer variable instead of 'var'
switch(answer) {
You don't need to put it in a loop. The use case is simple:
For 1-4 : do something and then return
For 5: quit/return Everything
else: ask for input again
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int answer = Integer.parseInt(scanner.next());
switch(answer) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
return; // System.exit(0) or quit however you want to
default:
answer = Integer.parseInt(scanner.next());
}
}
Related
So, I made a burger class with a method for extra stuff, my question is how can I use case 0,1,2 only 1 time, like if I use case 0, I can't use it anymore, I can use only 1 and 2, If I use case 1 after 0 , then I can use only case 2 since I used case 0 and 1 before , It's possible to do something like that ? If yes how ?
The code:
boolean flag=true;
while(flag){
System.out.println("Enter your choice for extra toppings ");
int choice=scanner.nextInt();
scanner.nextLine();
switch(choice) {
case 0:
double salad = 0.35;
setAdditional(getAdditional() + salad);
System.out.println("salad added\n");
break;
case 1:
double bacon=1.05;
setAdditional(getAdditional()+bacon);
System.out.println("Bacon added \n");
break;
case 2:
double fries=0.79;
setAdditional(getAdditional()+fries);
System.out.println("fries added \n");
break;
case 3:
System.out.println("Done");
flag=false;
}
}
} ```
boolean flag = true;
Set<Integer> set = new HashSet<>();
while (flag) {
System.out.println("Enter your choice for extra toppings ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 0:
if (!set.contains(choice)) {
double salad = 0.35;
setAdditional(getAdditional() + salad);
System.out.println("salad added\n");
break;
}
else {
System.out.println("Added already");
}
continue;
case 1:
double bacon = 1.05;
setAdditional(getAdditional() + bacon);
System.out.println("Bacon added \n");
break;
case 2:
double fries = 0.79;
setAdditional(getAdditional() + fries);
System.out.println("fries added \n");
break;
case 3:
System.out.println("Done");
flag = false;
}
set.add(choice);
}
}
so I did it with Set in the end, only for salad, but it's the same for the rest, if someone else needs it.
your cases go by integer numbers, so an array of boolean with 1 element for every option.
boolean[] allowed = new boolean[options]; (faster than hasMap of string to boolean).
add a check just before the "switch" statement:
if(allowed[choice] && choice != 3) {...}
you should also create an integer constant STOP_OPTION or something like that and use it in the above if-statement and in the final "case" of your switch statement. in your example, set it to 3. then later you can change it without replacing all instances of "3" in your code. but that's more of a styling suggestion.
the "flag" boolean is also redundant, the while loop can just check if choice != 3. be careful of NumberFormatExceptions!
good luck!
So my main got deleted 2 days ago and my teacher helped me a bit with the switch code. I rebuilt the code yesterday and he was away yesterday and could not help me.
public static void main(String[] args) throws InterruptedException {
do {
try {
System.out.println("Enter your birthYear");
birthYear = Integer.parseInt(input.next());
int length = String.valueOf(birthYear).length();
System.out.println(length);
if (length != 4) {
lengthTest = false;
System.out.println("Invalid Choice");
} else {
lengthTest = true;
}
test = true;
} catch (Exception e) {
System.out.println("Invalid Choice");
}
} while (test == true ^ lengthTest != false);
do {
System.out.println("Please enter a number between 1-4 \n"
+ "1 = AreaOfTriangle \n" +
"----------------------------------\n" +
"2 = HoursToDaysAndHours Calculator \n" +
"---------------------------------- \n" +
"3 = CelciusToFahrenheit Calculator \n" +
"----------------------------------\n" +
"4 = BirthdayGame \r\n" +
"----------------------------------");
try {
choice = Integer.toString(input.nextInt()).charAt(0);
System.out.println(choice);
switch (choice) {
case 1:
aOT.areaOfTriangle();
break;
case 2:
hTDAH.hoursToDaysAndHours();
break;
case 3:
cTF.celciusToFahrenheit();
case 4:
System.out.println("Code not implemented");
break;
case 'e':
repeat = false;
break;
default:
System.out.println("");
break;
}
}catch (Exception e) {
System.out.println("Invalid Awnser");
}
} while (repeat == true);
}
My problem is in my switch case i want to be able to use int's and Char's at the same time. For example i want to use e to exit and and the 4 numbers
You can try to use String as an input paramenter, then any int value or char will be readed correctly without necessity to convert them:
try {
String choice = input.next();
System.out.println(choice);
switch (choice) {
case "1":
aOT.areaOfTriangle();
break;
case "2":
hTDAH.hoursToDaysAndHours();
break;
case "3":
cTF.celciusToFahrenheit();
case "4":
System.out.println("Code not implemented");
break;
case "e":
repeat = false;
break;
default:
System.out.println("");
break;
}
You can't use int and chars at the same time, as you can only use one variable and a variable has to have a type, but:
If you cast a char or Character to int you get values. For example ((int) 'e') evaluates to 101 if I am not mistaken. (Try System.out.println((int) 'e'));
So in your case, you can switch over int values and detect for 1,2,3,4 and 101.
Your default should also throw an exception and you are fine.
Happy Coding
You could just use the char representations of the digits 1-4:
char choice = input.next().charAt(0);
switch (choice) {
case '1':
aOT.areaOfTriangle();
break;
case '2':
hTDAH.hoursToDaysAndHours();
break;
case '3':
cTF.celciusToFahrenheit();
case '4':
System.out.println("Code not implemented");
break;
case 'e':
repeat = false;
break;
default:
System.out.println("");
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!
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++;
}
I'm basically trying to validate so that you can only enter an Integer. This is what I have at the moment, but if I type letters it goes through the switch and just leaves the result as blank.
I want it so that if anything other than an integer is entered it will go to default in the switch.
Any help would be great. Thanks!
while(loop && kb.hasNextInt())
{
choice = kb.nextInt();
switch(choice)
{
case 1 :
language = "FRENCH";
loop = false;
break;
case 2 :
language = "GERMAN";
loop = false;
break;
case 3 :
language = "SPANISH";
loop = false;
break;
default :
System.out.println("That is not a correct choice. Please try again!");
break;
}
}
If the next input is not an integer,
then .hasNextInt() will return false,
and therefore the loop will terminate early.
If you want to allow text input and respond to it,
then you need to read line by line, text instead of numbers,
and parse the line read with Integer.parseInt.
If the line cannot be parsed, you will get a NumberFormatException.
You can catch it, and handle appropriately.
while (loop && scanner.hasNextLine()) {
String line = scanner.nextLine();
try {
choice = Integer.parseInt(line);
} catch (NumberFormatException e) {
System.out.println("That is not an integer. Please try again!");
continue;
}
switch (choice) {
case 1:
language = "FRENCH";
loop = false;
break;
case 2:
language = "GERMAN";
loop = false;
break;
case 3:
language = "SPANISH";
loop = false;
break;
default:
System.out.println("That is not a correct choice. Please try again!");
break;
}
}
This is because a letter will cause your while(loop && kb.hasNextInt()) to be false. I suggest put an if statement with the hasNextInt() within the while loop.
Example (using a while loop instead of if statement to really try getting the number):
while(loop)
{
// validate int using while loop
while(!kb.hasNextInt())
{
System.out.println("you must enter a number! ");
kb.next();
}
choice = kb.nextInt();
switch(choice)
{
case 1 :
language = "FRENCH";
loop = false;
break;
case 2 :
language = "GERMAN";
loop = false;
break;
case 3 :
language = "SPANISH";
loop = false;
break;
}
}
System.out.println("Thank You " + studentID + " you have been registered for " + language);
This code will blow before it even begins if the user did not enter a number as the while required kb.hasNextInt() to be true (have a number) to even run.
What I do is that I usually put the validation around where I receive the input:
int choice;
Boolean retry = null;
while(retry == null) {
try{
String input = scanner.nextLine();
choice = Integer.parseInt(input);
retry = false;
}catch(NumberFormatException e){
System.out.println("Please enter a number from 1 to 4.");
}
}
switch(choice){
case 1:
// Do stuff
break;
case 2:
// Do stuff
break;
case 3:
// Do stuff
break;
case 4:
// Do stuff
break;
default:
System.out.println("Something went wrong!");
}