arrays in a program
How can a program that uses arrays be changed into a class that can be used by other programs?
for example this program:
import java.util.Scanner;//working perfectly
publicclass AmountToText//Not taking credit for this
{
publicstaticvoid main(String... args)
{
Scanner keyboard =new Scanner(System.in);
System.out.print("enter whole amount ONLY ");
//AmountofCheck sn = new Amou
int[] amount =newint [1];//can hold 1 elements p. 451
amount[0] = keyboard.nextInt();//in the position 0
for (int n : amount)//was int
{
System.out.printf("%n%,d%n", n);
System.out.printf("%s%n", AmountToText(n));
}
}//ends main
staticfinal String[] units ={"","one","two","three","four",
"five","six","seven","eight","nine"};
staticfinal String[] teens ={"ten","eleven","twelve","thirteen",
"fourteen","fifteen","sixteen",
"seventeen","eighteen","nineteen"};
staticfinal String[] tens ={"twenty","thirty","forty","fifty",
"sixty","seventy","eighty","ninety"};
staticfinal String[] mil ={"","thousand"};
publicstatic String AmountToText(int num)// numToWords=NumberToWordsMT
{
if (num == 0)
{
return"cero";
}
StringBuilder sb =new StringBuilder();//var-length array has sequence of characters*concanates Good
/*if (num < 0)
{
sb.append("Negative");
}*/
String numStr = String.valueOf(num).replaceFirst("^-","");//replaces- w/nothing
String[] parts = numStr.split("(?=(?:\\d\\d\\d)++$)");//split them in parts with 3 digits
int mag = parts.length - 1;
for (int i = 0; i <= mag; i++)
{
if (parsePart(parts[i], sb) && mag > 0 && i < 6)//6=mag
{
sb.append(" ").append(mil[mag - i]).append(",");
}
}
return sb.toString();
}
/*************************************************/
staticboolean parsePart(String str, StringBuilder sb)
{
boolean notZeroes =false;
int pos = 0;// pos=index
char ch = (char)0;
if (str.length() == 3 && (ch = str.charAt(pos++)) !='0')
{//if it has 3 positions & is diff than 0
ExtraSpace(sb);//invoke units and append hundred
sb.append(units[ch -'0']).append(" hundred");//position 0=hundred
notZeroes =true;
}
if (str.length() > 1 && (ch = str.charAt(pos++)) !='0')//>1&diff than 0
{
ExtraSpace(sb);
notZeroes =true;
if (ch =='1')//if position 1 has a 1
{
sb.append(teens[str.charAt(pos)]);//invoke teeens
return notZeroes;
}
sb.append(tens[ch -'2']);//otherwise invoke tens
}
if (str.length() > 0 && (ch = str.charAt(pos)) !='0')
{
ExtraSpace(sb);//if it is in position 0
sb.append(units[ch -'0']);//invoke units array
notZeroes =true;
}
return notZeroes;
}
/*************************************************/
staticvoid ExtraSpace(StringBuilder sb)
{
if (sb.length() > 0)
{
sb.append(" ");
}
}
}//ends the begining
[7916 byte] By [
Patmea] at [2007-11-27 10:52:03]

Changed how? Please try to be clearer.
thank you for your prompt reply
this program can be run by itself because it has the "main"
How can this be changed to a class that can be used by other programs?
meaning after I removed the line 6:
public static void main(String... args)
What other changes do I have to do to this program so that another program such as the following could call/invoke it?
import java.util.Scanner;
public class AmountofCheckTester//SerialNumberTester
{
public static void main(String[] args)
{
//String dollar = "123.89"; // serial1-dollar
Scanner keyboard = new Scanner(System.in);
String dollar = "";
System.out.print("Enter DOLLAR amount (numbers only) $");
// Get a customer number from the user.
dollar = keyboard.nextLine();//customer=Amount=dollar
//Validate dollar
AmountofCheck sn = new AmountofCheck(dollar);
if (sn.isValid())
{
System.out.print(sn.getFirst() );
System.out.println(" and " + sn.getSecond()+"/100");
}
else
System.out.println(dollar + " is invalid.");
}
}
Patmea at 2007-7-29 11:35:08 >

It can be used by other programs whether it has a main or not
Really,
My teacher didn't mention that...
so how can I call it from the program called "AmountofCheck.java"
and give it the "amount" located in the variable sn.getFirst()
Patmea at 2007-7-29 11:35:08 >

> Really,
> My teacher didn't mention that...
> so how can I call it from the program called
> "AmountofCheck.java"
> and give it the "amount" located in the variable
> sn.getFirst()
the main method can be called like any other static method.
> > Really,
> > My teacher didn't mention that...
> > so how can I call it from the program called
> > "AmountofCheck.java"
> > and give it the "amount" located in the variable
> > sn.getFirst()
>
> the main method can be called like any other static
> method.
Not that that's necessarily the way to get your class to work with other classes, of course.....
import java.util.Scanner;
public class AmountofCheckTester//SerialNumberTester
{
public static void main(String[] args)
{
//String dollar = "123.89"; // serial1-dollar
Scanner keyboard = new Scanner(System.in);
String dollar = "";
System.out.print("Enter DOLLAR amount (numbers only) $");
// Get a customer number from the user.
dollar = keyboard.nextLine();//customer=Amount=dollar
//Validate dollar
AmountofCheck sn = new AmountofCheck(dollar);
if (sn.isValid())
{
System.out.print(sn.getFirst() );
// WHAT SHOULD I TYPE HERE?
System.out.println(" and " + sn.getSecond()+"/100");
}
else
System.out.println(dollar + " is invalid.");
}
}
Patmea at 2007-7-29 11:35:08 >

Move all the code out of that main method, into another method. Don't make that method static. Then have your main method here create a new instance of the class, and invoke this shiny new method
Bingo. Although from looking at it, the method is too busy. But worry about that later!
The previous program "AmountofCheckTester.java" test the following program:
but how can I call a program like the one called "AmountToText.java" that I posted above?
import java.util.StringTokenizer;
public class AmountofCheck//
{
private String first;// First group of characters
private String second; // Second group of characters
private boolean valid; // Flag indicating validity
//*******************************************************
// The following constructor accepts a number as
// its String argument. The argument is broken into
// 2 groups and each group is validated.
//*******************************************************
public AmountofCheck(String sn)
{
// Create a StringTokenizer and initialize
// it with a trimmed copy of sn.
StringTokenizer st =
new StringTokenizer(sn.trim(), ".");
// Tokenize and validate.
if (st.countTokens() != 2)//This is the number of tokens
valid = false;
else
{
first = st.nextToken();//1st part of amount
second = st.nextToken(); //2nd part of amount
validate(); //invoking meth below
}
}
//****************************************************
// The following method returns the valid field.*
//****************************************************
public boolean isValid()
{
return valid;
}
//****************************************************
// The following method sets the valid field to true *
// if the serial number is valid. Otherwise it sets *
// valid to false.*
//****************************************************
private void validate()//private
{
if (isFirstGroupValid() && isSecondGroupValid())
valid = true;
else
valid = false;
}
//****************************************************
// The following method validates the first group of *
// characters. If the group is valid, it returns*
// true. Otherwise it returns false.*
//****************************************************
private boolean isFirstGroupValid()
{
boolean groupGood = true; // Flag
int i = 0; // Loop control variable
// Check the length of the 1st group.
if (first.length() >= 4)//was !=5
groupGood = false;
// See if each character is a Digit.
while (groupGood && i < first.length())
{
if (!Character.isDigit(first.charAt(i)))
groupGood = false;
i++;
}
return groupGood;
}
//****************************************************
// The following method validates the second group*
// of characters. If the group is valid, it returns *
// true. Otherwise it returns false.*
//****************************************************
private boolean isSecondGroupValid()
{
boolean groupGood = true; // Flag
int i = 0; // Loop control variable
// Check the length of the group2.
if (second.length() != 2)
groupGood = false;
// See if each character is a digit.
while (groupGood && i < second.length())
{
if (!Character.isDigit(second.charAt(i)))
groupGood = false;
i++;
}
return groupGood;
}
public String getFirst()
{
return first;
}
public String getSecond()
{
return second;
}
}
Patmea at 2007-7-29 11:35:08 >

I tried this but it give me an error?
What am I missing?
import java.util.Scanner;
public class AmountToTextTester
{
public static void main(String... args)//(String... args)
{
Scanner keyboard = new Scanner(System.in);
int[] amount = new int[1]; // { 1, 23, 456, 7890, -1234567890 };
//validate amount
System.out.print("enter WHOLE amount");
amount[0] = keyboard.nextInt(); //in the position 0
//AmountToText sn = new AmountToText(amount);
for (int n : amount)
{
System.out.printf("%n%,d%n", n);
System.out.printf("%s%n", AmountToTextTester(n));//Added Tester
}
}//ends main
}//ends tester
Patmea at 2007-7-29 11:35:08 >

public class SomeOtherClass {
public static void main(String[] args) {
AmountToText amountToText = new AmountToText();
amountToText.invokeWhateverMethod();
}
}
Your teacher should be telling you this. If you're being formally taught, you shouldn't have to find this out from the forums. I'm criticising your teacher, not you, by the way!
My Teacher... she means well, but...
anyways...
this is what I did and this is the error I am getting,
import java.util.Scanner;
public class AmountToTextTester
{
public static void main(String[] args)//(String... args)
{
AmountToText amountToText = new AmountToText();
amountToText.parsePart();
}//ends main
}//ends tester
AmountToTextTester.java:7: parsePart(java.lang.String,java.lang.StringBuilder) in AmountToText cannot be applied to ()
amountToText.parsePart();
Is AmountToText.java suppose to look like this? Or did I do it all wrong?
import java.util.Scanner;//working perfectly
public class AmountToText//Not taking credit for this
{
/*public static void main(String... args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("enter whole amount ONLY ");
//AmountofCheck sn = new Amou
int[] amount = new int [1]; //can hold 1 elements p. 451
amount[0] = keyboard.nextInt(); //in the position 0
for (int n : amount)//was int
{
System.out.printf("%n%,d%n", n);
System.out.printf("%s%n", AmountToText(n));
}
}//ends main
*/
static final String[] units = { "", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine" };
static final String[] teens = { "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen" };
static final String[] tens = { "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety" };
static final String[] mil = { "", "thousand" };
public static String AmountToText(int num)// numToWords=NumberToWordsMT
{
if (num == 0)
{
return "cero";
}
StringBuilder sb = new StringBuilder();//var-length array has sequence of characters*concanates Good
/*if (num < 0)
{
sb.append("Negative");
}*/
String numStr = String.valueOf(num).replaceFirst("^-", "");//replaces- w/nothing
String[] parts = numStr.split("(?=(?:\\d\\d\\d)++$)");//split them in parts with 3 digits
int mag = parts.length - 1;
for (int i = 0; i <= mag; i++)
{
if (parsePart(parts[i], sb) && mag > 0 && i < 6)//6=mag
{
sb.append(" ").append(mil[mag - i]).append(",");
}
}
return sb.toString();
}
/*************************************************/
static boolean parsePart(String str, StringBuilder sb)
{
boolean notZeroes = false;
int pos = 0; // pos=index
char ch = (char)0;
if (str.length() == 3 && (ch = str.charAt(pos++)) != '0')
{ //if it has 3 positions & is diff than 0
ExtraSpace(sb);//invoke units and append hundred
sb.append(units[ch - '0']).append(" hundred");//position 0=hundred
notZeroes = true;
}
if (str.length() > 1 && (ch = str.charAt(pos++)) != '0')//>1&diff than 0
{
ExtraSpace(sb);
notZeroes = true;
if (ch == '1')//if position 1 has a 1
{
sb.append(teens[str.charAt(pos)]);//invoke teeens
return notZeroes;
}
sb.append(tens[ch - '2']);//otherwise invoke tens
}
if (str.length() > 0 && (ch = str.charAt(pos)) != '0')
{
ExtraSpace(sb);//if it is in position 0
sb.append(units[ch - '0']);//invoke units array
notZeroes = true;
}
return notZeroes;
}
/*************************************************/
static void ExtraSpace(StringBuilder sb)
{
if (sb.length() > 0)
{
sb.append(" ");
}
}
}//ends the begining
Patmea at 2007-7-29 11:35:08 >

Well, your parsePart method takes 2 arguments, you have to supply them. I question the wisdom of passing it a StringBuilder, though. If it needs a StringBuilder to do it's work, it can get one itself. Maybe it should return a string, if that's what you want out of it. There's a fair amount wrong with the code, to be honest, but it would take some time to go through it, and your best bet - and quickest option - is to throw it all out and start again. No, really. Write down what you want it to do, in very simple terms. Don't be tempted to sum it all up in one convoluted sentence, be simplistic. You should then have a good start of a design
oh, no!!
Don't tell me that.
I wouldn't be able to finish it in time to turn it in.
the program works fine as long as it is not being called by another method. it does this:
enter whole amount ONLY 678
678
six hundred seventy eight
The problem is trying to call it from other program
Patmea at 2007-7-29 11:35:08 >

You are probably going to laugh at me but It took me all week to get this other program ( I call it the father because it calls 3 classes) running. The only part that I am missing is:
to display the amount into text...
Patmea at 2007-7-29 11:35:13 >

> oh, no!!
> Don't tell me that.
> I wouldn't be able to finish it in time to turn it
> in.
Trust me, you will be quicker throwing it away. We've all been exactly here, in one way or another
> the program works fine as long as it is not being
> called by another method. it does this:
>
>
> > enter whole amount ONLY 678
>
> 678
> six hundred seventy eight
>
>
> The problem is trying to call it from other program
//**********************************************************
// This program tests a customer amount to determine*
// whether it is in the proper format. *
//**********************************************************
import java.util.Scanner;
import java.text.DecimalFormat;
public class CustomerNumber
{
static final String[] units = { "", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine" };
static final String[] teens = { "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen" };
static final String[] tens = { "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety" };
static final String[] mil = { "", "thousand" };
public static void main(String[] args)// = MetricDemo
{
String name,// To hold FIRST name
customerName,// to hold FIRST name
customerL,// to hold LAST name
dollar="",// to hold amount in check
customerDollar, // to hold ref to class' meth dollar
spelled; // to hold spelled amount
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
CurrentDate now = new CurrentDate();
System.out.println(now.getDate());
// Create a DecimalFormat object for output formatting
DecimalFormat fmt = new DecimalFormat("###.##");
System.out.println("Enter FIRST name only no numbers ");
// Get a customer name.
name = keyboard.nextLine();
// Determine whether it is valid.
/********************/
if (Customer.isValid(name))// invoking meth ot class Customer** name=first
{
System.out.println("Thank you for FIRST name "+ name);
}
else
{
System.out.println("That is the wrong format ");
System.out.println("Follow example: Abcdefg");
System.out.println("Enter FIRST name no numbers "); //added this
// Get a customer name.
name = keyboard.nextLine();
Customer c1 = new Customer(); // to hold 1st name
Customer c2 = new Customer(); // to hold Last name
Customer c3 = new Customer(); // to hold dollar Amt
Customer c4 = new Customer(); // to hold spelled out Amt
if (Customer.isValid(name))// invoking meth below** customer=first
{
System.out.println("Thank you for FIRST name "+ name);
}
}
/*****************/
//customerName=Customer.customerFirstName(customer);//CHECK THIS
//System.out.println("Your 1st name is " +customer);
/*****************************************************/
System.out.println("Enter LAST name only no numbers ");
// Get LAST name.
customerL = keyboard.nextLine();//Added L
// Determine whether it is valid.
if (Customer.isValidLastN(customerL))// invoking meth below
{
System.out.println("Thank you for LAST name ");
}
else
{
System.out.println("That is wrong ");
System.out.println("Follow this example: Abcdefg");
System.out.println("Enter LAST name only "); //added this
// Get LAST name.
customerL = keyboard.nextLine();//Added L
if (Customer.isValidLastN(customerL))// invoking meth below** customer=first
{
System.out.println("Thank you for LAST name ");
}
}
/*****************/
//customerName=Customer.isValidLastN(customer);//CHECK THIS
//***********************************************************
System.out.print("Enter DOLLAR amount (numbers only, NO spaces) $");
// Get a customer number from the user.
dollar = keyboard.nextLine();//customer=Amount=dollar
// Determine whether it is valid.
//Validate dollar
AmountofCheck sn = new AmountofCheck(dollar);
if(sn.isValid())//invoking class to check length & digits
{
System.out.println(sn.getFirst() ); //dollar + " is VALID");
/**********************************************/
/* System.out.print("enter whole amount ONLY ");
int[] amount = new int [1]; //can hold 1 elements p. 451
//int[] amount = new int[] { 1, 23, 456, 7890, -123456 };// , -1234567890
amount[0] = keyboard.nextInt(); //in the position 0
for (int n : amount)//was int
{
System.out.printf("%n%,d%n", n);
System.out.printf("%s%n", AmountToText(n));
}
*/
/******************/
/*static final String[] units = { "", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine" };
static final String[] teens = { "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen" };
static final String[] tens = { "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety" };
static final String[] mil = { "", "thousand" };
*/
/******************************************************/
System.out.println(" and " + sn.getSecond() + "/100");
}// ends if
else
{
//System.out.println(dollar + " is INVALID");
System.out.println("wrong format ");
System.out.println("Follow this example: 99999");
System.out.print("Enter numbers only $"); //added this
// Get a customer number from the user.
dollar = keyboard.nextLine();//customer=Amount=dollar
if (Customer.isValidDollar(dollar))// invoking Class.method customer=first
{
System.out.println("Thank you for typing Amount ");
//AmountToText.java;
}
}//ends else
/***********************************************************/
/***************************************************************/
System.out.println("\r");
CurrentDate today = new CurrentDate();
System.out.println("\t\t\t\t\t\t\t\t\t\t" + today.getDate());
System.out.println("\t" + name + " " + customerL + "\t\t$" + " and "+sn.getSecond()
+ "/100\r\r");
System.out.println("");
} // this closes main
/**********************************************************************/
/*public String toString()
{
CurrentDate now = new CurrentDate();
System.out.println(now.getDate());
// Create a string representing the object.
String str =
"Last Name: " + "variable's name" //?
+ "\nFirst Name: " + "customerL"
+ "\nOffice Number: " + "customerD";
// Return the string.
return str;
}*/
} /* this closes the begining */
Patmea at 2007-7-29 11:35:13 >

> You are probably going to laugh at me but It took me
> all week to get this other program ( I call it the
> father because it calls 3 classes) running. The only
> part that I am missing is:
> to display the amount into text...
Why would I laugh at you? Nobody was born with an innate knowledge of Java. We've all been learners. It might have taken you all week to do that, but it won't take you all week to do it again. Making mistakes is an unavoidable fact of coding. You can read a billion books and digest enough knowledge to avoid most mistakes. But just making the mistakes and learning from them is a lot quicker and more beneficial
You have 3 classes? Good. You've learnt not to cram everything into one class. You'll be fine, just write some basic requirements down in simple terms, and go from there. You've shown you understand enough to do this, you just need a bit of confidenec
my problem is the arrays I don't know how to make an array command that would receive the data from (line 20)
sn.getFirst()
//****************************************************
// This program demonstrates the AmountofCheck class. *
//****************************************************
import java.util.Scanner;
public class AmountofCheckTester//SerialNumberTester
{
public static void main(String[] args)
{
//String dollar = "123.89"; // serial1-dollar
Scanner keyboard = new Scanner(System.in);
String dollar = "";
System.out.print("Enter DOLLAR amount (numbers only) $");
// Get a customer number from the user.
dollar = keyboard.nextLine();//customer=Amount=dollar
//Validate dollar
AmountofCheck sn = new AmountofCheck(dollar);
if (sn.isValid())
{
System.out.print(sn.getFirst() );
// This is what I don't know *****
System.out.println(" and " + sn.getSecond()+"/100");
}
else
System.out.println(dollar + " is invalid.");
}
}
Patmea at 2007-7-29 11:35:13 >

What's an "array command"? Do you mean you want to write a class that you give data to, and it puts it in an array?
I didn't look at later code you posted, just the first. The method AmountToText() just takes in an int, no array. So you can call it as such:public class Test {
public static void main (String[] ignoredVariable) {
int arg = 5; // TODO: replace this.
System.out.println( AmountToText.AmountToText(arg) );
}
}
Oh wait, it looks like you want to completely re-write the class, eh? You want the method to return an array with two elements, one for the dollars and the other for the cents?
What are you trying to achieve? They enter the "$xx.xx" value, you parse it into an int, pass it to a method that returns two ints, then print it out again. So you'll just end up with what you started, but did a lot of work for nothing apparently.
I think it would be simpler if you learned about the following:
double
float
Money
array accessing, such as I think you want to return: a[0] + "." + a[1]
I started all over again
but again I am stuck and don't know how to fix it
I do know that double can take xx.xx
int xx no cents
float xx.xx
here is my new sucky attempt. I'm sooo frustrated this assignment is due today and I got nothing but ...
Patmea at 2007-7-29 11:35:13 >

//***************************************************
// This class's sequentialSearch method searches an *
// int array for a specified value.*
//***************************************************
public class SearchArray
{
//****************************************************
// The sequentialSearch method searches array for*
// value. If value is found in array, the element's *
// subscript is returned. Otherwise, -1 is returned. *
//****************************************************
public static int sequentialSearch(String[] array, String value)
{
int index,// Loop control variable
element;// Element the value is found at
boolean found; // Flag indicating search results
// Element 0 is the starting point of the search.
index = 0;
// Store the default values for element and found.
element = -1;
found = false;
// Search the array.
while (!found && index < array.length)
{
// Does this element have the value?
if (array[index] == value)
{
found = true;// Indicate the value is found.
element = index; // Save the subscript of the value.
}
// Increment index so we can look at the next element.
index++;
}
// Return either the subscript of the value (if found)
// or -1 to indicate the value was not foumd.
return element;
}
}
//****************************************************
// This program demonstrates the SearchArray class's *
// sequentialSearch method. *
//****************************************************
import java.util.Scanner;
public class TestSearch
{
public static void main(String[] args)
{
int results; // Results of the search POSITION
// Create an array of values.
final String[] units = { "", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine" };// Search the array for the value 100.
final String[] teens = { "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen" };
final String[] tens = { "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety" };
final String[] mil = { "", "thousand" };
Scanner keyboard = new Scanner(System.in);
System.out.print("enter whole amount ONLY ");
int[] amount = new int [1]; //can hold 1 elements p. 451
amount[0] = keyboard.nextInt(); //in the position 0
results = SearchArray.sequentialSearch(units, amount);
// Determine whether 100 was found in the array.
if (results == -1)
{
// -1 indicates the value was not found.
System.out.println("Value not found ");
}
else
{
// results holds the subscript of the value 100.
System.out.println("You entered " + amount
+ "in position " + (results - 1));
}
}
}
This is the error but I don't know how to fix it:
TestSearch.java:26: sequentialSearch(java.lang.String[],java.lang.String) in SearchArray cannot be applied to (java.lang.String[],int[])
results = SearchArray.sequentialSearch(units, amount);
Patmea at 2007-7-29 11:35:13 >

The error message is telling you exactly what is wrong. You havea sequentialSearch method that takes two parameters:
1) an array of String to be searched
2) a single String that may or may not be within the String array above.
You pass it something different:
1) an array of String.That part's ok. And,...
2) an array of int. This doesn't make sense. The array admittedly only has one element, but your routine doesn't know that. Also, even if you just pass that one element by passing amount[0], even though it is no longer an array variable, it's still an int, not a String.
Until you fix this, your prog is doomed to fail.
Pete you are wonderful,
Thank you very much for your help
Here is the check writer
//**********************************************************
// This program tests a customer amount to determine*
// whether it is in the proper format. *
//**********************************************************
import java.util.Scanner;
import java.text.DecimalFormat;
public class CustomerNumber
{
static final String[] units = { "", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine" };
static final String[] teens = { "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen" };
static final String[] tens = { "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety" };
static final String[] mil = { "", "thousand" };
public static void main(String[] args)// = MetricDemo
{
String name,// To hold FIRST name
customerName,// to hold FIRST name
customerL,// to hold LAST name
dollar="",// to hold amount in check
customerDollar, // to hold ref to class' meth dollar
spelled; // to hold spelled amount
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
CurrentDate now = new CurrentDate();
System.out.println(now.getDate());
// Create a DecimalFormat object for output formatting
DecimalFormat fmt = new DecimalFormat("###.##");
System.out.println("Enter FIRST name only no numbers ");
// Get a customer name.
name = keyboard.nextLine();
// Determine whether it is valid.
/********************/
if (Customer.isValid(name))// invoking meth ot class Customer** name=first
{
System.out.println("Thank you for FIRST name "+ name);
}
else
{
System.out.println("That is the wrong format ");
System.out.println("Follow example: Abcdefg");
System.out.println("Enter FIRST name no numbers "); //added this
// Get a customer name.
name = keyboard.nextLine();
Customer c1 = new Customer(); // to hold 1st name
Customer c2 = new Customer(); // to hold Last name
Customer c3 = new Customer(); // to hold dollar Amt
Customer c4 = new Customer(); // to hold spelled out Amt
if (Customer.isValid(name))// invoking meth below** customer=first
{
System.out.println("Thank you for FIRST name "+ name);
}
}
/*****************/
//customerName=Customer.customerFirstName(customer);//CHECK THIS
//System.out.println("Your 1st name is " +customer);
/*****************************************************/
System.out.println("Enter LAST name only no numbers ");
// Get LAST name.
customerL = keyboard.nextLine();//Added L
// Determine whether it is valid.
if (Customer.isValidLastN(customerL))// invoking meth below
{
System.out.println("Thank you for LAST name ");
}
else
{
System.out.println("That is wrong ");
System.out.println("Follow this example: Abcdefg");
System.out.println("Enter LAST name only "); //added this
// Get LAST name.
customerL = keyboard.nextLine();//Added L
if (Customer.isValidLastN(customerL))// invoking meth below** customer=first
{
System.out.println("Thank you for LAST name ");
}
}
/*****************/
//customerName=Customer.isValidLastN(customer);//CHECK THIS
//***********************************************************
System.out.print("Enter DOLLAR amount (numbers only, NO spaces) $");
// Get a customer number from the user.
dollar = keyboard.nextLine();//customer=Amount=dollar
// Determine whether it is valid.
//Validate dollar
AmountofCheck sn = new AmountofCheck(dollar);
if(sn.isValid())//invoking class to check length & digits
{
//System.out.print (sn.getFirst() ); //dollar + " is VALID");
System.out.println(sn.getFirst()+ " and " + sn.getSecond() + "/100");
}
else
{
//System.out.println(dollar + " is INVALID");
System.out.println("wrong format ");
System.out.println("Follow this example: 99999");
System.out.print("Enter numbers only $"); //added this
// Get a customer number from the user.
dollar = keyboard.nextLine();//customer=Amount=dollar
if (Customer.isValidDollar(dollar))// invoking Class.method customer=first
{
System.out.println("Thank you for typing Amount ");
}
}
System.out.println("\r");
CurrentDate today = new CurrentDate();
System.out.println("\t\t\t\t\t\t\t\t\t\t" + today.getDate());
System.out.println("\t" + name + " " + customerL + "\t\t" + AmountToText.AmountToText(Integer.parseInt(sn.getFirst()))
+" and "+sn.getSecond() + "/100\r\r");
System.out.println("");
} // this closes main
/**********************************************************************/
/*public String toString()
{
CurrentDate now = new CurrentDate();
System.out.println(now.getDate());
// Create a string representing the object.
String str =
"Last Name: " + "variable's name" //?
+ "\nFirst Name: " + "customerL"
+ "\nOffice Number: " + "customerD";
// Return the string.
return str;
}*/
} /* this closes the begining */
//************************************************************
// The AmountCheck class takes a number in
// The AmountCheck has 2 groups
// of characters, separated by period. The class extracts
// the 2 groups of characters and validates them.
//************************************************************
import java.util.StringTokenizer; //COPY FROM HERE
public class AmountofCheck//
{
private String first;// First group of characters
private String second; // Second group of characters
private boolean valid; // Flag indicating validity
//*******************************************************
// The following constructor accepts a number as
// its String argument. The argument is broken into
// 2 groups and each group is validated.
//*******************************************************
public AmountofCheck(String sn)
{
// Create a StringTokenizer and initialize
// it with a trimmed copy of sn.
StringTokenizer st =
new StringTokenizer(sn.trim(), ".");
// Tokenize and validate.
if (st.countTokens() != 2)//This is the number of tokens
valid = false;
else
{
first = st.nextToken();//1st part of amount
second = st.nextToken(); //2nd part of amount
validate(); //invoking meth below
}
}
//****************************************************
// The following method returns the valid field.*
//****************************************************
public boolean isValid()
{
return valid;
}
//****************************************************
// The following method sets the valid field to true *
// if the serial number is valid. Otherwise it sets *
// valid to false.*
//****************************************************
private void validate()//private
{
if (isFirstGroupValid() && isSecondGroupValid())
valid = true;
else
valid = false;
}
//****************************************************
// The following method validates the first group of *
// characters. If the group is valid, it returns*
// true. Otherwise it returns false.*
//****************************************************
private boolean isFirstGroupValid()
{
boolean groupGood = true; // Flag
int i = 0; // Loop control variable
// Check the length of the 1st group.
if (first.length() >= 4)//was !=5
groupGood = false;
// See if each character is a Digit.
while (groupGood && i < first.length())
{
if (!Character.isDigit(first.charAt(i)))
groupGood = false;
i++;
}
return groupGood;
}
//****************************************************
// The following method validates the second group*
// of characters. If the group is valid, it returns *
// true. Otherwise it returns false.*
//****************************************************
private boolean isSecondGroupValid()
{
boolean groupGood = true; // Flag
int i = 0; // Loop control variable
// Check the length of the group2.
if (second.length() != 2)
groupGood = false;
// See if each character is a digit.
while (groupGood && i < second.length())
{
if (!Character.isDigit(second.charAt(i)))
groupGood = false;
i++;
}
return groupGood;
}
public String getFirst()
{
return first;
}
public String getSecond()
{
return second;
}
}
import java.util.Scanner;//working perfectly
public class AmountToText
{
public static void main(String... args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("enter whole amount ONLY ");
//AmountofCheck sn = new Amou
int[] amount = new int [1]; //can hold 1 elements p. 451
amount[0] = keyboard.nextInt(); //in the position 0
for (int n : amount)//was int
{
System.out.printf("%n%,d%n", n);
System.out.printf("%s%n", AmountToText(n));
}
}//ends main
static final String[] units = { "", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine" };
static final String[] teens = { "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen" };
static final String[] tens = { "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety" };
static final String[] mil = { "", "thousand" };
public static String AmountToText(int num)// numToWords=NumberToWordsMT
{
if (num == 0)
{
return "cero";
}
StringBuilder sb = new StringBuilder();//var-length array has sequence of characters*concanates Good
/*if (num < 0)
{
sb.append("Negative");
}*/
String numStr = String.valueOf(num).replaceFirst("^-", "");//replaces- w/nothing
String[] parts = numStr.split("(?=(?:\\d\\d\\d)++$)");//split them in parts with 3 digits
int mag = parts.length - 1;
for (int i = 0; i <= mag; i++)
{
if (parsePart(parts[i], sb) && mag > 0 && i < 6)//6=mag
{
sb.append(" ").append(mil[mag - i]).append(",");
}
}
return sb.toString();
}
/*************************************************/
static boolean parsePart(String str, StringBuilder sb)
{
boolean notZeroes = false;
int pos = 0; // pos=index
char ch = (char)0;
if (str.length() == 3 && (ch = str.charAt(pos++)) != '0')
{ //if it has 3 positions & is diff than 0
ExtraSpace(sb);//invoke units and append hundred
sb.append(units[ch - '0']).append(" hundred");//position 0=hundred
notZeroes = true;
}
if (str.length() > 1 && (ch = str.charAt(pos++)) != '0')//>1&diff than 0
{
ExtraSpace(sb);
notZeroes = true;
if (ch == '1')//if position 1 has a 1
{
sb.append(teens[str.charAt(pos)]);//invoke teeens
return notZeroes;
}
sb.append(tens[ch - '2']);//otherwise invoke tens
}
if (str.length() > 0 && (ch = str.charAt(pos)) != '0')
{
ExtraSpace(sb);//if it is in position 0
sb.append(units[ch - '0']);//invoke units array
notZeroes = true;
}
return notZeroes;
}
/*************************************************/
static void ExtraSpace(StringBuilder sb)
{
if (sb.length() > 0)
{
sb.append(" ");
}
}
}//ends the begining
import java.text.*;
import java.util.*;
/**
Class CurrentDateTime. Contains a single
method that returns today's date
**/
public class CurrentDate
{
public String getDate()
{
String rv = " " ;
Date today = new Date ();
SimpleDateFormat adf_date = new SimpleDateFormat ("MMMM/d/y");
//SimpleDateFormat adf_time = new SimpleDateFormat ("h:mm a") ;
rv = adf_date.format (today);
return rv;
}
}
It is not perfect. I have to make a lot of changes to it still...
Thank you everybody for your help and suggestions
Patmea at 2007-7-29 11:35:13 >

