replaceFirst("^-", "") ?
I am learning about java and one of the programs has the following and I having been able to find information about their meaning or actions...
1.- replaceFirst("^-", ""); //what does ^- mean?
2.- split("(?:\\d\\d\\d)++$"); //what does this do? I know it has something to do with splitting the string ...
How can I modify this program so that it would accept a dollar amount from a user (between 0 and 999.99) and the program prints the text. Example:
user enters 123.34
the programs displays:
One hundred twenty three dollars and 34/100
Thank you for your help
public class NumberToWordsMT
{
public static void main(String... args)
{
int[] test = new int[] { 1, 23, 456, 7890, -1234567890 };// , -1234567890
for (int n : test)//was int
{
System.out.printf("%n%,d%n", n);
System.out.printf("%s%n", numToWords(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[] thousand = { "", "thousand", "million", "billion" };
public static String numToWords(int num)//was int
{
if (num == 0)
{
return "zero";
}
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, sb) && mag > 0 && i < mag)
{
sb.append(" ").append(thousand[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
[3539 byte] By [
Patmea] at [2007-11-27 10:38:23]

> I am learning about java and one of the programs has
> the following and I having been able to find
> information about their meaning or actions...
>
> 1.- replaceFirst("^-", ""); //what does ^- mean?
>
> 2.- split("(?:\\d\\d\\d)++$"); //what does this do?
> I know it has something to do with splitting the
> string ...
Those are regex patterns.
More info about those: http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html
> How can I modify this program so that it would accept
> a dollar amount from a user (between 0 and 999.99)
> and the program prints the text. Example:
> user enters 123.34
> the programs displays:
> One hundred twenty three dollars and 34/100
>
> Thank you for your help
By leaning Java.
It seems you found some code on the net which you yourself cannot adjust to your needs. Answering one question about it will only result in more questions. If you're really interested in learning Java, start with some basic tutorial:
http://java.sun.com/docs/books/tutorial/
You are more than welcome to ask a specific question here on the forum of course.
Good luck.
http://java.sun.com/docs/books/tutorial/extra/regex/index.html
http://www.regular-expressions.info/
> 1.- replaceFirst("^-", ""); //what does ^- mean?
^ means start of input.
- in that context is just a literal -
So if the string starts with '-', return a new string without the leading '-'
> 2.- split("(?:\\d\\d\\d)++$"); //what does this do?
I don't know exactly. It looks like it will just pull off any final groups of 3 digits from the end of the string.
> How can I modify this program so that it would accept
> a dollar amount from a user (between 0 and 999.99)
> and the program prints the text. Example:
> user enters 123.34
How do you think you'd do it? What problem are you having?
jverda at 2007-7-28 18:54:04 >

Thank you very much for ALL your prompt replies.
They are very helpful
jverd:
so far the program accepts whole numbers and replaces them as text. that is great. but I don't know how to make it accept numbers with decimals and save them into two different arrays so that array one will print the text for the whole amount and array two will contain the decimal portion of the amount and display 34/100
Thank you very much for your help
Patmea at 2007-7-28 18:54:05 >

Okay.
Post new code. A tiny program that does nothing more than turn, say, 12.34 into the form that you want. No user input, no other functionality, just hardcode the values you need.
Take your best shot, show your desired output, and indicate what's going wrong.
When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. (http://forum.java.sun.com/help.jspa?sec=formatting) It makes it much easier to read.
jverda at 2007-7-28 18:54:05 >

Here is the one that I started with but it doesn't display the amounts in text format. It does split them into groups...
[//****************************************************
// This program demonstrates the AmountofCheck class. *
//****************************************************
public class AmountofCheckTester//SerialNumberTester
{
public static void main(String[] args)
{
String dollar = "123.89"; // serial1-dollar
// Validate dollar.
AmountofCheck sn = new AmountofCheck(dollar);
if (sn.isValid())
System.out.println(dollar + " is valid.");
else
System.out.println(dollar + " is invalid.");
}
}/code]
//************************************************************
// 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()
{
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() != 3)//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;
}
}
[code]
Patmea at 2007-7-28 18:54:05 >

I'm lazy, and that's too much for me to read.
Get rid of the comments. They're simply repeating what your method names already tell us.
Get rid of the validation. Start with a hardcoded value that you know is valid. Once that works, then worry about validation.
jverda at 2007-7-28 18:54:05 >

thank you for your help jverd I really really need help
the following program displays 123 as text:
one hundred and twenty three.
How can I make the program into a class and call it from a different main class?
I tried this main class but it gives me an error
public class NumberToWordsTester
{
public static void main(String... args)
{
int[] test = new int[] { 1, 23, 456, 7890, -1234567890 };
numToWordsMT sn = new numToWordsMT(test);
for (int n : sn)//was test
{
System.out.printf("%n%,d%n", n);
System.out.printf("%s%n", numToWords(n));
numToWords?
}
}
}
public class NumberToWordsMT
{
/*public static void main(String... args)
{//This is what I want to remove so that this class can be called
// from a different main program
int[] test = new int[] { 1, 23, 456, 7890, -123456789 };
for (int n : test)//was int
{
System.out.printf("%n%,d%n", n);
System.out.printf("%s%n", numToWords(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[] thousand = { "", "thousand" };
public static String numToWords(int num)//was int
{
if (num == 0)
{
return "zero";
}
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("^-", "");
String[] parts = numStr.split("(?=(?:\\d\\d\\d)++$)");
int mag = parts.length - 1;
for (int i = 0; i <= mag; i++)
{
if (parsePart(parts[i], sb) && mag > 0 && i < 6)
{
sb.append(" ").append(thousand[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')
{
ExtraSpace(sb);
sb.append(units[ch - '0']).append(" hundred");
notZeroes = true;
}
if (str.length() > 1 && (ch = str.charAt(pos++)) != '0')
{
ExtraSpace(sb);
notZeroes = true;
if (ch == '1')
{
sb.append(teens[str.charAt(pos)]);
return notZeroes;
}
sb.append(tens[ch - '2']);
}
if (str.length() > 0 && (ch = str.charAt(pos)) != '0')
{
ExtraSpace(sb);
sb.append(units[ch - '0']);
notZeroes = true;
}
return notZeroes;
}
/*************************************************/
static void ExtraSpace(StringBuilder sb)
{
if (sb.length() > 0)
{
sb.append(" ");
}
}
}
Patmea at 2007-7-28 18:54:05 >

> I tried this main class but it gives me an error
Please paste in the exact, complete error message, as well as were it's occurring.
jverda at 2007-7-28 18:54:05 >

I am using jGrasp to run my programs
or should I say to "try" to run them because I can't even compile them :)
-jGRASP exec: javac -g D:\CIS150\week4\NumberToWordsTester.java
NumberToWordsTester.java:7: cannot find symbol
symbol : class numToWordsMT
location: class NumberToWordsTester
numToWordsMT sn = new numToWordsMT(test);
Patmea at 2007-7-28 18:54:05 >

It's telling you exactly what's wrong. There's no such class as numToWordsMT that it knows about.
jverda at 2007-7-28 18:54:05 >

I also tried calling the name of the class and it gives me an error also:
-jGRASP exec: javac -g D:\CIS150\week4\NumberToWordsTester.java
NumberToWordsTester.java:7: cannot find symbol
symbol : constructor NumberToWordsMT(int[])
location: class NumberToWordsMT
NumberToWordsMT sn = new NumberToWordsMT(test);
this is what my programs looks like:
public class NumberToWordsTester
{
public static void main(String... args)
{
int[] test = new int[] { 1, 23, 456, 7890, -1234567890 };
NumberToWordsMT sn = new NumberToWordsMT(test);
for (int n : sn)
{
System.out.printf("%n%,d%n", n);
System.out.printf("%s%n", NumberToWords(n));
}
}
}
Patmea at 2007-7-28 18:54:05 >

> I also tried calling the name of the class and it
> gives me an error also:
Once again, the error message is telling you exactly what's wrong.
You're calling a constructor that takes an array of int. There is no such constrctor.
Don't just take my word for it. Go back and read the error message carefully, so that you can see that it is saying exactly that.
jverda at 2007-7-28 18:54:05 >

Yes! you are soooo right.
How can I fix it? by adding a constructor that takes in [int]?
Patmea at 2007-7-28 18:54:05 >

> Yes! you are soooo right.
>
> How can I fix it? by adding a constructor that takes
> in [int]?
That's up to you.
Does it make sense for that class to take an int[] in it's c'tor? What will it do with it?
Or does it make more sense to do something different--like maybe constructing multiple instances of that class in turn, passing a single int from that array each time?
jverda at 2007-7-28 18:54:09 >

It will be much better to create instances of the class
that is what I tried to do in line 7 (main program)
obviously I did it wrong because I don't want to call a constructor
so how should I word it?
Patmea at 2007-7-28 18:54:09 >

> It will be much better to create instances of the
> class
That's what new does. You're currently creating one instance and giving it an array--or trying to, but you haven't written the class to accept an array at construcion time.
> that is what I tried to do in line 7 (main program)
> obviously I did it wrong because I don't want to call
> a constructor
What do you mean you don't want to call a constructor?
> so how should I word it?
Well, again: Does it make sense for your class to take an array of ints when it's instantiated? What will it do with them if it does? Or does it make sense for it to take something else? What will it do with that?
Decide what you want your class to do and what information it needs to do it, create constructors or methods that take that information as arguments, and then invoke those constructors or methods passing the appropriate values.
jverda at 2007-7-28 18:54:09 >

> Does it make sense for your class to
> take an array of ints when it's instantiated?
Yes, because the user will type a number (digits) between 0 and 999.99. this is going to be store in the main program and pass (I don't know how) to the class, so tha the class can turn the digits into text
>What will it do with them if it does?
the class is to "spell" the amount
but the main program "NumberToWordsTester" has to call the class "NumberToWords" to execute it
in other words:
say the user enters 123.45. It is the job of the program to convert the input into the following:
one hundred twenty three and 45/100
So, I will need to :
Split up user input into individual digits
Set up an array with the strings one, two, three.. and so on. (Which I did in the class)
Use the digits to extract strings from the array.
But my book doesn't specify how to create constructors (same name) or methods for the type "..." special array
Thank you for your patience I'm just starting to learn java
Patmea at 2007-7-28 18:54:09 >

public NumberToWordsMT(int[] numbers) {
// now we do something with numbers.
// Most likely set a member variable, like so
this.numbers = numbers;
}
When I said "what will it do with it?" I meant "What will the constructor do with it?" The purpose of a constructor is to put an object into a valid state so that it can be used. Does your object require an array of ints at its creation time in order to be used later? Or are you just going to pass the ints in one by one when you want to convert them/
http://java.sun.com/docs/books/tutorial/java/javaOO/methods.html
http://java.sun.com/docs/books/tutorial/java/javaOO/constructors.html
http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html
http://java.sun.com/docs/books/tutorial/java/javaOO/objectcreation.html
jverda at 2007-7-28 18:54:10 >

By the way, 123.45 and 999.99 are not ints.
jverda at 2007-7-28 18:54:10 >

Does it matter that they are not int?
because they are going to be stored in a String array
so is it wrong to use int?
I am also using int to specify the position of the elements of the array
I need the arrays to be String because I need to use lenght() in order to decide which method to use: units(), teens(), tenths() or thousands()
Patmea at 2007-7-28 18:54:10 >

> Does it matter that they are not int?
> because they are going to be stored in a String
> array
> so is it wrong to use int?
I thought the int[] was going to hold the numbers like 123.45. If it's for something else (something that is actually a bunch of ints) then ignore me, as I don't know what I'm talking about. :-)
jverda at 2007-7-28 18:54:10 >

please don't say that. You have been very helpful. I am the one who doesn't know what I am doing! But I want to learn and I apreciate your help
Patmea at 2007-7-28 18:54:10 >

This is my main program and from here I called the classes for the date and customer
//**********************************************************
// This program tests a customer number to determine*
// whether it is in the proper format. *
//**********************************************************
import java.util.Scanner;
import java.text.DecimalFormat;
public class CustomerNumber
{
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())
System.out.println(dollar + " is valid");
else
System.out.println(dollar + " is invalid");
/*if (Customer.isValidDollar(dollar))// invoking meth below
{
System.out.println("Thank you for typing AMOUNT ");
}
else
{
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("Enter dollar amount spelled out ");
// Get a customer number from the user.
spelled = keyboard.nextLine();//customer=Amount=dollar
/*************************************************************/
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$" + dollar
+ "\r\r" + spelled + "\r");
System.out.println("");
} // this closes main
/
}
Patmea at 2007-7-28 18:54:10 >

