3

In my validation method I want it to print an error message if the user inputs letters instead of decimal value, the method does exactly that it prints an error message on the console, but it prints it twice, for example if i input "dfdff" instead of a decimal it prints out:
"Error, invalid number.Try Again"

"Error, invalid number.Try Again"

How do I make it print the error message once each time the user inputs the wrong value???

 public static double getVaildSubtotal(Scanner sc)
{

    double subtotal = 0.0;
    boolean isValid = false;
    while (isValid == false)
    {
       if (sc.hasNextDouble())
       {
           subtotal = sc.nextDouble();
           isValid = true;
       }
       else
       {
           System.out.println("Error! Invalid decimal value. Try again.");
       }
       sc.nextLine();

       if (isValid == true && subtotal <= 0)
       {
           System.out.println("Error! Number must be greater then 0.");
           isValid = false;
       }
       else if (isValid == true && subtotal >= 10000)
       {
          System.out.println("Error! Number must be less then 10000.");
           isValid = false; 
       }

    }

    return subtotal;
}
1
  • i'm curious if you ever got this going; this is exactly the kind of coding i've been working on lately.
    – pandorym
    Feb 13, 2013 at 14:22

3 Answers 3

2

Now I just started working with Java, so be gentle on me.

In a little applet I was writing for class I came into something similar, so I adapted the principles:

public static double getVaildSubtotal(Scanner sc)
{ 
    double subtotal = 0.0;
    boolean isValid = false;
    while (isValid != true)
    {
        String stSubTotal = sc.nextLine().trim();
        int subTotalLength = stSubTotal.length();  
        boolean checkDouble = true;
        for (int k = 0; k < subTotalLength; k++)
        {
            if (Character.isDigit(stSubTotal.charAt(k)) != true)
            {
                System.out.println("Error! Invalid decimal value. Try again.");
                checkDouble = false;
            }
        }
        if (checkDouble == true)
        {
            subtotal = Double.parseDouble(stSubTotal);
            if (subtotal <= 0)
            {
                System.out.println("Error! Number must be greater then 0.");                    
            }
            else if (subtotal >= 10000)
            {
                System.out.println("Error! Number must be less then 10000.");                    
            }
            else
            {
                isValid = true;
            }
        }            
    }
    return subtotal;
}

Anyway, like this you get only one error code per entry as the entry gobbles up the whole line.

But, if you aren't interested in rebuilding the wheel (and, honestly, I won't be insulted), the current issue with the code is the your sc.nextLine(); Now, .nextLine()

"advances this scanner past the current line and returns the input that was skipped."

In this case, and it's only my belief, your sc.nextLine(); is reading the input of .nextLine() like it is supposed to. So when it comes around to see if there is a double inside, nope, there is no double, only \n.

I would suggest removing sc.nextLine(); if definitely need a blank space, want it to be a nextLine(), I would add another local Scanner for .nextLine(); in the validation method.

1

This is probably because the Scanner class's nextDouble() method doesn't "eat" the newline. This can cause the nextLine() method to return an empty line before moving to the next line after a primitive is read in via the nextDouble() and similar methods.

This can lead to some tricky results, but the simplest way is to force the Scanner to process the newline explicitly, by adding inserting an extra nextLine() here:

if (sc.hasNextDouble()) {
    subtotal = sc.nextDouble();
    sc.nextLine();
    isValid = true;
}

Beware that this can cause unexpected results when the scanner's delimiter is not just matching newlines. In this case, you might accidentally skip multiple inputs. Since you usually want to split by newlines, anyway, you can create a more permanent solution by changing the scanner's delimiter when you create it, like this:

Scanner sc = new Scanner(System.in);
sc.useDelimiter("[\r\n]+");

Using that solution, you will no longer need to use extra nextLine() calls, because any extra newlines will be ignored. However, this system will also fail to respond to blank line inputs, which will be simply skipped with that delimiter. If you want those to be processed, you can use the extra nextLine() fix along with this delimiter for safety:

sc.useDelimiter("\r\n|[\r\n]");
0

Your have to call sc.nextLine(); two times because after give some input you are pressing enter that generate newline.
So for that you can process this extra newline by adding one more sc.nextLine();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.