Try block starts printing while printStackTrace method is Printing - java

public class Argon {
public static void main(String[] args) {
Basil basil = new Basil();
Scanner in = new Scanner(System.in);
do {
try {
System.out.println("Please enter a number!");
String num1 = in.nextLine();
System.out.println("Please enter another number!");
String num2 = in.nextLine();
basil.numberCruncher(num1, num2);
System.out.println(basil.getSum());
break;
} catch (NumberException e) {
e.printStackTrace();
}
} while (true);
}
}
The code above works tries a block of code and catches any errors that occur. I purposefully supplied an error and the code prints the following.
Please enter a number!
nop
Please enter another number!
w
NumberException: Your Program Went Bananas.
Please enter a number!
at Basil.numberCruncher(Basil.java:23)
at Argon.main(Argon.java:15)
The Stack Trace has not been fully printed, but the try block starts executing anyways.
Why does this occur and what could I do to fix it?

Throwable#printStackTrace prints to System.err by default. You're printing to System.out. Since there's only one console, it receives both of those streams.
Whatever controls the console you see must be doing its own buffering and flushing which does not synchronize the writes from each stream and that can cause mixed output even though the program executed sequentially.

Related

Java: Program crashes after inputting two bad values

I coded a program, that calculates the gcd (greatest common divisor) and lcm (least common multiple). Everything works fine except the try {...} catch(...) {...}. Here is the part of the code that doesn't work as I want it to:
try {
num1 = Integer.parseInt(sc.nextLine());
}
catch(Exception e) {
System.out.println("Your input is not an integer (number w/o decimals)! Try again.");
System.out.print("Enter your first number: ");
num1 = Integer.parseInt(sc.nextLine());
}
When I input e.g. letters, it says:
Your input is not an integer (number w/o decimals)! Try again.
Enter your first number:
But when I type letters the second time, the program crashes:
Exception in thread "main" java.lang.NumberFormatException: For input string: "asdf"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at GCDLCMgetter.main(GCDLCMgetter.java:56)
It is probably a very simple mistake I made but I can't figure it out...
Thank you
Your second parseInt method call is not in try catch block. You need to use a loop for this kind of logic.
It's because your second prompt is inside the catch block. Instead of prompting again inside the catch block, you want to wrap the entire code section in a loop so it comes back around to the try block for the prompt again.
Something like:
boolean repeat = true;
while(repeat){
try{
//Prompt for input
repeat = false;
}catch(Exception e) {
//Display error message
}
}
When the first time you give letters it goes into catch block. Displays the error message. And then executes the line num1 = Integer.parseInt(sc.nextLine());
Again you have entered the letters, but this time there is no try-catch block to handle this. So it throws error.
In your code, it gets executed twice:
Reads a Line at try{...}
There is an Exception
The Exception is handled by the catch(Exception e){...}
The num1 = Integer.parseInt(sc.nextLine()); inside the catch(Exception e){...} cannot be handled. It's not placed inside try{}.
Execution finished because the last exception cannot be handled by any catch.
It seems you're using Scanner, I would recommend you using a loop whis way:
while (sc.hasNextLine()){
try {
System.out.print("Enter your first number: ");
num1 = Integer.parseInt(sc.nextLine());
}
catch(Exception e) {
System.out.println("Your input is not an integer (number w/o decimals)! Try again.");
}
}
If you're managing integers, it would be interesting using Scanner.nextInt()
while (sc.hasNextInt()){
try {
System.out.print("Enter your first number: ");
num1 = sc.nextInt());
}
catch(Exception e) {
System.out.println("Your input is not an integer (number w/o decimals)! Try again.");
}
}

How to use Try/Catch to prevent String input where an Int is needed

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package freetime;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* #author Andy
*/
public class NewClass {
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
int userInput=0,notInt=0,newInput=0;
System.out.println("Enter a integer number");
while (notInt == 0){
try {
newInput=scan.nextInt();
userInput=newInput;
if (userInput != newInput){
notInt=0;
}
if (userInput == newInput){
notInt=1;
}
}
catch(InputMismatchException e){
System.out.println("That is not an integer, please try again." );
}
}
System.out.println(userInput);
}
}
I am trying to prevent a string input and allow the user to re input as an int. i cannot seem to get it to work properly, i also did this without the while loop. I think my understanding of how the Try Mismatch functions work is causing some issues.
Thanks for the help.
Scanner scan=new Scanner(System.in);
int userInput=0,notInt=0,newInput=0;
boolean runL=true;
while (runL){
System.out.println("Enter a integer number");
if (scan.hasNextInt()){
userInput=scan.nextInt();
runL=false;
}
else {
System.out.println("That is not an integer, please try again.");
}
}
System.out.println(userInput);
So i changed the code to this but I am still running into the loop continuing to go after something other than an int is entered. What am i doing wrong?
int userInput=0,notInt=0,newInput=0;
boolean runL=true;
while (runL){
Scanner scan=new Scanner(System.in);
System.out.println("Enter a integer number");
if (scan.hasNextInt()){
userInput=scan.nextInt();
runL=false;
}
else {
System.out.println("That is not an integer, please try again.");
}
}
System.out.println(userInput);
I've found the problem, I needed to create the scanner object inside of the While loop. Thanks for the help!
I think my understanding of how the Try Mismatch functions work is causing some issues.
You are probably right there ...
When I remove some of the "strange" code from your try / catch statement it looks like this:
try {
newInput = scan.nextInt();
// do stuff
} catch (InputMismatchException e){
// do other stuff
}
Here's what that actually means:
Call scan.nextInt()
If the call succeeds (i.e. it doesn't throw an exception), then:
assign the result to newInput
"do stuff"
If the call failed, AND it threw a InputMismatchException, then:
"do other stuff"
So, based on that, you don't need to do anything in "do stuff" to test if you just got a valid input. You know that is the case.
And likewise, any stuff that needs to be do in the case where you didn't get a valid input should be in "do other stuff".
Having said that, Jon Skeet's suggestion to look at the hashNextInt method is spot on. If you use that the right way, you won't get an exception at all. The code will be much simpler.
And Jon is also correct that you should be using the boolean type for your true / false logic. (That is what the type is intended for!)
Use Integer.parseInt(input) in try block.
If input is not an int, then it will throw an exception and catch the exception in catch{} block.
Your while loop should look like this:
while (notInt == 0){
try {
newInput=Integer.parseInt(scan.nextLine());
userInput=newInput;
notInt=1;
}
catch(NumberFormatException e){
System.out.println("That is not an integer, please try again." );
}
}
Your code doesn't work because when a InputMismatchException is thrown, the token that causes the exception isn't actually read. So the loop is reading the same thing every iteration.
nextLine however, almost always reads the whole line as a string (except when there's no line). You put the string that is read into Integer.parseInt to turn it into an int. If it can't be turned into an int, a NumberFormatException will be thrown.
However, you should not use exceptions as a way of validating inputs because it's slow. You can try this approach with regex:
while (notInt == 0){
String line = scan.nextLine();
Pattern p = Pattern.compile("-?\\d+");
if (p.matcher(line).matches()) {
userInput = Integer.parseInt(line);
notInt = 1;
} else {
System.out.println("Please try again");
}
}

Java Infinite Loop appears when using try/catch block

I am stuck in an infinite loop with this piece of code. The program generates endless lines of "Enter number 1> Please enter a number." when an invalid input like "a" is entered instead of an integer.
I don't know what's wrong with my boolean variable, everything seems fine to me. Please check it out, thank you so much.
import java.util.*;
public class Adder{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
boolean correctInput=false;
while(!correctInput){
try{
System.out.print("Enter number 1> ");
int num1=sc.nextInt();
System.out.print("Enter number 2> ");
int num2=sc.nextInt();
System.out.println("Sum = "+(num1+num2));
correctInput=true;
}
catch(InputMismatchException e){
System.out.println("Please enter a number.");
correctInput=false;
}
}
}
}
Add sc.nextLine(); statement in your catch block.
If you need to retry then add sc.nextLine(); otherwise you can break the loop as well by putting break; statement in catch block.

try-catch statement not returning to try block when catching exception

I have a method that a wrote. This method just scans for a user entered integer input. If the user enters a character value it will throw an input mismatch exception, which is handled in my Try-Catch statement. The problem is that, if the user inputs anything that is not a number, and then an exception is thrown, I need the method to loop back around to ask the user for input again. To my understanding, a Try catch statement automatically loops back to the Try block if an error is caught. Is this not correct? Please advise.
Here is my method (it's pretty simple):
public static int getMask() {
//Prompt user to enter integer mask
Scanner keyboard = new Scanner(System.in);
int output = 0;
try{
System.out.print("Enter the encryption mask: ");
output = keyboard.nextInt();
}
catch(Exception e){
System.out.println("Please enter a number, mask must be numeric");
}
return output;
}//end of getMask method
Here is how the method is implemented into my program:
//get integer mask from user input
int mask = getMask();
System.out.println("TEMP mask Value is: " + mask);
/***********************************/
Here is my updated code. It creates an infinate loop that I can't escape. I don't understand why I am struggling with this so much. Please help.
public static int getMask() {
//Prompt user to enter integer mask
Scanner keyboard = new Scanner(System.in);
int output = 0;
boolean validInput = true;
do{
try {
System.out.print("Enter the encryption mask: ");
output = keyboard.nextInt();
validInput = true;
}
catch(InputMismatchException e){
System.out.println("Please enter a number, mask must be numeric");
validInput = false;
}
}while(!(validInput));
return output;
/********************/FINAL_ANSWER
I was able to get it finally. I think I just need to study boolean logic more. Sometimes it makes my head spin. Implementing the loop with an integer test worked fine. My own user error I suppose. Here is my final code working correctly with better exception handling. Let me know in the comments if you have any criticisms.
//get integer mask from user input
int repeat = 1;
int mask = 0;
do{
try{
mask = getMask();
repeat = 1;
}
catch(InputMismatchException e){
repeat = 0;
}
}while(repeat==0);
To my understanding, a Try catch statement automatically loops back to the Try block if an error is caught. Is this not correct?
No this is not correct, and I'm curious as to how you arrived at that understanding.
You have a few options. For example (this will not work as-is but let's talk about error handling first, then read below):
// Code for illustrative purposes but see comments on nextInt() below; this
// is not a working example as-is.
int output = 0;
while (true) {
try{
System.out.print("Enter the encryption mask: ");
output = keyboard.nextInt();
break;
}
catch(Exception e){
System.out.println("Please enter a number, mask must be numeric");
}
}
Among others; your choice of option usually depends on your preferred tastes (e.g. fge's answer is the same idea but slightly different), but in most cases is a direct reflection of what you are trying to do: "Keep asking until the user enters a valid number."
Note also, like fge mentioned, you should generally catch the tightest exception possible that you are prepared to handle. nextInt() throws a few different exceptions but your interest is specifically in an InputMismatchException. You are not prepared to handle, e.g., an IllegalStateException -- not to mention that it will make debugging/testing difficult if unexpected exceptions are thrown but your program pretends they are simply related to invalid input (and thus never notifies you that a different problem occurred).
Now, that said, Scanner.nextInt() has another issue here, where the token is left on the stream if it cannot be parsed as an integer. This will leave you stuck in a loop if you don't take that token off the stream. To that end you actually want to use either next() or nextLine(), so that the token is always consumed no matter what; then you can parse with Integer.parseInt(), e.g.:
int output = 0;
while (true) {
try{
System.out.print("Enter the encryption mask: ");
String response = keyboard.next(); // or nextLine(), depending on requirements
output = Integer.parseInt(response);
break;
}
catch(NumberFormatException e){ // <- note specific exception type
System.out.println("Please enter a number, mask must be numeric");
}
}
Note that this still directly reflects what you want to do: "Keep asking until the user enters a valid number, but consume the input no matter what they enter."
To my understanding, a Try catch statement automatically loops back to the Try block if an error is caught. Is this not correct?
It is indeed not correct. A try block will be executed only once.
You can use this to "work around" it (although JasonC's answer is more solid -- go with that):
boolean validInput = false;
while (!validInput) {
try {
System.out.print("Enter the encryption mask: ");
output = keyboard.nextInt();
validInput = true;
}
catch(Exception e) {
keyboard.nextLine(); // swallow token!
System.out.println("Please enter a number, mask must be numeric");
}
}
return output;
Further note: you should NOT be catching Exception but a more specific exception class.
As stated in the comments, try-catch -blocks don't loop. Use a for or while if you want looping.

A Confusing Issue with nextLong() method in java.util.Scanner class

I am trying to run a simple code which will take an account number as the long type from the user through nextLong() method.Now if the user has given the account_number(long accNo) as string_type or character_type instead of long_type value then the InputMismatchException is thrown.That is also fine,because I am aware of the fact that nextLong() method can throw InputMismatchException along with NoSuchElementException and IllegalStateException.But after that when I am expecting that after getting InputMismatchException the loop will revisit and ask me to give the account_number(long accNo) as long value again! then the problem occurs.It is not asking me to give any value,instead an infinite loop is running along with the exception again & again.!!
package genericsandcollection;
import java.util.*;
public class ScannerTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
boolean b=true;
while(b){
try{
System.out.println("Enter Your Account Number..: ");
long accNo=sc.nextLong();
System.out.println(accNo);
b=false;
}catch(InputMismatchException | IllegalStateException e){
e.printStackTrace();
System.out.println(e);
System.out.println("Wrong syntax");
}
}
}
}
Why is it happening ? Is not nextLong() smart enough to handle a situation inside a loop ! If I use Long.parseLong(sc.next()) instead of sc.nextLong(),then everything is alright as parseLong() is throwing NumberFormatException i.e. until I will give the account number as long_type it keeps asking the user to give the account_number as long_type value.Really Strange !!!! If anybody has any concern,please help.Thank you.
Do not close the scanner in the catch block or you won't be able to use it again.
You shouldn't close the Scanner because as well as meaning you cannot use the Scanner anymore it will also close System.in. Your infinite loop is because using any other method than nextLine will leave a line break (from pressing 'enter' to submit) at the end of the input buffer. This will cause nextLong to always throw an exception.
Calling nextLine will advance the Scanner. The following is a short example that shows this (adapted from a very similar answer I wrote).
do {
try {
accNo = sc.nextLong();
break;
} catch (InputMismatchException e) {
} finally {
sc.nextLine(); // always advances (even after the break)
}
System.out.print("Input must be a number: ");
} while (true);

Categories

Resources