Thanks for checking out my question. Edits were to expend.
This code takes the string "3$ 29C 3P 1H" and splits it into an array and prints. I want to parse each token of the array for the character and print as such: "3 dollars 29 cents 3 penny 1 hpenny" The idea is that the program can take any currency input and present it in "full" form.
public parseCurrency()
{
System.out.print('\u000c');
String currencyIn = "3$ 29C 3P 1H";
String[] tokens = currencyIn.split(" ");
for (String t : tokens)
{ System.out.println(t);}
String dollars = tokens[0];
String cents = tokens[1];
String penny = tokens [2];
String hPenny = tokens [3];
}
I think something like this needs to follow. The loop goes through the array, character by character, picks out the d, c, p, and h then replaces the characters with the corresponding strings.
for (int i=0; i<tokens.length(); i++)
{
char c = tokens.charAt(i);
if (c == 'D')
{
String dollarsFull = dollars.replaceAll("D", "Dollars");
}
if (c == 'C')
{
String centsFull = cents.replaceAll("C", "cents");
}
etc
}
Question 1: The loop condition "tokens.length" is supposed to be the number of characters in each part of the array. I know my code is incorrect, but I don't understand why.
Question 2: I've used charAt() to parse characters in a string, does this line work the same way?
edits - I left this stuff out to keep the question light weight
The program is supposed to take user input with scanner so there is also supposed to be error detection. I took my current code out to make it quicker to read etc. I've seen examples with error detection parse a string and have a series of if statements (or switch) with error returns. For example, if the user inputs "3 29c 3p 1h" then the program will return something like "expected 'D'".
Many thanks in advance.
tokens.lengthgives you length of array (in your case it would be 4) and not the length of string. 2.tokens.charAt(i);this would not event compile sincecharAtis a method of String class, and is not applicable to array