How to loop java with incorrect input - java

I'm currently learning how to code and I'm facing a bit of a problem, and I was hoping someone could help me out. Currently, Im creating a program that prompts for military status and shows appropriate discounts, but I would like it to loop if the answer isn't one of the given options.
This is my code:
public static void main(String[] args)
{
char milID = ' ';
char status = ' ';
String validMilitaryID = JOptionPane.showInputDialog("Do you have a valid military ID?");
milID = validMilitaryID.charAt(0);
Scanner valid = new Scanner(System.in);
if (milID == 'Y') {
System.out.printf("%n Are you Active Duty, Retired, or a Dependant?");
status = valid.nextLine().charAt(0);
} else if (milID == 'y'){
System.out.printf("%n Are you Active Duty, Retired, or a Dependant?");
status = valid.nextLine().charAt(0);
}else{
JOptionPane.showMessageDialog(null, "Sorry, you are currently ineligible for a Military Discount");
System.exit(0);
}
if (status == 'A'){
JOptionPane.showMessageDialog(null, "Congratulations! You are eligible to recieve a 15% discount!");
} else if (status == 'R'){
JOptionPane.showMessageDialog(null, "Congratulations! You are eligible to recieve a 13% discount!");
}else if ( status == 'D'){
JOptionPane.showMessageDialog(null, "Congratulations! You are eligible to recieve a 10% discount!");
} else {
JOptionPane.showMessageDialog(null, "Sorry! That was not a valid answer.");
}
System.exit(0);
}//END MAIN
If anyone is able to help, can you explain the process as well. Since I am new to Java I would like to learn rather than just have a fix.
Thank you!!

1) you may call your input as well as your if code into a while loop
2) maybe use a switch instead of if..else if
something from the logic such as:
boolean checkInput = true;
while (checkInput) {
// now get your input... not coded
switch (milId) {
case "y","Y": bla bla, break;
case "x","X": bla bla, break;
otherwise: bla bla, break;
}}
3) use a variable for your account value; you could code this with a lookup

An integral part of Java (or programming in general) is missing from your code, and that is the "while loop". I do not know how much knowledge of Java you have so far, but a while loop repeats what's in its block of code until a requirement is met. If you are adding a feature that repeats the survey if the wrong input is given, a while loop at the beginning of your conditionals is what you need.
Pseudocode
create variable called correctAnswer
Do you have a military id? Enter y or Y if yes, any other key for no
if yes, correctAnswer = 1
if no, correctAnswer = 0 and while loop is skipped
while correctAnswer = 1
{
Are you active, retired, etc?
If yes, what is your status?
if A, R, or D is given, display congrats message. correctAnswer = 0 //end
if anything other than A, R or D is given, then correctAnswer = 1 //repeat
}
The while loop in the second block of conditionals keeps repeating the loop until a correct answer is given.

Related

Ask for input again if wrong input is entered

I am new to Java programming. I want the program to ask for input again if wrong input is entered by the user. What must I do? Please help! Jump to the 'if else if' part if you want to avoid the mess... And not being rude but please don't request for closing the question if you can't answer.
case 'A': case 'a':
System.out.println("You selected NOS Tank.");
int price;
double quantity;
double variant=0;
System.out.println("Select the variant: ");
System.out.println("Enter 'D' without apostrophe for dry or 'W' for wet");
variant=xss.next().charAt(0);
if (variant=='D' || variant=='d')
{
System.out.println("The price of dry nitrous oxide system is: $600");
}
else if (variant=='w' || variant=='W')
{
System.out.println("The price of wet nitrous oxide is: $740");
}
else
{
System.out.println("Invalid input.");
}
It has been 28 days since you asked your doubt so I don't know if you have come across the answer or not but here's my solution.
To accept the correct input you need to make use of a while loop, loops are iterations in java which run for multiple number of times as per the given instructions. In this program I have incorporated a while loop whose condition is true always, so basically it is an infinite loop. If the inputted variant is correct and matches with any one of the if condition then the loop will break automatically because of the "break;" statement.
break; is a jump statement in java which allows you to terminate a loop when your requirements are met.
Given below is your required program code.
Hope this solves you query :)
case 'A': case 'a':
System.out.println("You selected NOS Tank.");
int price;
double quantity;
double variant=0;
System.out.println("Select the variant: ");
while(true)
{
System.out.println("Enter 'D' without apostrophe for dry or 'W' for wet");
variant=xss.next().charAt(0);
if (variant=='D' || variant=='d')
{
System.out.println("The price of dry nitrous oxide system is: $600");
break;
}
else if (variant=='w' || variant=='W')
{
System.out.println("The price of wet nitrous oxide is: $740");
break;
}
else
{
System.out.println("Invalid input.");
System.out.println("Please enter the variant again:");
}
}

Java NumberFormatException when using Integer.parseInt

I have truly searched for the answer all over the Internet before coming here and I think that the answer will have something to do with the try/catch statements, but even after watching a couple tutorials on the topic I am not sure on how to implement that.
Anyways, I am trying to do a simple thing in my newbie reminders app that I am making (I am learning Java as my first language for about 3 months now).
I want the program to check the user's input and if it is a certain letter ("R") I want the program to do a certain stuff. If it is an integer from 0 to 100 then I want to do other stuff. And if its neither of them, then I want the "else" statement to work.
The issue that I can't get the "else" statement to work as I get the NumberFormatException error. For example if I enter some other letter i.e. "d" - I get this error message:
Exception in thread "main" java.lang.NumberFormatException: For input
string: "d" at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580) at
java.lang.Integer.parseInt(Integer.java:615) at
mash.Dialogue.startDialogue(Dialogue.java:51) at
mash.Dialogue.newRem(Dialogue.java:27) at
mash.Dialogue.startDialogue(Dialogue.java:38) at
mash.Dialogue.start(Dialogue.java:13) at mash.Main.main(Main.java:9)
Here is the code (I am sorry for any readability issues, this is the first time ever I am showing my code to somebody). You don't have to read the else if statement, as the issue seems to not depend on the text inside of that statement.
I would really appreciate if anybody could point me what is wrong with the code and how I would get to do what I intended. Some newcomer-friendly solution will be much appreciated.
Thank you in advance!
String secondLetter = mash.nextLine();
if(secondLetter.equals("r") || secondLetter.equals("R")) { //if the user enters R - create a new Reminder
newRem();
}
else if((Integer.parseInt(secondLetter) >= 0) && (Integer.parseInt(secondLetter) < maximum)) { //if the user enters number - check task list
tasks.remText(Integer.parseInt(secondLetter));
System.out.println("Enter 'D' to set the reminder as Done. Or enter 'T' to return to the list");
String v = mash.nextLine();
System.out.println(v);
if(v.equals("d")|| v.equals("D")) { //if user enters D - set the reminder as done
tasks.setDone(Integer.parseInt(secondLetter));
System.out.println("The reminder is now added to 'Done' list");
}
else if(v.equals("t")|| v.equals("T")) { //if user enters T - return to the list of reminders
tasks.display();
}
else {
System.out.println("Please enter the correct symbol");
}
}
else {
System.out.println("Enter the correct symbol");
}
You can check your input if it's a valid number before attempting to convert it. For example:
if(!secondLetter.matches("[0-9]+")) {
//it's not a number, so dont attempt to parse it to an int
}
place it in your if/else like this:
if(secondLetter.equals("r") || secondLetter.equals("R")) {
newRem();
} else if(!secondLetter.matches("[0-9]+")){
System.out.println("please type r or R or a number");
} else if((Integer.parseInt(secondLetter) >= 0) && ...
Short answer: docs.oracle.
Complete answer:
You can use Integer.parsInt (String s) only on a string that can be parserized into an integer. The letter "R" can not be a number, so it generates an exception.
if(Character.isLetter(secondLetter) && "R".equalsIgnoreCase(secondLetter)){
do code with "R"
}else if(Integer.parseInt(secondLetter) > 0 && Integer.parseInt(secondLetter) < 100){
do code with 0 < number < 100
}else{
do something else
}

Why is my code in Java giving me so much trouble with if else statements in this specific line of code in Jgrasp?

Learning Java, now I do not know why but this code keeps giving me issues with else if statements.
public class Sherlock
{
public static void main(String[] args)
{
String answer = "Watson";
String response = "";
int tries = 0;
Scanner input = new Scanner(System.in);
while (tries <=3);
{
System.out.print("Enter the name of Sherlock's partner, and dear friend. ");
response = input.nextLine();
tries++;
if (response.equals ("Watson"))
while (tries<= 3)
{
System.out.println("Yes, that is right, Barrel Rider.");
break;
}
else if (tries == 3)
{
System.out.println("Ooooh, sorry kid but it looks like you are S.O.L.");
break;
}
else
while (tries <= 3)
{
System.out.println("Sorry, try again!");
}
}
}
}
The if else statement error has been more or less solved, but now I'm getting a different error:
Sherlock.java:24: error: break outside switch or loop
break;
^
1 error
Why does it keep insisting I put break outside the switch or loop?
remove the semi-colons from the if statement
if (response.equals ("Watson"))
And the while loop
while (tries <=3)
These semi-colons are messing up the parsing of your control statements. The reason why the semi-colon after the if-statement messes things up is that the parser doesn't expect there to be a body due to the presence of the semi-colon, and therefore it doesn't expect there to be an else statement after an if-statement with no body.
In the future, I suggest that you make sure that you have checked your code for valid semantics and syntax. You will learn the basics about control statements from any good tutorial on YouTube.

Trouble returning to command options using loops/ only one command is being run (JAVA)

This is my first time on this site. I am taking a course in Java right now and I am having some trouble with this code/program that I am supposed to make that allows the user to select whether they want to see "good monkeys", "bad monkeys" or "show monkeys". It is nowhere near done but I am having trouble returning to the command screen/area after a command is completed. I would like the commands to be used as many times as possible. Secondly, my program treats every input if someone put in "Good Monkey". So if you put in a word like "pineapple", it will still greet you with the output designated for the "Good Monkeys" input.
I've looked online and seen that maybe I should use a "do-while" loop and use "switch". Any input/ help would be greatly appreciated. Thank you so much!
Here is my code: public class and public static and Scanner import are in this code, but for some reason I cannot add them into this post without messing up the formatting of the code.
Scanner jScanner = new Scanner(System.in);
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
String userChoice = jScanner.nextLine();
for (int b= 1; b < 11000; b++)
{
if (userChoice.equalsIgnoreCase("Good Monkeys"));
{
System.out.println("You have selected Good Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner goodMonkeyScanner = new Scanner (System.in);
int userChoiceGood = goodMonkeyScanner.nextInt();
if (userChoiceGood >= 3 && userChoiceGood <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else if (userChoice.equalsIgnoreCase("Bad Monkeys"))
{
System.out.println("You have selected Bad Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner badMonkeyScanner = new Scanner (System.in);
int userChoiceBad = badMonkeyScanner.nextInt();
if (userChoiceBad >= 3 && userChoiceBad <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else
System.out.println("Sorry this doesn't work");
}
else if ((userChoice.equalsIgnoreCase("Show Monkeys")))
{
System.out.println("Monkeys");
System.out.println("0");
System.out.println("\\/");
System.out.println(" |");
System.out.println("/\\");
break;
}
else
{
System.out.println(" Wrong Answer. Try again");
}
break;
}
}
}
}
First, you need to define the loop. Second, you need to put the input instruction inside the loop.
I'll include a done variable to detect when the user wants to escape
So, let's code:
Scanner jScanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
System.out.println("(or enter 'done' to exit");
String userChoice = jScanner.nextLine();
swithc(userChoice.toLowerCase()) {
case "good monkeys":
/*
* The code for this option
*/
break;
case "bad monkeys":
/*
* The code for this option
*/
break;
case "show monkeys":
/*
* The code for this option
*/
break;
case "done":
done = true;
break;
default:
System.out.println("Your input isn't what I expected!\nTry again!");
break;
}
}
The code, explained:
That while(!done) stuff can be read as "while 'not done' do what follows"
userChoice.toLowerCase(): I convert the userChoice to lower-case, to simplify comparissons. That way, I only need to compare the string with other lower-case strings
switch(userChoice.toLowerCase()): ... hmmm... I think you can figure it out yourself ;)
That default block is what happens if no other case is valid
The "done" block will set the done variable to true, and thus it will terminate the loop
Important: ALWAYS end the case blocks with break
Further reading:
The Java Tutorials: Language basics
The while and do-while statements
The switch statement
Also, I recommend you study Flowcharts and, before start coding, try to draw in paper a flowchart of your program. That way, you will have a clear image of your program before you start writing the very first line of code.

JAVA: Menu Infinite-loop

This is a follow up to a question I have asked previously that did get answers that should have fixed my problem, but unfortunately did not. My program reads in a text file and organises data before giving the user a number of options. When the program gets to this point I want to user to be able to select an option, that performs an operations, but then returns the user back to the start point to be able to perform more operations. This is the answer I liked best (thanks to Octopus) and am currently trying to implement.
//set choiceentry to -1, this will make it to enter while loop
int choiceentry = -1
while(choiceentry < 1 || choiceentry > 3){
System.out.println("Enter \"1\", \"2\" or \"3\"");
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
switch(choiceentry){
case 1:
//do logic
break;
case 2:
//do logic
break;
case 3:
//do logic
break;
}
}
As I see it, the program should enter the loop initially, allow the user to input a selection, then return back to "enter a value". However, the program does not return, and terminates after one operation. How can I prevent this to continue the program running infinitely?
Thanks in advance!
The current while loop is there to get valid input -- don't change it.
You need to wrap this code in another while loop that loops til a sentinal value is entered.
while (!isSentinalValue) {
while (inputNotValid) {
// get valid input
}
}
Edit
More specifically in pseudocode:
while (!isSentinalValue) {
input = invalidValue
while (inputNotValid) {
getInput
}
use input to do menu things
}
So I would not have the switch block inside of the inner loop, since that loop concerns itself only with making sure that the input entered is valid. Do the switch block outside of the inner loop, and be sure to set the sentintal value that allows the user to escape the outerloop when appropriate.
Your while(choiceentry < 1 || choiceentry > 3) condition is wrong. If you want it to loop , then you have to make it between 1 and 3 .
So this also means that you will have to change your choiceentry initialization value. This will work.
int choiceentry = 1
while(choiceentry >=1 && choiceentry <= 3){
System.out.println("Enter \"1\", \"2\" or \"3\"");
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
....
}
your loop only runs while choiceentry is less than 1 or greater than 3. As soon as the user enters one of those values, the loop exits.
Learn to use a debugger.
place the following code after switch
if(choiceentry == 4){
break;
}
Now when you will input 4 then it will be terminated, you can use any value other then 4
Use break only when user wants to quit(Say when choiceentry=0). You can use "continue" to make loop infinite. Sample code is given for reference
int choiceentry = 1; // can set any int value except 0 (exit code is 0 for this example)
Scanner scanchoice = null;
while (choiceentry != 0) {
System.out.println("Enter \"1\", \"2\" or \"3\" ..Press 0 to quit");
scanchoice = new Scanner(System.in);
if (scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
// System.out.println("choiceentry=" + choiceentry);
switch (choiceentry) {
case 0:
{
System.out.println("Bye Bye");
break;
}
case 1:
{
System.out.println("In Case 1");
continue;
}
case 2: {
System.out.println("In Case 2");
continue;
}
case 3: {
System.out.println("In Case 3");
continue;
}
}
}

Categories