Am working on a problem, basic code is shown below, takes 4 possible inputs from the user, and produces a response based on which one is input. However I need to add a test to validate that the only 1 of the 4 possible answers has been input.
I know how I could compare 2 of the 4 inputs however not all 4 at once, can someone give me an idea? Would prefer to figure out the actual code myself but a pointer in the right direction would be beneficial.
So to clarify How to - If input is anything except "Bill, Circular, Postcard or Letter" produce Error Message X
System.out.println("What type of Letter has been received?");
System.out.println("Bill, Circular, Postcard or Letter");
String Letter = kybd.nextLine();
{
if (Letter.equalsIgnoreCase("Bill"))
{
System.out.println("Bills must be paid");
}
else if (Letter.equalsIgnoreCase("Circular"))
{
System.out.println("Circulars are thrown away");
}
else if (Letter.equalsIgnoreCase("Postcard"))
{
System.out.println("Postcards are put on the wall");
}
else if (Letter.equalsIgnoreCase("Letter"))
{
System.out.println("Personal letters are read and have replies written for them");
}
}
if (Letter.equalsIgnoreCase("Bill"))
{
System.out.println("Bills must be paid");
}
else if (Letter.equalsIgnoreCase("Circular"))
{
System.out.println("Circulars are thrown away");
}
else if (Letter.equalsIgnoreCase("Postcard"))
{
System.out.println("Postcards are put on the wall");
}
else if (Letter.equalsIgnoreCase("Letter"))
{
System.out.println("Personal letters are read and have replies written for them");
}else{
System.out.println("ERROR");
}
You want to throw an 'else' conditional statement in there, and you may want to look at try and catch blocks, or simply 'throw' a NoSuchElement exception in your 'else' conditional.
Looking at this may be useful to you:
http://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
Throwing an exception in an else statement would be a lot like the answer before mine, whereas a try...catch block is pretty much the test you're talking about. So, it could look something like this:
try
{
Letter != "Bill" //not exactly how it'd look, but this is a general idea on what you'd do here
}
catch (NoSuchElementException e)
{
System.out.println("Not a valid input.");
}
Related
I am very new to java and I am trying out error handling. I am pretty proficent in python and I know the error handling in python would go
while True:
try:
*some code*
except IndexError:
continue
break
I would like to know what the equivalent of a retry loop after exception is in java
EDIT:
This is what I have so far, however whenever a exception is thrown it does an infinite loop saying "Enter an Short: Error Try again."
while(true)
{
try {
System.out.print("Enter an Short: "); //SHORT
short myShort = reader.nextShort();
System.out.println(myShort);
break;
}
catch (InputMismatchException e) {
System.out.println("Error Try again.");
continue;
}
}
To clarify what exactly I would like is. When "InputMismatchException" is thrown the loop re runs and prompts the user again and it does this until the user gives the correct input. I hope that clarifies what I would like it to do.
What you have is almost good as #Thomas mentioned. Just need to add some brackets and semicolons. It should look line following code.
while(true){
try{
// some code
break; // Prevent infinite loop, success should break from the loop
} catch(Exception e) { // This would catch all exception, you can narrow it down ArrayIndexOutOfBoundsException
continue;
}
}
As your question asks about error handling and you showed IndexError as an example, the equivalent in Java could be:
try {
//*some code*
}
catch(ArrayIndexOutOfBoundsException exception) {
//handleYourExceptionHere(exception);
}
About ArrayIndexOutOfBoundsException, you take a look here, in the documentation. About Exceptions, in general, you can read here.
EDIT, according to your question edition, adding more information...
while(true)
{
try {
System.out.print("Enter a short: ");
short myShort = reader.nextShort();
System.out.println(myShort);
}
catch (InputMismatchException e) {
System.out.println("Error! Try again.");
//Handle the exception here...
break;
}
}
In this case, when the InputMismatchException occurs, the error message is exhibited and the break should leave the loop. I do not know yet if I understand well what you are asking, but I hope this helps.
To the help of #Slaw he determined that scanner would keep inputting the same value unless I closed it at the end of the loop and here is the working code.
while (true)
{
Scanner reader = new Scanner(System.in);
try
{
System.out.print("Enter an Short: "); //SHORT
short myShort = reader.nextShort();
System.out.println(myShort);
reader.close();
break;
}
catch (InputMismatchException e)
{
System.out.println("Error Try again.");
}
}
I am making a basic application where it trains your math skills. I have this code:
while (true)
{
try
{
int userAnswer;
System.out.println("Type quit to exit to the menu!");
int randInt = r.nextInt(num2);
System.out.println(num1 + " + " + randInt + " =");
userAnswer = in.nextInt();
if(userAnswer == num1 + randInt) System.out.println("Correct!");
else System.out.println("Wrong!");
break;
}
catch(Exception e)
{
}
}
When someone prints out a d or something in the answer, the try catch goes. But, then it goes to the while loop and repeatedly spams Type quit to exit to the menu and then something like 1 + 2 = infinitely... I think I know what's wrong, userAnswer has been assigned already as something that throws an exception that goes to the catch and it just keeps printing those and goes to the catch and goes back because userAnswer is already assigned. I think this is what is happening, I could be wrong. Please help!
EDIT: I forgot to make this clear, but I want the question to be re-printed again, exiting out of the loop goes to a menu where you can't get the question back, I want it to redo what's in the try catch...
You should never catch an Exception without handling it.
catch(Exception e)
{
System.out.println("An error has occured");
break;
}
This should stop your program from looping infinitely if an Exception occurs.
If user input comes as letter it will get an exception because you are trying to read(parse) as integer. So your catch clause is in the loop you have to write break in there to go out from loop.
Still i will suggest you to getline as string and than compare with your cli commands (quit in your case) than you can try to parse it as an integer and handle loop logic.
You're not breaking the while loop if there is a mismatch
while(true)
{
try
{
}
catch(InputMisMatchException e)//I suggest you to use the exact exception to avoid others being ignored
{
System.out.println("Thank you!");
break;//breaks the while loop
}
}
Yoy're not breaking the loop in case of Exception occurs.
Add break; statement in the catch block to run your program without going to infinite loop, in case exception occurs.
Since the given answers don't match your requirement I'll solve that "riddle" for you.
I guess what you didn't knew is that the scanner won't read the next token if it doesn't match the expectation. So, if you call in.nextInt() and the next token is not a number, then the scanner will throw an InputMismatchException and keeps the reader position where it is. So if you try it again (due to the loop), then it will throw this exception again. To avoid this you have to consume the erroneous token:
catch (Exception e) {
// exception handling
in.next();
}
This will consume the bad token, so in.nextInt() can accept a new token. Also there is no need to add break here.
Mind that in.next() reads only one token, which is delimited by a whitespace. So if the user enters a b c, then your code will throw three exception and therefore generate three different question befor the user can enter a number. You can avoid that by using in.nextLine() instead. But this can lead into another problem: Scanner issue when using nextLine after nextXXX, so pay attention to that :).
I have this particular code somewhere in my program.
while(scanner.hasNext()){
contents = scanner.nextLine();
if((contents.contains(username))&&(contents.contains(password))){
call.fileManager();
}
if((!contents.contains(username))&&(!contents.contains(password))){
JOptionPane.showMessageDialog(null, "Invalid username/password! Check your spelling/capitalization.", "Error!", JOptionPane.ERROR_MESSAGE);
call.loginFrame();
}
}
I'd like the loop to quit once the condition is satisfied. For example, if a specific content is found in the file, it would go to the first if, then call the file manager and exit. If the content is not found, it will go to the second if statement instead.
UPDATE:
It seems like I have forgotten break. I'm sorry for this stupid question :)
UPDATE:
No, break did not solve my problem. Something more of that did. I used counter to read each line and a counter to decrement and increment. After that I subtracted the counter decremented/incremented from the counter which reads the line. Of course if nothing was read, it would return a 0.
Use break like below
while (obj != null) {
if (obj == null) {
break;
}
}
For your code it would be something like this
while (scanner.hasNext()) {
contents = scanner.nextLine();
if ((contents.contains(username)) && (contents.contains(password))) {
call.fileManager();
break;
}
if ((!contents.contains(username)) && (!contents.contains(password))) {
JOptionPane.showMessageDialog(null, "Invalid username/password! Check your spelling/capitalization.", "Error!", JOptionPane.ERROR_MESSAGE);
call.loginFrame();
break;
}
}
You can use break to terminate the while loop. Also, at a given point, only one of the condition will be satisfied. So use if...else construction for better performance (though, the difference won't be clearly visible in this case!).
But it definitely reduces the work of the compiler internally.
while(scanner.hasNext())
{
contents = scanner.nextLine();
if((contents.contains(username))&&(contents.contains(password)))
{
call.fileManager();
break;
}
else
{
JOptionPane.showMessageDialog(null, "Invalid username/password! Check your spelling/capitalization.", "Error!", JOptionPane.ERROR_MESSAGE);
call.loginFrame();
break;
}
}
For some reason this program won't loop correctly, its supposed to wait for user input, then decide on weather or not it should loop.Instead, it skips the user input part, goes straight to deciding it needs to loop, then allows user input to be taken into account.
For example, it asks for a number, i type 5, then it says "would you like to go again?" "Please use either yes or no, case sensitive!" "would you like to go again?".After it has run that it will accept user input,I thought about using a sleep(2000),but I don't want it to just skip over and assume the user didn't put anything in.I am stumped! keep in mind this is my second day working with java. I am a newbie and this is only the 3rd program i am working on. I had this issue on another program but i managed to fix it just fine.However this one seems to not want to work in the same fashion despite the fact that i did framework exactly the same.
do {
System.out.println("would you like to go again?");
if (input.hasNextLine()){
again = input.nextLine();
if (again.equals("yes")){
yon2 = false;
dateconverter.main(args);
}else if (again.equals("no")){
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
}else{
yon2 = true;
System.out.println("Please use either yes or no. caps sensative!");
}
}
} while (!(yon2 = false));
Java loops correctly. However, yon2 = false is an assignment and not a comparison.
Thus the loop is equivalent to:
do {
// ..
yon2 = false; // assign! :(
} while (!yon2);
So Java is doing exactly what it was told to do.
Now, with that out of the way, I believe the other issue is being confused about the variables usage. Consider this:
boolean askAgain = true;
do {
System.out.println("would you like to go again?");
if (input.hasNextLine()){
String again = input.nextLine();
if (again.equals("yes")){
// Finally done asking
askAgain = false;
dateconverter.main(args);
} else if (again.equals("no")){
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
} else {
// If we're here, we still need to ask again
System.out.println("Please use either yes or no. caps sensative!");
}
} else {
// no more lines! do something sensible
System.exit(0);
}
// Loop while we need to ask again!
// Note that the negative is removed
} while (askAgain);
However, taking a second to refactor this allows for something easier to read later and avoids the dealing with a flag entirely:
boolean promptKeepPlaying (Scanner input) {
while (input.hasNextLine()){
System.out.println("would you like to go again?");
String again = input.nextLine();
if (again.equalsIgnoreCase("yes")){
return true;
} else if (again.equalsIgnoreCase("no")){
return false;
} else {
System.out.println("Please use either yes or no.");
}
}
// no more lines
return false;
}
// somewhere else
if (promptKeepPlaying(input)) {
// restart game
dateconverter.main(args);
} else {
// exit game
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
}
You've got a bug in your program. You've accidentally written an assignment instead of an equality test.
However, the real lesson here is that you should not be writing cumbersome == and != tests involving booleans. There are simpler, more elegant and less error prone ways of writing the tests. For example, assuming that condition is a boolean.
condition == true is the same as condition
condition == false is the same as !condition
!(condition == false) is the same as condition
condition == condition2 is the same as !(condition ^ condition2)1.
There is a real benefit in taking the time to write your code simply and elegantly.
1 - This is an example where == is more elegant ... but the ^ exclusive-or operator avoids the accidental assignment trap.
I'm writing a straight forward Airport Terminal style program for class. I'm going beyond the scope of the assignment and "attempting" to use Try/Catch blocks...
However Java is being that guy right now.
The problem is that when someone enters a non-letter into the following code it doesn't catch then return to the try block it caught...
Why?
Edit - Also the containsOnlyLetters method works, unless someone thinks that could be the error?
System.out.println("\nGood News! That seat is available");
try
{//try
System.out.print("Enter your first name: ");
temp = input.nextLine();
if (containsOnlyLetters(temp))
firstName = temp;
else
throw new Exception("First name must contain"
+ " only letters");
System.out.print("Enter your last name: ");
temp = input.nextLine();
if (containsOnlyLetters(temp))
lastName = temp;
else
throw new Exception("Last name must contain"
+ " only letters");
}//end try
catch(Exception e)
{//catch
System.out.println(e.getMessage());
System.out.println("\nPlease try again... ");
}//end catch
passengers[clients] = new clientInfo
(firstName, lastName, clients, request, i);
bookSeat(i);
done = true;
You seem to misunderstand the purpose and mechanism of try/catch.
It's not intended for general flow control, and more specifically, the meaning is not that the try block is repeated until it finishes without an exception. Instead, the block is run only once, the point is that the catch block will only execute if a matching exception is thrown.
You should use a while loop and if clauses for your code, not try/catch.
If a Throwable or Error is generated it won't be caught by your handler. You could try catching Throwable instead.
What do you mean when you say
when someone enters a non-letter into the following code it doesn't catch then return to the try block it caught...
It is not clear the outcome you expect, are u thinking that once the exception is caught, control will go back into the try block? That is not how it is intended to work.
When an exception is thrown, the control goes to the appropriate catch/finally blocks and then moves ahead, remaining lines in the try block are not executed