Results 1 to 4 of 4
  1. #1
    net2chris is offline Member
    Join Date
    Oct 2011
    Posts
    3
    Rep Power
    0

    Default How to ERROR if user presses Enter?

    I'm new to Java and maybe 15 years since taking a programming class but wanted to learn so I enrolled at a local community college.

    I need to do the following:
    Ask user if they want to continue and
    1. if yes - do something
    2. if no - do something
    3. if neither yes or no - do something
    4. if user presses enter without pressing a character beforehand - do something.

    I know how to code 1-3, it's 4 I can't figure out.

    I've tried using the scanner class and if(!hasNext()), assuming that if the user presses enter, that would mean, there is no token but this doesn't seem to work because if I replace it with if(hasNext()) or if(hasNextLine), I can easily get to desired statements. I've looked all over the net and searched these forums but it's hard to search for the exact condition I'm looking for. I've also e-mailed the professor but no reply.

    Thanks in advance for any help!

    Chris

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

    Default Re: How to ERROR if user presses Enter?

    There is a token, it's an end of line token. I'd get the input via Scanner's nextLine(), I'd trim the String returned via the trim() method and then check to see if the String is empty via the isEmpty() String method. If so, you're at situation #4.

  3. #3
    net2chris is offline Member
    Join Date
    Oct 2011
    Posts
    3
    Rep Power
    0

    Default Re: How to ERROR if user presses Enter?

    Thanks. I just also got a reply from my professor. Amazing how condescending people in academia can be. "If you pay attention to lecture..." I haven't been accused of not paying attention in years.

    Anyway, thanks again. He suggested I follow this example which I'm currently reading through but it seems to be helpful. I did come across what you mentioned on the web. One thing I do remember about my coding experience in the 90s at school is that there are often way easier ways to do things outside the scope of the bloody text book.
    Here's the example my professor referenced and again thanks!
    //Example of using user-defined validation classes, exception handling, and other supporting classes

    import java.util.*;
    import java.text.*;

    public class FutureValueValidationApp3
    {
    public static void main(String[] args)
    {
    System.out.println("Welcome to the Future Value Calculator\n");

    Scanner sc = new Scanner(System.in);
    String choice = "y";

    while (choice.equalsIgnoreCase("y"))
    {
    // get the input from the user
    System.out.println("DATA ENTRY");
    double monthlyInvestment = Validator.validDoubleWithinRange(sc,
    "Enter monthly investment: ", 0, 1000);
    double interestRate = Validator.validDoubleWithinRange(sc,
    "Enter yearly interest rate: ", 0, 30);
    int years = Validator.validIntWithinRange(sc,
    "Enter number of years: ", 0, 100);

    // calculate the future value
    double monthlyInterestRate = interestRate/12/100;
    int months = years * 12;
    double futureValue = Investment.calculateFutureValue(
    monthlyInvestment, monthlyInterestRate, months);

    // get the currency and percent formatters
    NumberFormat currency = NumberFormat.getCurrencyInstance();
    NumberFormat percent = NumberFormat.getPercentInstance();
    percent.setMinimumFractionDigits(1);

    // format the result as a single string
    String results =
    "Monthly investment:\t"
    + currency.format(monthlyInvestment) + "\n"
    + "Yearly interest rate:\t"
    + percent.format(interestRate/100) + "\n"
    + "Number of years:\t"
    + years + "\n"
    + "Future value:\t\t"
    + currency.format(futureValue) + "\n";

    // print the results
    System.out.println();
    System.out.println("FORMATTED RESULTS");
    System.out.println(results);

    // see if the user wants to continue
    choice = Validator.validYesNo(sc, "Continue? (y/n): ");
    System.out.println();
    }
    }
    }

    //User defined supporting class to validate entries
    class Validator {
    //validate yes or no with empty entry
    public static String validYesNo( Scanner sc, String prompt)
    {
    String entryType = null;
    boolean isValid = false;
    while( !isValid) {
    System.out.print( prompt );
    entryType = sc.nextLine();
    if (entryType.equals("")) { //just pressed enter key
    System.out.println("Must enter your choice. Please try again...");
    }
    else if( !(entryType.equalsIgnoreCase("y")||
    entryType.equalsIgnoreCase("n")) ) {
    System.out.println("Only 'y' or 'n' is allowed.");
    isValid = false;
    }
    else
    isValid = true;
    }
    return( entryType);
    }
    //validate double
    public static double validDouble(Scanner sc, String prompt)
    {
    double d = 0.0;
    boolean isValid = false;
    while (isValid == false)
    {
    try {

    System.out.print(prompt);
    if (sc.hasNextDouble())
    {
    d = sc.nextDouble();
    isValid = true;
    }
    else
    { // throw an API exception class
    throw new NumberFormatException("Error! Invalid double value. Try again.");

    }

    }// end of try block

    catch (NumberFormatException e)
    {
    System.out.println(e);
    }
    sc.nextLine(); // discard any other data entered on the line
    }
    return d;
    }

    //vlaidate double with range
    public static double validDoubleWithinRange(Scanner sc, String prompt,
    double min, double max)
    {
    double d = 0.0;
    boolean isValid = false;
    while (isValid == false)
    {
    try {

    d = validDouble(sc, prompt);
    if (d <= min) // throw user-defined exceptions
    throw new DoubleOutOfMinRangeException("Error! Number must be greater than " + min + ".");
    else if (d >= max)
    throw new DoubleOutOfMaxRangeException("Error! Number must be less than " + max + ".");
    else
    isValid = true;
    } // end of try block
    catch (DoubleOutOfMinRangeException e)
    {
    System.out.println(e);
    }
    catch (DoubleOutOfMaxRangeException e)
    {
    System.out.println(e);
    }

    }
    return d;
    }

    //validate int
    public static int validInt(Scanner sc, String prompt)
    {
    int i = 0;
    boolean isValid = false;
    while (isValid == false)
    {
    try {
    System.out.print(prompt);
    if (sc.hasNextInt())
    {
    i = sc.nextInt();
    isValid = true;
    }
    else
    { // throw an API exception
    throw new NumberFormatException("Error! Invalid integer value. Try again.");

    }
    } // end of try block
    catch (NumberFormatException e)
    {
    System.out.println(e);
    }

    sc.nextLine(); // discard any other data entered on the line
    }
    return i;
    }

    //validate int with range
    public static int validIntWithinRange(Scanner sc, String prompt,
    int min, int max)
    {
    int i = 0;
    boolean isValid = false;
    while (isValid == false)
    {
    try {

    i = validInt(sc, prompt);
    if (i <= min)
    System.out.println(
    "Error! Number must be greater than " + min + ".");
    else if (i <= min) // throw user-defined exceptions
    throw new IntOutOfMinRangeException("Error! Number must be greater than " + min + ".");
    else if (i >= max)
    throw new IntOutOfMaxRangeException("Error! Number must be less than " + max + ".");
    else
    isValid = true;

    } // end of try block
    catch (IntOutOfMinRangeException e)
    {
    System.out.println(e);
    }
    catch (IntOutOfMaxRangeException e)
    {
    System.out.println(e);
    }
    }
    return i;
    }
    }

    // user-defined supporting exception classes

    class DoubleOutOfMinRangeException extends Exception
    {
    public DoubleOutOfMinRangeException()
    { }

    public DoubleOutOfMinRangeException(String message)
    {
    super(message);
    }
    }

    class DoubleOutOfMaxRangeException extends Exception
    {
    public DoubleOutOfMaxRangeException()
    { }

    public DoubleOutOfMaxRangeException(String message)
    {
    super(message);
    }
    }

    class IntOutOfMinRangeException extends Exception
    {
    public IntOutOfMinRangeException()
    { }

    public IntOutOfMinRangeException(String message)
    {
    super(message);
    }
    }

    class IntOutOfMaxRangeException extends Exception
    {
    public IntOutOfMaxRangeException()
    { }

    public IntOutOfMaxRangeException(String message)
    {
    super(message);
    }
    }

    //supporting class to calculate future value
    class Investment {
    public static double calculateFutureValue(double monthlyInvestment,
    double monthlyInterestRate, int months)
    {
    double futureValue = 0;
    for (int i = 1; i <= months; i++)
    {
    futureValue =
    (futureValue + monthlyInvestment) *
    (1 + monthlyInterestRate);
    }
    return futureValue;
    }

    }

  4. #4
    net2chris is offline Member
    Join Date
    Oct 2011
    Posts
    3
    Rep Power
    0

    Default Re: How to ERROR if user presses Enter?

    Thanks. I just also got a reply from my professor. Amazing how condescending people in academia can be. "If you pay attention to lecture..." I haven't been accused of not paying attention in years.

    Anyway, thanks again. He suggested I follow this example which I'm currently reading through but it seems to be helpful. I did come across what you mentioned on the web. One thing I do remember about my coding experience in the 90s at school is that there are often way easier ways to do things outside the scope of the bloody text book.
    Here's the example my professor referenced and again thanks!
    //Example of using user-defined validation classes, exception handling, and other supporting classes

    import java.util.*;
    import java.text.*;

    public class FutureValueValidationApp3
    {
    public static void main(String[] args)
    {
    System.out.println("Welcome to the Future Value Calculator\n");

    Scanner sc = new Scanner(System.in);
    String choice = "y";

    while (choice.equalsIgnoreCase("y"))
    {
    // get the input from the user
    System.out.println("DATA ENTRY");
    double monthlyInvestment = Validator.validDoubleWithinRange(sc,
    "Enter monthly investment: ", 0, 1000);
    double interestRate = Validator.validDoubleWithinRange(sc,
    "Enter yearly interest rate: ", 0, 30);
    int years = Validator.validIntWithinRange(sc,
    "Enter number of years: ", 0, 100);

    // calculate the future value
    double monthlyInterestRate = interestRate/12/100;
    int months = years * 12;
    double futureValue = Investment.calculateFutureValue(
    monthlyInvestment, monthlyInterestRate, months);

    // get the currency and percent formatters
    NumberFormat currency = NumberFormat.getCurrencyInstance();
    NumberFormat percent = NumberFormat.getPercentInstance();
    percent.setMinimumFractionDigits(1);

    // format the result as a single string
    String results =
    "Monthly investment:\t"
    + currency.format(monthlyInvestment) + "\n"
    + "Yearly interest rate:\t"
    + percent.format(interestRate/100) + "\n"
    + "Number of years:\t"
    + years + "\n"
    + "Future value:\t\t"
    + currency.format(futureValue) + "\n";

    // print the results
    System.out.println();
    System.out.println("FORMATTED RESULTS");
    System.out.println(results);

    // see if the user wants to continue
    choice = Validator.validYesNo(sc, "Continue? (y/n): ");
    System.out.println();
    }
    }
    }

    //User defined supporting class to validate entries
    class Validator {
    //validate yes or no with empty entry
    public static String validYesNo( Scanner sc, String prompt)
    {
    String entryType = null;
    boolean isValid = false;
    while( !isValid) {
    System.out.print( prompt );
    entryType = sc.nextLine();
    if (entryType.equals("")) { //just pressed enter key
    System.out.println("Must enter your choice. Please try again...");
    }
    else if( !(entryType.equalsIgnoreCase("y")||
    entryType.equalsIgnoreCase("n")) ) {
    System.out.println("Only 'y' or 'n' is allowed.");
    isValid = false;
    }
    else
    isValid = true;
    }
    return( entryType);
    }
    //validate double
    public static double validDouble(Scanner sc, String prompt)
    {
    double d = 0.0;
    boolean isValid = false;
    while (isValid == false)
    {
    try {

    System.out.print(prompt);
    if (sc.hasNextDouble())
    {
    d = sc.nextDouble();
    isValid = true;
    }
    else
    { // throw an API exception class
    throw new NumberFormatException("Error! Invalid double value. Try again.");

    }

    }// end of try block

    catch (NumberFormatException e)
    {
    System.out.println(e);
    }
    sc.nextLine(); // discard any other data entered on the line
    }
    return d;
    }

    //vlaidate double with range
    public static double validDoubleWithinRange(Scanner sc, String prompt,
    double min, double max)
    {
    double d = 0.0;
    boolean isValid = false;
    while (isValid == false)
    {
    try {

    d = validDouble(sc, prompt);
    if (d <= min) // throw user-defined exceptions
    throw new DoubleOutOfMinRangeException("Error! Number must be greater than " + min + ".");
    else if (d >= max)
    throw new DoubleOutOfMaxRangeException("Error! Number must be less than " + max + ".");
    else
    isValid = true;
    } // end of try block
    catch (DoubleOutOfMinRangeException e)
    {
    System.out.println(e);
    }
    catch (DoubleOutOfMaxRangeException e)
    {
    System.out.println(e);
    }

    }
    return d;
    }

    //validate int
    public static int validInt(Scanner sc, String prompt)
    {
    int i = 0;
    boolean isValid = false;
    while (isValid == false)
    {
    try {
    System.out.print(prompt);
    if (sc.hasNextInt())
    {
    i = sc.nextInt();
    isValid = true;
    }
    else
    { // throw an API exception
    throw new NumberFormatException("Error! Invalid integer value. Try again.");

    }
    } // end of try block
    catch (NumberFormatException e)
    {
    System.out.println(e);
    }

    sc.nextLine(); // discard any other data entered on the line
    }
    return i;
    }

    //validate int with range
    public static int validIntWithinRange(Scanner sc, String prompt,
    int min, int max)
    {
    int i = 0;
    boolean isValid = false;
    while (isValid == false)
    {
    try {

    i = validInt(sc, prompt);
    if (i <= min)
    System.out.println(
    "Error! Number must be greater than " + min + ".");
    else if (i <= min) // throw user-defined exceptions
    throw new IntOutOfMinRangeException("Error! Number must be greater than " + min + ".");
    else if (i >= max)
    throw new IntOutOfMaxRangeException("Error! Number must be less than " + max + ".");
    else
    isValid = true;

    } // end of try block
    catch (IntOutOfMinRangeException e)
    {
    System.out.println(e);
    }
    catch (IntOutOfMaxRangeException e)
    {
    System.out.println(e);
    }
    }
    return i;
    }
    }

    // user-defined supporting exception classes

    class DoubleOutOfMinRangeException extends Exception
    {
    public DoubleOutOfMinRangeException()
    { }

    public DoubleOutOfMinRangeException(String message)
    {
    super(message);
    }
    }

    class DoubleOutOfMaxRangeException extends Exception
    {
    public DoubleOutOfMaxRangeException()
    { }

    public DoubleOutOfMaxRangeException(String message)
    {
    super(message);
    }
    }

    class IntOutOfMinRangeException extends Exception
    {
    public IntOutOfMinRangeException()
    { }

    public IntOutOfMinRangeException(String message)
    {
    super(message);
    }
    }

    class IntOutOfMaxRangeException extends Exception
    {
    public IntOutOfMaxRangeException()
    { }

    public IntOutOfMaxRangeException(String message)
    {
    super(message);
    }
    }

    //supporting class to calculate future value
    class Investment {
    public static double calculateFutureValue(double monthlyInvestment,
    double monthlyInterestRate, int months)
    {
    double futureValue = 0;
    for (int i = 1; i <= months; i++)
    {
    futureValue =
    (futureValue + monthlyInvestment) *
    (1 + monthlyInterestRate);
    }
    return futureValue;
    }

    }

Similar Threads

  1. Replies: 3
    Last Post: 01-01-2011, 02:36 AM
  2. RegardingSgould Enter in user defined inbox
    By Prashant.surwade in forum CLDC and MIDP
    Replies: 0
    Last Post: 09-23-2009, 01:21 PM
  3. Replies: 21
    Last Post: 06-11-2009, 02:18 AM
  4. Responding to button presses
    By Java Tip in forum javax.swing
    Replies: 0
    Last Post: 06-26-2008, 07:38 PM
  5. Replies: 2
    Last Post: 04-16-2008, 12:18 PM

Tags for this Thread

Posting Permissions

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