In my recent Java projects I’ve been finding myself hitting the user up for input, now during the development phase of these projects everything is command prompt, so here is a useful little userdata utility that I’ve been using, and as I run into other types of input I will be adding to it.
UserData.java
import java.util.Scanner;
/**
* Gives us various methods for getting info from the user.
*
* @author Michael Avila
* @version 1.0
*/
public class UserData
{
private Scanner reader;
/**
* Constructor
*/
public UserData()
{
reader = new Scanner( System.in );
}
/**
* Asks the user a question, returns their response as a string
*/
public String prompt ( String statement )
{
System.out.println( statement );
return reader.nextLine();
}
/**
* Asks the user a yes or no question, returns either Y or N
*/
public boolean askYN( String question )
{
System.out.println(question + "[Y/N]");
while (true)
{
String response = reader.nextLine();
if (response.equals("Y"))
{
return true;
} else if (response.equals("N"))
{
return false;
}
System.out.println(question + "[Y/N]");
System.out.println("Please enter either [Y]es or [N]o");
}
}
}
And here is a little TestDrive application for seeing how it works…
UserDataTest.java,
public class UserDataTest
{
/**
* Entry-point
*/
public static void main( String[] args )
{
// new instance of UserData
UserData uData = new UserData();
// asks a yes or no question, returning the answer as a boolean
boolean likes = uData.askYN( "Do you like this class?" );
System.out.println( likes );
if (likes)
{
// prompts the user with either a question or statement, then returns their feedback.
String response = uData.prompt( "What is one thing you like about this class?" );
System.out.println( response );
}
}
}
This code isn’t the greatest thing in the world, but it has helped quicken development time for me, and I’m sure it will for you.
If you have any suggestions as to methods that could be added, go ahead and comment them, and I’ll try putting it together when I can. Take Care.