473,698 Members | 2,339 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Java data validation question

2 New Member
Ok this is homework, and I have wrestled with this for quite awhile now. My program is supposed to give an error message if the user enters any invalid entries. The program works great when the user enters an invalid integer, but my problem is trying to get it to give an error message when the user enters an invalid entry when asked if they want to continue. Currently right now it just runs again if an invalid entry is entered. But I need it to give an error message if the user enters anything other than y or n. Id appreciate any help and suggestions on this. Thanks


*************** *************** *************** *************** *************** *************** **
Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2. import java.text.*;
  3.  
  4. public class MReikowskyapp51
  5. {
  6.     public static void main(String[] args)
  7.     {
  8.         // welcome the user to the program
  9.         System.out.println("Welcome to the Factorial Calculator");
  10.         System.out.println();  // print a blank line
  11.  
  12.         // create a Scanner object named sc and intializ variables
  13.  
  14.  
  15.         Scanner sc = new Scanner(System.in);
  16.  
  17.         // perform Factorial application when user enters "y" or "Y"
  18.         String choice = "y";
  19.         while (choice.equalsIgnoreCase("y"))
  20.         {
  21.             //get input from user
  22.             int power = getIntWithinRange(sc,
  23.             "Enter number greater than 0 and less than 10: ", 0, 10);
  24.             long number = 1;
  25.             //use a for loop to calculate the power
  26.             for (int i = 1; i<= power; i++)
  27.             {
  28.  
  29.                    number = number * i;
  30.              }
  31.                    System.out.println("power " + number + "\n");
  32.                    String cont = "";
  33.                    System.out.println("Continue? (y/n)");
  34.                    cont = sc.next();
  35.                    sc.nextLine();
  36.                    System.out.println();
  37.  
  38.  
  39.          }
  40. }
  41. public static int getInt (Scanner sc, String prompt)
  42. {
  43.     int i = 0;
  44.     boolean isValid = false;
  45.     while (isValid == false)
  46.     {
  47.         System.out.print(prompt);
  48.         if (sc.hasNextInt())
  49.         {
  50.             i = sc.nextInt();
  51.             isValid = true;
  52.         }
  53.         else
  54.         {
  55.             System.out.println
  56.             ("Error! Invalid integer value. Try again.");
  57.         }
  58.         sc.nextLine(); //discard any other data entered on the line
  59.     }
  60.     return i;
  61. }
  62.     public static int getIntWithinRange (Scanner sc, String prompt, int min, int max)
  63.     {
  64.         int i = 0;
  65.         boolean isValid = false;
  66.         while (isValid == false)
  67.         {
  68.             i = getInt(sc, prompt);
  69.             if (i <= min)
  70.                 System.out.println("Error! Number must be greater than " + min + ".");
  71.  
  72.             else if (i >= max)
  73.             System.out.println("Error! Number must be less than " + max + ".");
  74.  
  75.             else
  76.             isValid = true;
  77.         }
  78.         return i;
  79.     }
  80.   }//end program
Feb 18 '07 #1
3 3912
horace1
1,510 Recognized Expert Top Contributor
the line
Expand|Select|Wrap|Line Numbers
  1.                    System.out.println("Continue? (y/n)");
  2.                    cont = sc.next();
  3.  
should be
Expand|Select|Wrap|Line Numbers
  1.                    System.out.println("Continue? (y/n)");
  2.                    choice = sc.next();
  3.  
because you test choice in
Expand|Select|Wrap|Line Numbers
  1.         while (choice.equalsIgnoreCase("y"))
  2.         {
  3.  
Feb 18 '07 #2
MBReikowsky
2 New Member
Ok thank you very much. My next question is where and how do I post the error message if something other than y or n is entered? Ive looked all over in my book and I couldnt find the command that will validate a string. I found plenty for numbers IE nextDouble but nothing that explains how to check the data they enter when they determine if they wish to continue or not?
Feb 18 '07 #3
Ganon11
3,652 Recognized Expert Specialist
You can use the .equals() function in the String class. No matter what they enter, you will be interpreting it as a String, whether it is actually a number, character, word, etc.

Once you have the input in a variable (choice?), use

choice.equals(" y");

to determine if it is y. You can use the same function to see if it is n. If it is neither y nor n (that is, !choice.equals( "y") && !choice.equals( "n")), then the user has entered a bad input.
Feb 18 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

4
1757
by: TP | last post by:
Hi, I have reached a situation where I have to create small pieces of xml (around 8k characters) within my java app. Right now I am using stringbuffer to create the xml which does not go against a dtd. This is working for now, since I do not have to read in the xml again. But if I wanted to use some other xml utility like xerces or jdom, is it recommended for my use of xml or would it be an overkill. Please let me know.
0
4106
by: Brian | last post by:
I am having alot of trouble getting a XML document validated with a schema. I got a sample document and schema off of w3schools.com, which passed an online xml validator: http://tools.decisionsoft.com/schemaValidate.html. I cannot, however, get them validated programmatically. The documents are:
2
2683
by: Dnna | last post by:
I have a table which is bound to an Internet Explorer XML data island. I'm using ASP.NET's client-side validators for an input field in the table. The problem is that if the input fields are in a table that is bound to the island (such that the rows are dynamically generated by IE from the XML data island), the validators do not work. If the table is not bound, the validators do work, but then I don't have the table iterating through...
1
9634
by: David Van D | last post by:
Hi there, A few weeks until I begin my journey towards a degree in Computer Science at Canterbury University in New Zealand, Anyway the course tutors are going to be teaching us JAVA wth bluej and I was wondering if anyone here would be able to give me some tips for young players such as myself, for learning the language. Is this the best Newsgroup for support with JAVA?
2
6956
by: Jobs | last post by:
Download the JAVA , .NET and SQL Server interview with answers Download the JAVA , .NET and SQL Server interview sheet and rate yourself. This will help you judge yourself are you really worth of attending interviews. If you own a company best way to judge if the candidate is worth of it. http://www.questpond.com/InterviewRatingSheet.zip
4
11046
by: Francois Stander | last post by:
Hi, hope someone can help me. It seems imposible to read data from a server, however, I can read the validation data from the server and hold it in dataviews . datasets or data tables in my asp "load" page. I would like to use these data (which I presume is in some form of html or xml) in my HTML portion of the asp page. The data must be read using java script and after lots of calculations perform on it - be written to xml controls. I can...
1
4304
by: jaimemartin | last post by:
hello, I want to validate an xml by means of a schema (xsd). To do that first of all I´m using a SchemaFactory. The problem is that if I run the code in Windows all works fine, but If I run it in Linux there is an error. The code that fails is the following: SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); I´m sure that code is ok. In fact, I´ve found that in several...
20
6919
by: hippomedon | last post by:
Hello everyone, I'm looking for some advice on whether I should break the normalization rule. Normally, I would not consider it, but this seems to be a special case. I have created an "Outcomes Database" used to store response data from measures/ questionnaires for a longitudinal health study. It is essentially derived from Duane Hookom's Survey Database (thanks Duane!!!), with many modifications added to fit the needs of my lab.
0
8674
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9027
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8895
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7725
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6518
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3046
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2329
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.