Results 1 to 10 of 10
  1. #1
    Java_Lover is offline Member
    Join Date
    Apr 2010
    Location
    Virginia, USA
    Posts
    12
    Rep Power
    0

    Default Console Input Issue

    All,

    I am just learning Java and am creating a menu based program with some very simple options. The idea is to have a main menu where the user selects an option. For example, if the user chooses 1, they will then be able to convert liters to gallons. Pretty simple but gotta start somewhere.

    I am also playing with linking two class files because I feel it will provide cleaner code.

    So, here is the main class file:
    Java Code:
    /*
    	Created: 4/20/2010
    	Author:Bryan
    	Purpose: To get input from the user.
    */
    public class KeyBoardInput {
    
    
    	public static void main(String args[])
    	throws java.io.IOException
    	{
    		mainMenu();
    	} 
    
    
    	public static void mainMenu()
    	throws java.io.IOException
    	{
    		/*
    			Main menu:
    			1.  Convert gallons to liters.
    			2.  Find the square root of a number.
    			3.  Distance lightning is away.
    		*/
    			//Define fields
    			char selection;
    
    			//Show the main menu
    			System.out.println("Main Menu");
    			System.out.println("1.  Convert gallons to liters");
    			System.out.println("2.  Find the square root of a number.");
    			System.out.println("3.  Determine how far lightning is away.");
    			System.out.println("Press any key:");
    		
    
    			selection = (char) System.in.read();
    			
    			switch (selection)
    			{
    				case '1': 
    					new GalToLiters();
    					break;
    				case '2': 
    					SquareRoot();
    					break;
    				case '3': 
    					Distance();
    					break;
    				default: 
    					InvalidSelection();
    			}
    
    	}
    
    	private static void SquareRoot()
    	{
    		System.out.println("SquareRoot");
    	}
    
    	private static void Distance()
    	{
    		System.out.println("Distance");
    	}
    
    	private static void InvalidSelection()
    	{
    		System.out.println("Invalid Selection");
    	}
    
    }
    The second class file:
    Java Code:
    public class GalToLiters 
    {
    
    /*	Objective: 
    **	To convert gallons into liters.  The user must supply us with the number of liters to convert.
    **	3.78541178 liters in one gallon
    **	Print to console the number of liters.
    **
    */
    	public GalToLiters()
    	throws java.io.IOException
    	{
    		//Declare fields
    		double gallons, liters;
    	
    		//Get the number of gallons user wants to conver.
    		System.out.println();
    		System.out.println(); //Add some blank lines so the console screen is not cluttered.
    		System.out.println("How many gallons do you want to convert?");
    		gallons = (char) System.in.read(); // need an edit check to make sure it's a number.
    	
    		//Make conversion
    		liters = gallons * 3.78541178;
    
    		//Print result to screen
    		System.out.println("Liters = " + liters);
    
    		//Return to main menu
    		
    	}
    
    
    
    }
    I know there are probably some issues with my coding but I am focusing on the gallons to liters conversion right now. From the main menu, pressing 1 does successfully get to the second class file.

    Here's what happens when the second class file is executed:
    1. The two blank lines are printed to the console.
    2. How many gallons do you wish to convert? is displayed
    3. Liters = 37.8541178 is displayed.

    Obviously the user did not get a chance to input how many gallons there were and the program calculated 10 gallons for some reason.

    The question is, how do I allow the user to enter a numeric value?

    Also, if you see any other general issues with my code or suggested practices, please let me know. I will be moving the SquareRoot, Distance and InvalidSelection to separate class files. I'm new to Java but do have a passion for it.

    Thanks for your time,
    Bryan

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  3. #3
    iluxa is offline Senior Member
    Join Date
    Mar 2010
    Posts
    266
    Rep Power
    5

    Default

    try this:

    Java Code:
    BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
    String userInput = br.readLine();
    // just in case, trim the whitespace, so that 
    // "   user   input   " becomes "user input"
    userInput = userInput.trim ();
    int gallons = Integer.parseInt (userInput);
    //...

  4. #4
    Java_Lover is offline Member
    Join Date
    Apr 2010
    Location
    Virginia, USA
    Posts
    12
    Rep Power
    0

    Default

    I added iluxa's code and but received the following compile message:
    Java Code:
    GalToLiters.java:28: cannot find symbol
    symbol  : class BufferedReader
    location: class GalToLiters
    		BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
    		^
    GalToLiters.java:28: cannot find symbol
    symbol  : class BufferedReader
    location: class GalToLiters
    		BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
    		                        ^
    GalToLiters.java:28: cannot find symbol
    symbol  : class InputStreamReader
    location: class GalToLiters
    		BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
    		                                            ^
    3 errors
    Here is what the GalToLiters.java file looks like with the new code added:

    Java Code:
    public class GalToLiters 
    {
    
    /*	Objective: 
    **	To convert gallons into liters.  The user must supply us with the number of liters to convert.
    **	3.78541178 liters in one gallon
    **	Print to console the number of liters.
    **
    */
    	public GalToLiters()
    	throws java.io.IOException
    	{
    		//Declare fields
    		double liters;
    		
    		//Get the number of gallons user wants to conver.
    		System.out.println();
    		System.out.println(); //Add some blank lines so the console screen is not cluttered.
    		System.out.println("How many gallons do you want to convert?");
    		//gallons = (byte) System.in.read(); // need an edit check to make sure it's a number.
    		BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
    		String userInput = br.readLine();
    		// just in case, trim the whitespace, so that 
    		// "   user   input   " becomes "user input"
    		userInput = userInput.trim ();
    		int gallons = Integer.parseInt (userInput);
    	
    		System.out.println(gallons);
    		
    
    		//Make conversion
    		liters = gallons * 3.78541178;
    
    		//Print result to screen
    		System.out.println("Liters = " + liters);
    
    		//Return to main menu	
    	}
    }
    Keep in mind I am a newbie so I'd appreciate the WHY in addition to the WHAT. :)

    Thanks for your time.

  5. #5
    iluxa is offline Senior Member
    Join Date
    Mar 2010
    Posts
    266
    Rep Power
    5

    Default

    you didn't import the classes.

    up top, do

    import java.io.*;

  6. #6
    Java_Lover is offline Member
    Join Date
    Apr 2010
    Location
    Virginia, USA
    Posts
    12
    Rep Power
    0

    Default

    Iluxa,

    I added the import line and was able to compile (?) the .java file.

    When I run it, I select option 1 from the main menu. This loads GaltoLiters but I get:
    Java Code:
    How many gallons do you want to convert?
    Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    	at java.lang.Integer.parseInt(Integer.java:493)
    	at java.lang.Integer.parseInt(Integer.java:514)
    	at GalToLiters.<init>(GalToLiters.java:28)
    	at KeyBoardInput.mainMenu(KeyBoardInput.java:41)
    	at KeyBoardInput.main(KeyBoardInput.java:12)
    This is my interpretation of the error.
    It appears there is an issue with data types. I changed the line
    Java Code:
    int gallons = Integer.parseInt (userInput);
    to read
    Java Code:
    double gallons = Integer.parseInt (userInput);
    I did this because it was being multiplied by a decimal -> 3.78...

    I got the same error but that is probably due to the fact that you can't set a double to an integer. In reading this error, I see GalToLiters.java:28. Does this mean on line 28 of my GalToLiters.java file, a potential error exists?

    Line 28 is the line above where gallons is defined as an integer. I do realize that these errors may not point to the exact cause but something after it. Any help would be appreciated.

    Thanks.

  7. #7
    iluxa is offline Senior Member
    Join Date
    Mar 2010
    Posts
    266
    Rep Power
    5

    Default

    1. double gallons=Double.parseDouble(userInput).
    2. if user input is an empty string "", how do you expect to make a number out of it? do this:

    Java Code:
    try {
      double gallons=Double.parseDouble(userInput);
      // if you're here, it's a good number so you can use it
    } catch (Throwable t) {
      System.out.println ("bad number of gallons entered: " + userInput);
    }

  8. #8
    Java_Lover is offline Member
    Join Date
    Apr 2010
    Location
    Virginia, USA
    Posts
    12
    Rep Power
    0

    Default

    Iluxa,

    I implemented your solution, received two compile errors and altered the class file to this:
    Java Code:
    import java.io.*;
    
    public class GalToLiters 
    {
    
    /*	Objective: 
    **	To convert gallons into liters.  The user must supply us with the number of liters to convert.
    **	3.78541178 liters in one gallon
    **	Print to console the number of liters.
    **
    */
    
    
    	public GalToLiters()
    	throws java.io.IOException
    	{
    		//Declare fields
    		double liters,gallons;
    		
    		//Get the number of gallons user wants to conver.
    		System.out.println();
    		System.out.println(); //Add some blank lines so the console screen is not cluttered.
    		System.out.println("How many gallons do you want to convert?");
    		
    		BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
    		String userInput = br.readLine();
    
    		/*	just in case, trim the whitespace, so that 
    			"   user   input   " becomes "user input"	
    		*/ 	
    		userInput = userInput.trim ();
    
    		try {
      			gallons=Double.parseDouble(userInput);
    			// if you're here, it's a good number so you can use it
    		} catch (Throwable t) {
    			  System.out.println ("bad number of gallons entered: " + userInput);
    			gallons = 0;
    		}
    		//Make conversion
    		liters = gallons * 3.78541178;
    
    		//Print result to screen
    		System.out.println("Liters = " + liters);
    
    		//Return to main menu	
    	}
    }
    Changes I made to your suggestion:
    1. I declared the gallons variable outside of the try block.
    2. I set gallons = 0 in the catch section.

    When I run this, the catch code executes and the value of NULL is passed. This is evident due to the output being:
    Java Code:
    bad number of gallons entered:
    So I am wondering if the main class file, posted at the very beginning of this thread, is written correctly. I know the problem is a blank space is being passed but not sure what is causing it.

    Thanks!

  9. #9
    iluxa is offline Senior Member
    Join Date
    Mar 2010
    Posts
    266
    Rep Power
    5

    Default

    Actually, you're mistaken. "bad number of gallons entered:" means inputString was "". Had it been null, you'd see "bad number of gallons entered: null".

    so, your input text is empty for some reason... perhaps it eats two lines instead of one... try this:

    Java Code:
    String userInput = br.readLine();
    
    while (userInput != null && userInput.trim().length == 0) {
      userInput = br.readLine();
    }
    and see if that helps

  10. #10
    Java_Lover is offline Member
    Join Date
    Apr 2010
    Location
    Virginia, USA
    Posts
    12
    Rep Power
    0

    Default

    Iluxa,

    I appreciate your time but received an error when compiling.

    Java Code:
    GalToLiters.java:34: cannot find symbol
    symbol  : variable length
    location: class java.lang.String
    		while (userInput != null && userInput.trim().length == 0) {
    		                                            ^
    1 error
    Here's the relevant info from the class file after I implemented your suggestion. I probably kept a line I should not have so feel free to let me my mistake.

    BTW, thanks for the Null pointer.
    Java Code:
    import java.io.*;
    
    public class GalToLiters 
    {
    	public GalToLiters()
    	throws java.io.IOException
    	{
    		//Declare fields
    		double liters,gallons;
    		
    		//Get the number of gallons user wants to conver.
    		//System.out.println();
    		//System.out.println(); //Add some blank lines so the console screen is not cluttered.
    		System.out.println("How many gallons do you want to convert?");
    		
    		BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
    		
    
    		/*	just in case, trim the whitespace, so that 
    			"   user   input   " becomes "user input"	
    		*/ 
    
    		String userInput = br.readLine();
    
    		while (userInput != null && userInput.trim().length == 0) {
    		  userInput = br.readLine();
    		}	
    		
    		try {
      			gallons=Double.parseDouble(userInput);
    			// if you're here, it's a good number so you can use it
    		} catch (Throwable t) {
    			  System.out.println ("bad number of gallons entered: " + userInput);
    			gallons = 0;
    		}
    		//Make conversion
    		liters = gallons * 3.78541178;
    
    		//Print result to screen
    		System.out.println("Liters = " + liters);
    
    		//Return to main menu	
    	}
    }

Similar Threads

  1. How to get input from Console
    By karma in forum New To Java
    Replies: 8
    Last Post: 08-13-2010, 09:32 PM
  2. how to take input from console in jsp
    By veena in forum New To Java
    Replies: 1
    Last Post: 05-06-2008, 04:39 AM
  3. ways to get input from console
    By soni in forum New To Java
    Replies: 2
    Last Post: 05-05-2008, 09:44 PM
  4. How to read input from the console
    By Java Tip in forum java.io
    Replies: 0
    Last Post: 04-06-2008, 07:41 PM
  5. Taking input from console
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-05-2007, 04:47 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •