Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

ReadLine Returns What on No Input?

807600Nov 23 2007 — edited Nov 25 2007
I'm trying to grab user input (numbers) and I want to be able to process them. I'm looking for a way to insert a default value into the storage variable if the user just hits 'Enter' (e.g. enters no input), but the code either pitches a fit or doesn't make it obvious what return value I'm testing for in such a case.

So I did the search, nothing obvious in the forums:

http://search.sun.com/search/onesearch/index.jsp?qt=readline&rfsubcat=siteforumid%3Ajava54&col=developer-forums

The JavaDoc page doesn't show anything about the return value I'm interested in:

http://java.sun.com/j2se/1.3/docs/api/java/io/BufferedReader.html

Many tutorials site this particular process I'm going through, but don't cover the case I need:

http://www.scit.wlv.ac.uk/~jphb/java/basicio.html
http://pages.cs.wisc.edu/~cs302/io/JavaIO.html

Code:
import java.io.*;

public class testing_IO {
    public static void main(String[] args) {
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));    
        System.out.println("Enter the Following information:");

        int info;

        try {
            info = Integer.parseInt( read.readLine() );
        } 
        catch (IOException ioe) {        
            System.out.println("Using default value [0] for Spell Damage");
            System.out.println("IO error trying to read 'Spell Damage'");
            System.exit(1);
        }        
        catch(NumberFormatException nfex)
        {
            System.out.println("\"" + nfex.getMessage() + "\" is not numeric");
            System.exit(1);
        }
    }        
}
From a little experimentation I see that when I enter no input at my prompt there, I get a non-numeric result. Now I need to know how to field the exception, e.g. I want to be able to set info=0 if I detect the case where I get no input.

--Pontifex
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 23 2007
Added on Nov 23 2007
18 comments
580 views