36232

try catch for Scanner

Question:

I am using Scanner to get user input. If the user inputs a name, I add that to the ArrayList. If the user does not enter a name then I want to throw an exception, but I want to continue the loop that gets the answer.

for(int i = 0; i < totalLanes; i++){ runArr.add(this.addRacer()); } public static String addRacer() throws NullPointerException{ System.out.print("Enter a name for a racer: ");//Method uses try catch to catch a NullPointerException. Scanner sc = new Scanner(System.in); String rName = null; try { if(!sc.nextLine().isEmpty()){ rName = sc.nextLine(); }else{ throw new NullPointerException("name cannot be blank"); } } catch (NullPointerException e) { System.out.println(e.toString()); System.out.print("Enter a name for a racer: "); addRacer(); } return rName; } <ul><li>Why would this recurse infinitely?</li> <li>What is the best way to retrieve the input from the user but make sure they are inputting valid data?</li> </ul>

Thanks in advance.

Answer1:

The problem is that you read input twice. I mean you have two calls of sc.nextLine() method in your code. Try this instead:

String rName = sc.nextLine(); try { if(rName.isEmpty()){ throw new NullPointerException("Name cannot be blank."); } }

Answer2:

You shouldn't throw an exception for that. Just use a while loop:

String rName = sc.nextLine(); while (rName.isEmpty()) { System.out.println("Name can't be blank. Try again."); rName = sc.nextLine(); } return rName;

After that loop you are guaranteed to have a non-empty name in your variable, and you can use that name to add a new racer. You do not need recursion.

Answer3:

You can use a do{}while() in your case, this can be better way :

Scanner sc = new Scanner(System.in); String rName; do { System.out.print("Enter a name for a racer: "); rName = sc.nextLine(); try { if (rName.isEmpty()) { //throw and exception throw new NullPointerException("name cannot be blank"); } } catch (NullPointerException e) { //print the exception System.out.println(e.getMessage()); } } while (rName.isEmpty()); return rName;

So you can't break your loop until the value in not empty.

Answer4:

<blockquote>

If the user does not enter a name then I want to throw an exception, but I want to continue the loop that gets the answer.

</blockquote>

For that you need to use a while loop

<blockquote>

What is the best way to retrieve the input from the user but make sure they are inputting valid data?

</blockquote>

Use a while loop which should execute until user inputs the valid input. You <strong>don't need to use recursion</strong> for what you are trying to achieve.

public static String addRacer() throws NullPointerException{ System.out.print("Enter a name for a racer: "); Scanner sc = new Scanner(System.in); String rName = null; try { String rName = sc.nextLine(); if(rName.isEmpty()){ throw new NullPointerException("name cannot be blank"); } while (rName.isEmpty()) { System.out.println("Name can't be blank. Try again."); rName = sc.nextLine(); } } catch (NullPointerException e) { System.out.println(e.toString()); } return rName; }

Answer5:

Don't call addRacer() function in catch. And also remove the line i have marked.Use if else condition for recursion.

catch (NullPointerException e) { System.out.println(e.toString()); System.out.print("Enter a name for a racer: ");//remove this addRacer();//remove this }

Recommend

  • should i be creating an index for this?
  • Getting TypeError while fetching value from table using Python and Django
  • Java parsing text file and preserving line breaks?
  • Using mgsub function with word boundaries for replacement values
  • Is there a better way for reduce operation on RDD[Array[Double]]
  • Initialization order of values in objects: How to setup cyclic/recursive objects properly?
  • Append Filename to RDD
  • Hashtable getting null for existing key
  • sparklyr change all column names spark dataframe
  • AngularJS two http get in one controller make problems
  • Spark DataFrame equivalent to Pandas Dataframe `.iloc()` method?
  • Spark dataframes: Extract a column based on the value of another column
  • spark importing data from oracle - java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
  • Android FileProvider delete file
  • Count the number of non-null values in a Spark DataFrame
  • How to create a generic Task.ContinueWith extension method
  • Exception in the iconization of JInternalFrame with DefaultDesktopManager
  • Why are “sc.addFile” and “spark-submit --files” not distributing a local file to all workers?
  • pickle.PicklingError: args[0] from __newobj__ args has the wrong class with hadoop python
  • Authentication failed with Azure Active Directory in Windows Phone
  • python script hangs on input method when running spark
  • Creating Java object from class name with constructor, which contains parameters [duplicate]
  • How to use RequestBodyAdvice
  • Array.prototype.includes - not transformed with babel
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • align graphs with different xlab
  • Return words with double consecutive letters
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Proper folder structure for lots of source files
  • Proper way to use connect-multiparty with express.js?
  • JTable with a ScrollPane misbehaving
  • How does Linux kernel interrupt the application?
  • apache spark aggregate function using min value
  • unknown Exception android
  • Checking variable from a different class in C#
  • Sorting a 2D array using the second column C++
  • Reading document lines to the user (python)
  • failed to connect to specific WiFi in android programmatically
  • Python/Django TangoWithDjango Models and Databases
  • How can I use threading to 'tick' a timer to be accessed by other threads?