So I'm currently dealing with this [keep in mind I cut most of the code out cause it's quite long]
int choice = 0;
while (choice != 7){
System.out.println("--- Mathematical Calculator ---");
System.out.println("");
System.out.println("Pick an operation from the list - Use nos. 1 to 7");
System.out.println("1) Multiplication");
System.out.println("2) Division");
System.out.println("3) Addition");
System.out.println("4) Subtraction");
System.out.println("5) Find the area of a regular object");
System.out.println("6) Find the volume of a regular object");
System.out.println("7) Exit Program");
**boolean ok = false;
do {
try{
choice = userInput.nextInt();
ok = true;
} catch (InputMismatchException e){
System.out.println("Invalid input");
}
}
while (ok = false);**
switch (choice) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
System.out.println("Thanks for using my program");
System.out.println("Program terminated");
break;
default: System.out.println("Invalid choice");
}
}
userInput.close();
}
So currently, when I run the program and enter something that is NOT an integer, the program will give the following output:
--- Mathematical Calculator ---
Pick an operation from the list - Use nos. 1 to 7
1) Multiplication
2) Division
3) Addition
4) Subtraction
5) Find the area of a regular object
6) Find the volume of a regular object
7) Exit Program
Invalid input
Invalid choice
Over
And over
And over
I know I've probably done something wrong with the exception handling (program works fine with valid input), but I really don't know how I can fix it.
Help?
You need to catch the \n\r with an userInput.nextLine() in your exception and it stops printing for ever like this
catch (InputMismatchException e){
System.out.println("Invalid input");
userInput.nextLine();
}
while (ok = false); should be while (ok == false);, or while (!ok);.
ok = false is an assignment.
Also, I guess you have intentionally left the cases empty, but even so, make sure that you put a break; on each of them, otherwise the option 7 will always be executed.
EDIT: for the infinite loop, you should also do what Kevin Esche suggests in his answer (+1).
Related
I'm making this program that lists websites, username, and password data (kind of like a passwords manager), and in the console I get this:
Select: Not a valid entry! repeats twice
I'm not sure why this is happening, but here is the code block:
System.out.print("PASSCODE: ");
passcode = (char) System.in.read();
if(passcode == '}'){
System.out.println("Welcome! Enter 'Q' to exit at any time!");
System.out.println("1) Website A \n2) Website B \n3) Website C \n4) Website D");
for(;(char) choice != 'Q';){
System.out.print("SELECT: ");
choice = (char) System.in.read();
switch(choice){
case '1':
websiteA.Display();
break;
case '2':
websiteB.Display();
break;
case '3':
websiteC.Display();
break;
case '4':
websiteD.Display();
break;
default:
System.out.println("\nNot a valid entry!");
}
}
} else {System.out.println("ACCESS DENIED");}
I'm confused, because I would think the code would halt at System.in.read() in the for loop.
Aside from the objects, everything here is a conglomeration of what I've learned up to chapter 3 from Java: A Beginner's Guide Eight Edition by Herbert Schildt. So I'm still somewhat new to this.
When you enter a char, there's actually 2 char sent, the first one is your key, the second is the line break char code, aka \n. So with the loop, it will process twice for each choice.
I noticed a problem while I was programming in Java. It has been ~6 years since I've messed with Java (I've been doing front end design and development and haven't needed to program with Java since High School). I was trying to refresh my mind and do some object oriented programming and came across an issue I haven't seen before.
I was trying to setup a school database (more specifically a simple interface), and my else statement always ran even after my if statement passed. Can anyone explain to me why the else statement would run even when the if statement passes?
else {
System.out.println("Bart, come to Principal Skinner's office immediately. You broke the system. \n");
}
I wasn't able to fix this until I changed my else statement to an else if statement (to specifically disclude those if statements).
else if(!input.equals("1") && !input.equals("2") && !input.equals("3") && !input.equals("4"))
{
System.out.println("Bart, come to Principal Skinner's office immediately. You broke the system. \n");
}
Here is what the code was:
Scanner scanner = new Scanner(System.in);
int end = 0;
while(end == 0)
{
System.out.println("Welcome to Springfield Elementary School");
System.out.println("----------------------------------------");
System.out.println("Please select from the following options");
System.out.println("1) Add Course");
System.out.println("2) Remove Course");
System.out.println("3) View All Courses");
System.out.println("4) Exit");
System.out.print("-->");
String input = scanner.nextLine();
if(input.equals("1"))
{
System.out.println("That function is currently unavailable at this time");
}
if(input.equals("2"))
{
System.out.println("That function is currently unavailable at this time");
}
if(input.equals("3"))
{
System.out.println("That function is currently unavailable at this time");
}
if(input.equals("4"))
{
end = 1;
System.out.println("Thanks for accessing the Springfield Elementary School Database. Have a nice day.");
}
else {
System.out.println("Bart, come to Principal Skinner's office immediately. You broke the system. \n");
}
}
I'm not really interested in if this works or not, but why this else if works and the else statement doesn't. This isn't for school or work, but for pure learning. From my understanding of if statements, if they passed, they should skip all other conditional statements, unless it is an else if. This would seem to contradict that.
Why is my else statement always running inside my while loop?
If statements are very simple, and the problem you ran into was very simple as well. When you do
if(cond1){
code1
}
if(cond2){
code2
}else{
code3
}
It evalutes, if cond1 is true, then run cond 1. Then it does: if cond2 is true, run code2, otherwise (else) run code3.
You had all your if statements separate so the only one the else applied to was the last one. What you were looking for was an else-if.
e.g.
if(cond1){
code1
}else if(cond2){
code2
}else{
code3
}
This will only run that last else statement if all of your if statements evaluate to false.
Alternatively you can use a switch statement, these can be more confusing and sometimes more powerful, so I'll just link to it and let you read about it. https://www.w3schools.com/java/java_switch.asp
else is only applicable to the last if statement(the one checking for "4"), if you don't want to check other conditions once one is true, either use switch or add continue; inside if.
i.e.:
if(input.equals("1")) {
System.out.println("That function is currently unavailable at this time");
continue;
}
if(input.equals("2")) {
System.out.println("That function is currently unavailable at this time");
continue;
}
...
switch example:
Scanner scanner = new Scanner(System.in);
int end = 0;
while(end == 0)
{
System.out.println("Welcome to Springfield Elementary School");
System.out.println("----------------------------------------");
System.out.println("Please select from the following options");
System.out.println("1) Add Course");
System.out.println("2) Remove Course");
System.out.println("3) View All Courses");
System.out.println("4) Exit");
System.out.print("-->");
String input = scanner.nextLine();
switch(input) {
case "1":
case "2":
case "3":
System.out.println("That function is currently unavailable at this time");
break;
case "4":
end = 1;
System.out.println("Thanks for accessing the Springfield Elementary School Database. Have a nice day.");
break;
deafult:
System.out.println("Bart, come to Principal Skinner's office immediately. You broke the system. \n");
}
}
first question:
There is a do while loop, within the do section there is a switch. After selection case 1, some calculations are done, two options can result as shown in the If statement. My problem is code runs until the break; then just goes straight back to the menu loop. My question: how do i get the program to print the output for the user, then continue the menu loop?
Second question:
In case 1 there are two resulting options, the first being a failed response. from here, how do i get the program to loop back to the start of case 1 to ask for user input again? Even back to the main menu would be fine.
public static void showMenu() {
System.out.print('\u000c');
System.out.println("1 - Compute Change \n");
System.out.println("2 - Estimate Feast \n");
System.out.println("3 - \n");
System.out.println("4 - \n");
System.out.println("5 - I'm broke, get me out of here\n");
System.out.println("Select Option:\n");
}
public StackPost() {
System.out.println("Welcome to the Bank of Winterfell");
Scanner in = new Scanner(System.in);
do {
showMenu();
selection = in.nextInt();
switch (selection) {
case 1:
// get input, compute then decision:
if (something<somethingElse) {
// false response -
} else {
// correct response - system prints out some stuff back to user, back to main
// menu loop
}
break;
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
You could print "Press enter to continue" (or whatever you want to give notice of before locking the program), and add a call to Scanner#nextLine() before your break. This will lock the progression 'till user presses enter.
case 2:
// Some code here...
// Done, now show result and tell user to press any key to continue
System.out.println("Some fancy result from case handle code");
System.out.println("Press enter to continue...");
in.nextLine();
break;
You could add a while-loop that won't let the code continue 'till whatever input is expected in the first case is acceptable.
case 1:
System.out.println("Some handle that tells user to input something, and what is acceptable");
String input = null;
while(!(input = in.nextLine()).equals("something")) {
System.out.println("Wrong input, try again...");
}
// Input is acceptable, now do something with it...
System.out.println(input);
System.out.println("Press enter to continue...");
in.nextLine();
break;
Be aware, in your code, you call Scanner#nextInt(), and #nextInt doesn't consume the \n from pressing enter, and will thus be transferred into the switch case's usage of #nextLine(). You could avoid this with selection = Integer.parseInt(in.nextLine()).
You can use achieve it by:
For First question: Using return statement in case of correct response.
For Second question: Using while loop in case 1
After implementaing the proposed solution the StackPost() method will look like following. You can see the complete working code here:
public static void StackPost()
{
System.out.println("Welcome to the Bank of Winterfell");
try(Scanner in = new Scanner(System.in))
{
int selection;
do
{
showMenu();
selection = in.nextInt();
switch (selection)
{
case 1:
// get input, compute then decision:
while(true)
{
int something = in.nextInt();
int somethingElse = in.nextInt();
if (!(something<somethingElse)) {
// correct response - system prints out some stuff back to user, back to main
System.out.println("Print here the result");
// menu loop
return;
}
// false response - continue for next iteration in while-loop
}
//No need of 'break;' here
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
}
Note: It is best practice to use try-with-resources while handling system resources which implements AutoCloseable interface.
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)
I am trying to make a simple calculator program where a user can opt to do an operation and enter the numbers as long as he/she wishes to.
I just have problem because whenever I would reach inside my loop and ask the user if he/she want to continue and whenever I would run the program, I would have an "Exception in thread "main" java.lang.NullPointerException"
Scanner myInput=new Scanner(System.in);
System.out.print("Do you have numbers to compute?");
ans=myInput.findInLine(".").charAt(0);
while ((ans=='Y')||(ans=='y'))
{
//get the numbers
//provide the menu
//get the user's choice
switch (calc)
{
case 1: out.println("Sum is: " +(num1+num2)); break;
case 2: out.println("Difference is: " +(num1-num2)); break;
case 3: out.println("Product is: " +(num1*num2)); break;
case 4: out.println("Quotient is: " +(num1/num2)); break;
case 5: out.println("Modulo is is: " +(num1%num2)); break;
case 6: out.println("Sum is: " +(num1+num2));
out.println("Difference is: " +(num1-num2));
out.println("Product is: " +(num1*num2));
out.println("Quotient is: " +(num1/num2));
out.println("Modulo is is: " +(num1%num2)); break;
default: out.println("Invalid."); break;
}
out.println("Compute another?");
ans=myInput.findInLine(".").charAt(0);
}
May I humbly ask what can I do with this program so that it will ask again for the user's input whether to continue or not? Thanks in advance for your help.
in this palce, best way is to use do-while
do{
System.out.print("Do you have numbers to compute?");
ans=myInput.findInLine(".").charAt(0);
//
//
//
}while ((ans=='Y')||(ans=='y'));
This will keep asking till the user's answer is 'Y' or 'y'.
I hope you can take care of other thing.
for using while loop.
System.out.print("Do you have numbers to compute?");
char ans=myInput.findInLine(".").charAt(0);
while((ans=='Y')||(ans=='y')){
//
//
//
System.out.print("Do you have numbers to compute?");
ans=myInput.findInLine(".").charAt(0);
}
The NullPointerException is being thrown as Scanner.findInLine() can return null if it does not find the requested String/Pattern. The code invokes the method charAt(0) on the null String. Changing the code to the following will resolve this:
Scanner myInput=new Scanner(System.in);
char ans;
System.out.print("Do you have numbers to compute?");
ans=myInput.findInLine(".").charAt(0);
while ((ans=='Y')||(ans=='y'))
{
// Code omitted
System.out.print("Compute another?");
myInput.nextLine();
String s = myInput.findInLine(".");
ans = (null == s) ? 'n' : s.charAt(0);
}