SlideShare a Scribd company logo
1 of 7
Download to read offline
I Have the following Java program in which converts Date to Words and the only thing I have to
do now is add a boolean for a leap year. ( I am using Apache NetBeans) please explain where the
boolean goes.
Like this:
I need the code working with the boolean added, Thank you!!!
package a1_demo;
import java.util.Scanner;
public class MainApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Welcome to the Date to Words Converter!nn");
while ( true ) {
// get user input
String str_MM_DD_YYYY = Validator.getString(
Validator.sc,
"Enter date in MM/DD/YYYY format: "
);
// convert text to ints:
// "11/22/3333" - > int, int int
String[] dateComponents = str_MM_DD_YYYY.split( "/" );
if ( dateComponents.length != 3 ) {
System.out.println("tt Bad input, please retry...");
continue;
}
int month = 0;
int day = 0;
int year = 0;
try {
month = Integer.parseInt(dateComponents[ 0 ]);
day = Integer.parseInt(dateComponents[ 1 ]);
year = Integer.parseInt(dateComponents[ 2 ]);
} catch ( java.lang.NumberFormatException ex ) {
System.out.println("tt numeric values are expected, please retry...");
continue;
}
Date2TextConverter converter = new Date2TextConverter( month, day, year );
System.out.print( converter.month2text() );
System.out.print( " " );
System.out.print( converter.day2text() );
System.out.print( " " );
System.out.print( converter.year2text() );
System.out.println();
}// endless while loop
}//main
}//class MainApp
package a1_demo;
public class Date2TextConverter {
//---------------------------------------
// data
//---------------------------------------
int month = 0;
int day = 0;
int year = 0;
//---------------------------------------
// constructors
//---------------------------------------
public Date2TextConverter(int month, int day, int year )
{
this.month = month;
this.day = day;
this.year = year;
}//Date2TextConverter
//---------------------------------------
// operations
//---------------------------------------
public String month2text()
{
switch( month )
{
case 1: return "Jan";
case 2: return "Feb";
case 3: return "Mar";
case 4: return"April";
case 5: return"May";
case 6: return"June";
case 7: return"July";
case 8: return"Aug";
case 9: return"Sep";
case 10: return"Oct";
case 11: return"Nov";
case 12: return"Dec";
//...
default:
return "Invalid Month";
}
}//month2text
public String day2text()
{
//return Integer.toString( day );
return number2words (day);
}//day2text
public String year2text()
{
int century = year / 100;
int yearInCentury = year % 100;
String centuryText = number2words( century );
String yearText = number2words( yearInCentury );
if ( yearInCentury < 10 ) {
return centuryText + " zero " + yearText;
} else {
return centuryText + " " + yearText;
}
}//year2text
private String number2words( int number ) {
// convert to text a number 0 through 99
if ( number < 20 ) {
// 0, 1, 2, 3, ..., 19
return zero2nineteen[ number ];
} else if ( number % 10 == 0 ) {
// 20, 30, 40, ... 90
return decades[ number / 10 - 2 ];
} else {
// 21, 22, 23, 24, ... 29, 31, 32, ..., 99
return decades[ number / 10 - 2 ] + " " + zero2nineteen[ number % 10 ];
}
} //number2words
//---------------------------------------
// static vocabulary
//---------------------------------------
private static final String[] zero2nineteen = {
"zero", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fouteen", "fifteen", "sixteen",
"seventeen",
"eighteen", "nineteen"
};
private static final String[] decades = {
"twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", "ninety"
};
}//class Date2TextConverter
import java.util.Scanner;
public class Validator
{
public static Scanner sc = new Scanner( System.in );
public static String getString(Scanner sc, String prompt)
{
String s = null;
do
{
System.out.print(prompt);
s = sc.nextLine(); // read user entry
if (s.equals(""))
{
System.out.println("String cannot be left blank!");
}
} while (s.equals(""));
return s;
}
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public static int getInt(Scanner sc, String prompt,
int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println(
"Error! Number must be greater than " + min + ".");
else if (i >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return i;
}
public static double getDouble(Scanner sc, String prompt)
{
double d = 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(); // discard any other data entered on the line
}
return d;
}
public static double getDouble(Scanner sc, String prompt,
double min, double max)
{
double d = 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;
}
}

More Related Content

Similar to I Have the following Java program in which converts Date to Words an.pdf

So Far I have these two classes but I need help with my persontest c.pdf
So Far I have these two classes but I need help with my persontest c.pdfSo Far I have these two classes but I need help with my persontest c.pdf
So Far I have these two classes but I need help with my persontest c.pdf
arihantgiftgallery
 
Java questionI am having issues returning the score sort in numeri.pdf
Java questionI am having issues returning the score sort in numeri.pdfJava questionI am having issues returning the score sort in numeri.pdf
Java questionI am having issues returning the score sort in numeri.pdf
forwardcom41
 
Java programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdfJava programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdf
fathimafancy
 
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdfWrite the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
arihantmum
 
@author public class Person{   String sname, .pdf
  @author   public class Person{   String sname, .pdf  @author   public class Person{   String sname, .pdf
@author public class Person{   String sname, .pdf
aplolomedicalstoremr
 
I am having some trouble getting this to compile, I have made seve.docx
I am having some trouble getting this to compile, I have made seve.docxI am having some trouble getting this to compile, I have made seve.docx
I am having some trouble getting this to compile, I have made seve.docx
adampcarr67227
 

Similar to I Have the following Java program in which converts Date to Words an.pdf (17)

So Far I have these two classes but I need help with my persontest c.pdf
So Far I have these two classes but I need help with my persontest c.pdfSo Far I have these two classes but I need help with my persontest c.pdf
So Far I have these two classes but I need help with my persontest c.pdf
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
Java questionI am having issues returning the score sort in numeri.pdf
Java questionI am having issues returning the score sort in numeri.pdfJava questionI am having issues returning the score sort in numeri.pdf
Java questionI am having issues returning the score sort in numeri.pdf
 
Java programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdfJava programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdf
 
Lab01.pptx
Lab01.pptxLab01.pptx
Lab01.pptx
 
Nodejs do teste de unidade ao de integração
Nodejs  do teste de unidade ao de integraçãoNodejs  do teste de unidade ao de integração
Nodejs do teste de unidade ao de integração
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
sodapdf-converted into ppt presentation(1).pdf
sodapdf-converted into ppt presentation(1).pdfsodapdf-converted into ppt presentation(1).pdf
sodapdf-converted into ppt presentation(1).pdf
 
Lab101.pptx
Lab101.pptxLab101.pptx
Lab101.pptx
 
JS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless BebopJS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless Bebop
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Java script
Java scriptJava script
Java script
 
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdfWrite the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
 
@author public class Person{   String sname, .pdf
  @author   public class Person{   String sname, .pdf  @author   public class Person{   String sname, .pdf
@author public class Person{   String sname, .pdf
 
I am having some trouble getting this to compile, I have made seve.docx
I am having some trouble getting this to compile, I have made seve.docxI am having some trouble getting this to compile, I have made seve.docx
I am having some trouble getting this to compile, I have made seve.docx
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
JAVA.pdf
JAVA.pdfJAVA.pdf
JAVA.pdf
 

More from allystraders

Suponga que las tasas de inter�s en los Estados Unidos, pero no aume.pdf
Suponga que las tasas de inter�s en los Estados Unidos, pero no aume.pdfSuponga que las tasas de inter�s en los Estados Unidos, pero no aume.pdf
Suponga que las tasas de inter�s en los Estados Unidos, pero no aume.pdf
allystraders
 
How would I create this diagramRentTool Viewpoints � Technology .pdf
How would I create this diagramRentTool Viewpoints � Technology .pdfHow would I create this diagramRentTool Viewpoints � Technology .pdf
How would I create this diagramRentTool Viewpoints � Technology .pdf
allystraders
 
How well did Thaldorf interact with each member of the DMUOn what.pdf
How well did Thaldorf interact with each member of the DMUOn what.pdfHow well did Thaldorf interact with each member of the DMUOn what.pdf
How well did Thaldorf interact with each member of the DMUOn what.pdf
allystraders
 

More from allystraders (20)

Supplemental knowledge conversion processes have been added to the E.pdf
Supplemental knowledge conversion processes have been added to the E.pdfSupplemental knowledge conversion processes have been added to the E.pdf
Supplemental knowledge conversion processes have been added to the E.pdf
 
Supongamos que Musashi, un economista de un programa de radio AM, y .pdf
Supongamos que Musashi, un economista de un programa de radio AM, y .pdfSupongamos que Musashi, un economista de un programa de radio AM, y .pdf
Supongamos que Musashi, un economista de un programa de radio AM, y .pdf
 
Suponga que las tasas de inter�s en los Estados Unidos, pero no aume.pdf
Suponga que las tasas de inter�s en los Estados Unidos, pero no aume.pdfSuponga que las tasas de inter�s en los Estados Unidos, pero no aume.pdf
Suponga que las tasas de inter�s en los Estados Unidos, pero no aume.pdf
 
Suponga que la ARN polimerasa estaba transcribiendo un gen eucari�ti.pdf
Suponga que la ARN polimerasa estaba transcribiendo un gen eucari�ti.pdfSuponga que la ARN polimerasa estaba transcribiendo un gen eucari�ti.pdf
Suponga que la ARN polimerasa estaba transcribiendo un gen eucari�ti.pdf
 
Suppose researchers are about to draw a sample of 1450 observations .pdf
Suppose researchers are about to draw a sample of 1450 observations .pdfSuppose researchers are about to draw a sample of 1450 observations .pdf
Suppose researchers are about to draw a sample of 1450 observations .pdf
 
Suponga que el Congreso est� considerando un proyecto de ley que imp.pdf
Suponga que el Congreso est� considerando un proyecto de ley que imp.pdfSuponga que el Congreso est� considerando un proyecto de ley que imp.pdf
Suponga que el Congreso est� considerando un proyecto de ley que imp.pdf
 
Suppose that there are two groups of people in the economy. In group.pdf
Suppose that there are two groups of people in the economy. In group.pdfSuppose that there are two groups of people in the economy. In group.pdf
Suppose that there are two groups of people in the economy. In group.pdf
 
Suppose that the Fed will increase the money supply. Which of the fo.pdf
Suppose that the Fed will increase the money supply. Which of the fo.pdfSuppose that the Fed will increase the money supply. Which of the fo.pdf
Suppose that the Fed will increase the money supply. Which of the fo.pdf
 
Suppose that the body weights of Roborovski dwarf hamsters are norma.pdf
Suppose that the body weights of Roborovski dwarf hamsters are norma.pdfSuppose that the body weights of Roborovski dwarf hamsters are norma.pdf
Suppose that the body weights of Roborovski dwarf hamsters are norma.pdf
 
Suppose that in a particular country, the TFR fell to zero and remai.pdf
Suppose that in a particular country, the TFR fell to zero and remai.pdfSuppose that in a particular country, the TFR fell to zero and remai.pdf
Suppose that in a particular country, the TFR fell to zero and remai.pdf
 
Suppose that disposable income, consumption, and saving in some coun.pdf
Suppose that disposable income, consumption, and saving in some coun.pdfSuppose that disposable income, consumption, and saving in some coun.pdf
Suppose that disposable income, consumption, and saving in some coun.pdf
 
Suppose that 60 of students at Kansas State University have listene.pdf
Suppose that 60 of students at Kansas State University have listene.pdfSuppose that 60 of students at Kansas State University have listene.pdf
Suppose that 60 of students at Kansas State University have listene.pdf
 
Suppose Maria and Jamal both face the following individual loss dist.pdf
Suppose Maria and Jamal both face the following individual loss dist.pdfSuppose Maria and Jamal both face the following individual loss dist.pdf
Suppose Maria and Jamal both face the following individual loss dist.pdf
 
Suppose a random variable X has the following probability distributi.pdf
Suppose a random variable X has the following probability distributi.pdfSuppose a random variable X has the following probability distributi.pdf
Suppose a random variable X has the following probability distributi.pdf
 
Suppose a country had a smaller increase in debt in 2011 than it had.pdf
Suppose a country had a smaller increase in debt in 2011 than it had.pdfSuppose a country had a smaller increase in debt in 2011 than it had.pdf
Suppose a country had a smaller increase in debt in 2011 than it had.pdf
 
how would implement empowerment techniques within a service Choose .pdf
how would implement empowerment techniques within a service Choose .pdfhow would implement empowerment techniques within a service Choose .pdf
how would implement empowerment techniques within a service Choose .pdf
 
How were the management controls at Siemens prior to the Bribery sca.pdf
How were the management controls at Siemens prior to the Bribery sca.pdfHow were the management controls at Siemens prior to the Bribery sca.pdf
How were the management controls at Siemens prior to the Bribery sca.pdf
 
How would I create this diagramRentTool Viewpoints � Technology .pdf
How would I create this diagramRentTool Viewpoints � Technology .pdfHow would I create this diagramRentTool Viewpoints � Technology .pdf
How would I create this diagramRentTool Viewpoints � Technology .pdf
 
How well did Thaldorf interact with each member of the DMUOn what.pdf
How well did Thaldorf interact with each member of the DMUOn what.pdfHow well did Thaldorf interact with each member of the DMUOn what.pdf
How well did Thaldorf interact with each member of the DMUOn what.pdf
 
How do increasing atmospheric CO2 emissions threaten sea creatures, .pdf
How do increasing atmospheric CO2 emissions threaten sea creatures, .pdfHow do increasing atmospheric CO2 emissions threaten sea creatures, .pdf
How do increasing atmospheric CO2 emissions threaten sea creatures, .pdf
 

Recently uploaded

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 

I Have the following Java program in which converts Date to Words an.pdf

  • 1. I Have the following Java program in which converts Date to Words and the only thing I have to do now is add a boolean for a leap year. ( I am using Apache NetBeans) please explain where the boolean goes. Like this: I need the code working with the boolean added, Thank you!!! package a1_demo; import java.util.Scanner; public class MainApp { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Welcome to the Date to Words Converter!nn"); while ( true ) { // get user input String str_MM_DD_YYYY = Validator.getString( Validator.sc, "Enter date in MM/DD/YYYY format: " ); // convert text to ints: // "11/22/3333" - > int, int int String[] dateComponents = str_MM_DD_YYYY.split( "/" ); if ( dateComponents.length != 3 ) { System.out.println("tt Bad input, please retry..."); continue; } int month = 0; int day = 0; int year = 0; try { month = Integer.parseInt(dateComponents[ 0 ]); day = Integer.parseInt(dateComponents[ 1 ]); year = Integer.parseInt(dateComponents[ 2 ]);
  • 2. } catch ( java.lang.NumberFormatException ex ) { System.out.println("tt numeric values are expected, please retry..."); continue; } Date2TextConverter converter = new Date2TextConverter( month, day, year ); System.out.print( converter.month2text() ); System.out.print( " " ); System.out.print( converter.day2text() ); System.out.print( " " ); System.out.print( converter.year2text() ); System.out.println(); }// endless while loop }//main }//class MainApp package a1_demo; public class Date2TextConverter { //--------------------------------------- // data //--------------------------------------- int month = 0; int day = 0; int year = 0; //--------------------------------------- // constructors //--------------------------------------- public Date2TextConverter(int month, int day, int year ) { this.month = month; this.day = day; this.year = year; }//Date2TextConverter
  • 3. //--------------------------------------- // operations //--------------------------------------- public String month2text() { switch( month ) { case 1: return "Jan"; case 2: return "Feb"; case 3: return "Mar"; case 4: return"April"; case 5: return"May"; case 6: return"June"; case 7: return"July"; case 8: return"Aug"; case 9: return"Sep"; case 10: return"Oct"; case 11: return"Nov"; case 12: return"Dec"; //... default: return "Invalid Month"; } }//month2text public String day2text() { //return Integer.toString( day ); return number2words (day); }//day2text public String year2text() { int century = year / 100; int yearInCentury = year % 100;
  • 4. String centuryText = number2words( century ); String yearText = number2words( yearInCentury ); if ( yearInCentury < 10 ) { return centuryText + " zero " + yearText; } else { return centuryText + " " + yearText; } }//year2text private String number2words( int number ) { // convert to text a number 0 through 99 if ( number < 20 ) { // 0, 1, 2, 3, ..., 19 return zero2nineteen[ number ]; } else if ( number % 10 == 0 ) { // 20, 30, 40, ... 90 return decades[ number / 10 - 2 ]; } else { // 21, 22, 23, 24, ... 29, 31, 32, ..., 99 return decades[ number / 10 - 2 ] + " " + zero2nineteen[ number % 10 ]; } } //number2words //--------------------------------------- // static vocabulary //--------------------------------------- private static final String[] zero2nineteen = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fouteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private static final String[] decades = { "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
  • 5. }; }//class Date2TextConverter import java.util.Scanner; public class Validator { public static Scanner sc = new Scanner( System.in ); public static String getString(Scanner sc, String prompt) { String s = null; do { System.out.print(prompt); s = sc.nextLine(); // read user entry if (s.equals("")) { System.out.println("String cannot be left blank!"); } } while (s.equals("")); return s; } public static int getInt(Scanner sc, String prompt) { int i = 0; boolean isValid = false; while (isValid == false) { System.out.print(prompt); if (sc.hasNextInt()) { i = sc.nextInt(); isValid = true; } else {
  • 6. System.out.println("Error! Invalid integer value. Try again."); } sc.nextLine(); // discard any other data entered on the line } return i; } public static int getInt(Scanner sc, String prompt, int min, int max) { int i = 0; boolean isValid = false; while (isValid == false) { i = getInt(sc, prompt); if (i <= min) System.out.println( "Error! Number must be greater than " + min + "."); else if (i >= max) System.out.println( "Error! Number must be less than " + max + "."); else isValid = true; } return i; } public static double getDouble(Scanner sc, String prompt) { double d = 0; boolean isValid = false; while (isValid == false) { System.out.print(prompt); if (sc.hasNextDouble()) { d = sc.nextDouble(); isValid = true;
  • 7. } else { System.out.println("Error! Invalid decimal value. Try again."); } sc.nextLine(); // discard any other data entered on the line } return d; } public static double getDouble(Scanner sc, String prompt, double min, double max) { double d = 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; } }