Help with displaying error messages

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 5759 Views - Last Post: 06 August 2010 - 09:01 PM Rate Topic: -----

#1 Guest_Navalava*


Reputation:

Help with displaying error messages

Posted 04 August 2010 - 09:02 AM

I'm trying to do this: http://docs.google.c...hYjJmYTdh&hl=en

In the requirements, if the user doesn't enter anything at the continue prompt, the program is supposed to display an error message. I tried using a NullPointerException to do this, but it didn't work. When I run the program, if I don't enter anything at the continue prompt, nothing happens.

Also, if the user enters 'x' instead of 'y' or 'n', the program displays the appropriate error message, but the continue prompt doesn't reappear.

Below is my code. Please let me know if you can find where I went wrong:
import java.util.*;
import java.text.*;

public class Five
{
	public static void main(String[] args)
	{
		String choice = "y";
		Scanner sc = new Scanner(System.in);
		System.out.println("Welcome to the Area and Perimeter Calculator");
		while (choice.equalsIgnoreCase("y"))
		{int first=0;
			System.out.println();
			double length = getDoubleWithinRange (sc, "Enter length: ", 0, 1000000);
			double width = getDoubleWithinRange (sc, "Enter width: ", 0, 1000000);
			double area = length * width;
			double perimeter = (2 * length) + (2 * width);
			String results = "Area:\t\t" + area + "\n" + "Perimeter:\t" + perimeter;
			System.out.print(results);
			System.out.println();
			try
			{
				System.out.println();
				System.out.print("Continue? (y/n): ");
				do{
					if(first==1)
						System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
					choice = sc.next();
					first=1;
				 }
				while(! (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")))
				;

				System.out.println();
			}
			catch (NullPointerException e)
			{

				System.out.println("Error! This entry is required. Try again.");
				sc.next();
			}
		}
	}
	public static double getDouble(Scanner sc, String prompt)
		{
			double d = 0.0;
			boolean isValid = false;
			while (isValid == false)
			{
				System.out.print(prompt);
				if (sc.hasNextDouble())
				{
					d = sc.nextDouble();
					isValid = true;
				}
				else
				{
					System.out.println("Error! Invalid decimal value. Try again.");
					sc.nextLine();
				}
			}
			return d;
	}
	public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
	{
		double d = 0.0;
		boolean isValid = false;
		while (isValid == false)
		{
			d = getDouble(sc, prompt);
			if (d<=min)
			{
				System.out.println("Error! Number must be greater than " + min
				+ ".");
			}
			else if (d >= max)
			{
				System.out.println("Error! Number must be less than " + max +
				".");
			}
			else
				isValid = true;
		}
		return d;
	}

}



Is This A Good Question/Topic? 0

Replies To: Help with displaying error messages

#2 Sergio Tapia   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1258
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: Help with displaying error messages

Posted 04 August 2010 - 09:18 AM

I'm fairly new to Java-ness coding practices; why are your passing a Scanner object to your methods instead of just passing the captured value?
Was This Post Helpful? 0
  • +
  • -

#3 calebjonasson   User is offline

  • Enter Title Here
  • member icon

Reputation: 209
  • View blog
  • Posts: 989
  • Joined: 28-February 09

Re: Help with displaying error messages

Posted 04 August 2010 - 09:40 AM

A string with no information in it ie:
String e = ""
Is not a null string. This still has a pointer value inside of it. The string will have to be null in order for this to work.
Was This Post Helpful? 0
  • +
  • -

#4 guido-granobles   User is offline

  • D.I.C Addict
  • member icon

Reputation: 171
  • View blog
  • Posts: 617
  • Joined: 02-December 09

Re: Help with displaying error messages

Posted 04 August 2010 - 09:51 AM

The next() method block while waiting for input to scan. It does not do anything if the user press the key enter. You should use the method nextLine() in this case if the user press the key enter this method return "".
Was This Post Helpful? 0
  • +
  • -

#5 Sergio Tapia   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1258
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: Help with displaying error messages

Posted 04 August 2010 - 10:32 AM

Here's my stab at it, since I'm a beginner of Java I'd like some suggestions on where I can improve.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String choice = "y";
        double Perimeter = 0;
        double Area = 0;

        System.out.println("Perimeter and Area Calculator.");

        while (choice.equalsIgnoreCase("y")) {
            System.out.println(" ");

            System.out.println("Please enter the Length:");
            double Length = scanner.nextDouble();
            System.out.println("Please enter the Width.");
            double Width = scanner.nextDouble();

            Area = Length * Width;
            Perimeter = (2 * Length) + (2 * Width);

            System.out.println("Results: Area - " + Area + "|| Perimeter - " + Perimeter);

            System.out.println("Would you like to calculate something else?");
            if (!scanner.next().equalsIgnoreCase("y")) {
                System.out.println("Thanks for using the program!");
                break;
            }
        }
    }
}



This code doesn't:
1. Check for null inputs.
2. Check for negative numbers.
3. Check for range of number.

Any suggestions?

This post has been edited by stapia.gutierrez: 04 August 2010 - 10:33 AM

Was This Post Helpful? 0
  • +
  • -

#6 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Help with displaying error messages

Posted 04 August 2010 - 11:37 AM

Well yes , yours is doing what you intend it to do, but the OP is using methods. He is trying to be focus more on OOP and that is definitely a good thing!

Okay so for the problems:

1. Displaying error message if nothing is inputted for length/width:

As mentioned above, you'd be better off using the .nextLine() for this problem. That will give you a String of whatever was inputted on the line before pressing enter.

Of course, when you have the String you are going to want to check if it's not equal to "" (empty string), in which case you will set it equal to your double variable d.
theString = sc.nextLine();

			if (!theString.equals(""))
			{



Now you can't just set a String to be equal to a double, so you have to Parse the string. The parseDouble method will help you with this. It's in the Double class and you can check that from the java docs. So something like this:
d = Double.parseDouble(theString);
				isValid = true;
			} else
			{
				System.out.println("Must enter a value!");



That should set you well on your way!

2. Displaying error message and asking for another choice when entering wrong input on the continue question:

From the looks of it, you very much over complicated this part. It can be done the same way with the nextLine() method, only you don't have to worry about parsing anything. Something like this will get you started:
System.out.print("Continue? (y/n): ");
			choice = sc.nextLine();

			while (!choice.equalsIgnoreCase("y")
					&& !choice.equalsIgnoreCase("n"))



The you'll just have to check for wrong input, or empty string and print a different message for each case.



Any more questions? Just ask!

Hope this helps!
Was This Post Helpful? 3
  • +
  • -

#7 Guest_Navalava*


Reputation:

Re: Help with displaying error messages

Posted 06 August 2010 - 02:11 PM

Thank you everyone for all the helpful advice! I managed to simplify it a little bit, but it's still not working the way it's supposed to. Here's the modified version:
String newprompt = "Continue? (y/n): ";
			System.out.print(newprompt);
			choice = sc.next();
			String theString = sc.nextLine();
			if (choice != "")
			{
				if (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n"))
				{
					System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
				}
			}
			else if (choice == "")
			{
				System.out.println("Error! This entry is required. Try again.");
				sc.nextLine();
			}


Was This Post Helpful? 0

#8 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Help with displaying error messages

Posted 06 August 2010 - 03:50 PM

What's going wrong with your code now? Maybe I can further assist you.
Was This Post Helpful? 0
  • +
  • -

#9 Guest_Navalava*


Reputation:

Re: Help with displaying error messages

Posted 06 August 2010 - 04:25 PM

Oh right, I forgot to explain the problem, haha. At this point, when I enter a value other than 'y' or 'n', the error message displays properly, and the program prompts the user again to enter a value. However, when I don't enter any value, or press 'enter', the program doesn't display the error message "Error! This entry is required. Try again." I also modified the code from last time. Here it is:
boolean cool = true;
			while (true)
			{
				String newprompt = "Continue? (y/n): ";
				System.out.print(newprompt);
				choice = sc.next();
				String theString = sc.nextLine();
				if (!choice.equals(""))
				{
					System.out.println("Error! This entry is required. Try again.");
					cool = true;
				}
				else if (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n"))
				{
					System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
					cool = true;
				}
				else if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n"))
				{
					break;
				}
			}


Was This Post Helpful? 0

#10 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Help with displaying error messages

Posted 06 August 2010 - 04:34 PM

Well I wouldn't suggest using your "choice" variable at all. I'd do this all with theString variable because that is getting the entire line.

Also, the last else-if isn't hurting anything from what I can tell, but you could also just change the boolean variable in there instead of using break.

Try the nextLine() method and let me know what happens.
Was This Post Helpful? 0
  • +
  • -

#11 Guest_Navalava*


Reputation:

Re: Help with displaying error messages

Posted 06 August 2010 - 04:54 PM

I tried replacing all of the 'choice'(s) in the if-statements with 'theString', but then, even if I put 'y' or 'n' at the prompt, the error message kept appearing. Also, I included the break at the end because I wanted it to come out of the while loop so it could fall under another while-loop (not included in the code I pasted). Also, I checked what the difference between next() and nextLine() was in one of my Java textbooks (Murach's Java SE6), and it says that the nextLine() method is used to discard the remaining values in a line. So how would that help me here?
Was This Post Helpful? 0

#12 n8wxs   User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Help with displaying error messages

Posted 06 August 2010 - 05:02 PM

Here's how I 'simplified' your loop: :)

...
while (true) {
    System.out.print("Continue? (y/n): ");

    // get user input
    choice = sc.nextLine();

    // remove any leading or trailing white space
    choice = choice.trim();

    // Only accept single character input
    if (choice.length() == 1) {
        // force lowercase string
        choice = Character.toString(Character.toLowerCase(choice.charAt(0)));

        if ((choice.equals("y") || choice.equals("n"))) {
            break; // legal input - exit to outer while() loop
        }
    }

    System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
}
...



Here's the output:

Quote

run:
Welcome to the Area and Perimeter Calculator

Enter length: 10
Enter width: 20
Area: 200.0
Perimeter: 60.0

Continue? (y/n): c
Error! Entry must be 'y' or 'n'. Try again.
Continue? (y/n): 123
Error! Entry must be 'y' or 'n'. Try again.
Continue? (y/n): ssss
Error! Entry must be 'y' or 'n'. Try again.
Continue? (y/n):
Error! Entry must be 'y' or 'n'. Try again.
Continue? (y/n): n

BUILD SUCCESSFUL (total time: 23 seconds)


I did make one change to the getDouble() method:

public static double getDouble(Scanner sc, String prompt) {
    double d = 0.0;
    boolean isValid = false;
    while (isValid == false) {
        System.out.print(prompt);
        if (sc.hasNextDouble()) {
            d = sc.nextDouble();
            isValid = true;
        } else {
            System.out.println("Error! Invalid decimal value. Try again.");
        }
    }
    sc.nextLine(); // eat line terminator
    return d;
}



EDIT:

I moved the sc.nextLine(); statement to the bottom of the method since the line terminator needs to be 'eaten' regardless of whether the user entered a double or not.

Something was bothering me about the change I made - the sc.nextLine(); statement needs to stay where it was as the while() loop won't exit if the 'bad' input isn't removed. The statement I added at the bottom can either stay there or be moved to follow the d = sc.nextDouble(); statement.

Both sides of the if() statement need to 'flush' the input stream.

Here's the corrected method:

public static double getDouble(Scanner sc, String prompt) {
    double d = 0.0;
    boolean isValid = false;
    while (isValid == false) {
        System.out.print(prompt);
        if (sc.hasNextDouble()) {
            d = sc.nextDouble();
            sc.nextLine(); // eat line terminator
            isValid = true;
        } else {
            System.out.println("Error! Invalid decimal value. Try again.");
            sc.nextLine(); // remove non-double input
        }
    }
    return d;
}


This post has been edited by n8wxs: 06 August 2010 - 07:17 PM

Was This Post Helpful? 2
  • +
  • -

#13 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Help with displaying error messages

Posted 06 August 2010 - 05:11 PM

Well Navalava, let me show you what I did to your code to make it work correctly, and I'll explain line by line(taken from your original code):

System.out.print("Continue? (y/n): ");
choice = sc.nextLine();


^nextLine() is used here because it will set choice to any input (or no input) before enter is pressed

just one while loop here is all that was needed, keep looping until the user enters a y or an n
			
while (!choice.equalsIgnoreCase("y")&&    !choice.equalsIgnoreCase("n"))



So now within the while loop we know it wasn't a y or an n, so first we check if it was nothing...
{
                                
if (choice.equals(""))
{
        System.out.println("Error! This entry is required. Try again.");
        System.out.print("Continue? (y/n): ");
}



Then we check to see if it was something other than nothing or y and n
else
{
	System.out.println("Error! Entry must be 'y' or 'n'. Try again.");

        System.out.println("Continue? (y/n): ");
					         
}



Then just simple get the input again, and the loop will start over
choice = sc.nextLine();
}



This code was all made from what you originally had. You were actually very very close. :bigsmile:

This post has been edited by eZACKe: 06 August 2010 - 05:21 PM

Was This Post Helpful? 2
  • +
  • -

#14 Guest_Navalava*


Reputation:

Re: Help with displaying error messages

Posted 06 August 2010 - 07:29 PM

Thank you very much eZACKe! That was a great help! This time, the appropriate error messages were displayed at the right time, but there was one extra thing. Let me write down the output I got:

Welcome to the Area and Perimeter Calculator

Enter length: 4 --user inputs value and presses 'enter'
Enter width: 5 --user inputs value and presses 'enter'
Area: 20.0-output value
Perimeter: 18.0-output value

--Here comes the extra part

Continue? (y/n): Error! This entry is required! Try again.
Continue? (y/n): n
Press any key to continue...

The extra part is that error message that comes without me inputing any value at the continue prompt. The second continue prompt that comes works properly (displays the proper error messages, etc.), but I'm not sure why the first error message appears spontaneously. I coded it exactly in the order you gave me:
System.out.print("Continue? (y/n): ");
			choice = sc.nextLine();
			while (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n"))
			{
				 if (choice.equals(""))
				 {
		 	        System.out.println("Error! This entry is required. Try again.");
		 	        System.out.print("Continue? (y/n): ");
				 }
				 else
				 {
			   		  System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
				      System.out.print("Continue? (y/n): ");
				 }
				choice = sc.nextLine();
			}



But I can't see any connection between the continue prompt and the actual calculator part besides the all-encompassing while (choice.equalsIgnoreCase("y")) at the very beginning of the class. Sorry if I seem really picky about details, but I just see these as opportunities where I can grasp the basics of java better.

P.S. How do I make my output appear the way n8wxs did it?
Was This Post Helpful? 0

#15 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Help with displaying error messages

Posted 06 August 2010 - 08:20 PM

Could you post your whole updated code? I just substituted what you posted above into my working program, and it still works as expected. It must be something else somewhere. I'd like to take a look and compare what you're doing.


EDIT: And oh by the way, you're welcome! Glad to help. :bigsmile:

This post has been edited by eZACKe: 06 August 2010 - 08:23 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2