0

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.

2
  • Assuming that both pieces of code are within same scope: 1. tokens.length gives 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 since charAt is a method of String class, and is not applicable to array Commented Apr 19, 2018 at 16:48
  • please select one of the answers, if they are useful and does what you need. new users always do tend to forget they should select an answer if useful, or comment on them if they deviate from your needs. Commented Apr 28, 2018 at 13:00

6 Answers 6

2

1.) charAt() is a method of String class (comes from CharSequence so available in it implementations )so you can only use it with strings like tokens[0].charAt(i);

2.) replaceAll takes String which are case sensitive so this cents.replaceAll("C", "cents") is different from cents.replaceAll("c", "cents")

or you can use replace rather than regex as

    System.out.print('\u000c');
    String currencyIn = "3$ 29C 3P 1H".replace("$"," Dollar")
                        .replace("C"," Cents");
                        // and so on
    String[] tokens = currencyIn.split(" ");

    String dollars = tokens[0]; // 3 Dollar
    String cents = tokens[1]; // 29 Cents
    String penny = tokens [2];
    String hPenny = tokens [3];
Sign up to request clarification or add additional context in comments.

2 Comments

iterative use of replaceAll is always dangerous as any previous replacement might include characters to be replaced.
@YılmazDurmaz yes, but in this case, then the other option is break the string first then apply the replace using charAt and conditional statment
1

You don't need a loop here. You can simply use replace method. Each replace method call returns a new String after replacing the target (D, C, P, H here) with the replacement string.

System.out.println(currencyIn.replace("D", " Dollars")
            .replace("C", " Cents")
            .replace("P", " Penny")
            .replace("H", " HPenny"));

2 Comments

iterative use of replaceAll is always dangerous as any previous replacement might include characters to be replaced.
@YılmazDurmaz From the requirement of the OP, it follows that the input would always be in a specific format.
1

Instead of

    String dollars = tokens[0];
    String cents = tokens[1];
    String penny = tokens[2];
    String hPenny = tokens[3];

Try this instead:

    String dollars = tokens[0].replaceAll("D", "Dollars");
    String cents = tokens[1].replaceAll("C", "cents");
    ...

To answer your specific questions, it looks like you want to loop over characters in a string to find the characters to replace. But instead you're looping over tokens in the tokens array. Remember that tokens is defined to be a String[] so you can't call .charAt(i). You can only call .charAt() on a String object:

for (String token : tokens) {
    for (int i = 0; i < token.length(); i++) {
        char c = token.charAt(i);
        ...
    }
}

But this approach isn't necessary, using .replaceAll will accomplish what you want without you needing to write a loop.

Comments

0

try this :

public static String parseCurrency(String s)
{
    return s.replaceAll("\\$", " Dollars").replaceAll("C", " cents").replaceAll("P", " penny").replaceAll("H", " hpenny");
}

and you call :

String s = "3$ 29C 3P";
System.out.println(parseCurrency(s));

Please note that "$" is a special character, use "\$" instead of only "$" when you use replaceAll

1 Comment

iterative use of replaceAll is always dangerous as any previous replacement might include characters to be replaced.
0

The easiest way to do this would be like this:

String currencyIn = "3$ 29C 3P 1H".toUpperCase();
currencyIn = currencyIn.replaceAll("$","dollar").replaceAll("C","cents").replaceAll("P","penny ").replaceAll("H","hpenny");

The code will get the string an change all the lowercase characters to uppercase.You can also change all the uppercase to lowercase using:

currencyIn.toLowerCase();

For the questions part:

1) tokens.length is showing the length of an array not the lengths of each item in the array.

2) charAt() is only used in strings.For arrays you use [index] and it will give you the object at the the index position.Be aware that you start from zero in arrays.

1 Comment

iterative use of replaceAll is always dangerous as any previous replacement might include characters to be replaced.
0

Try this instead:

String dollars = tokens[0].toUpperCase().replaceAll("D", "Dollars");
String cents = tokens[1].toUpperCase().replaceAll("C", "Cents");
String penny = tokens[2].toUpperCase().replaceAll("P", "Pennies");
String hPenny = tokens[3].toUpperCase().replaceAll("H", "HPennies");

You don't have to manually write your own code as there possibly are libraries to do what you want. replaceAll does what you want, partially. toUpperCase ensures correct conversion. If you need anything else, that should be to check if there is any misspelling in the entry, or check the value and write singular names like "Penny.

Also l=tokens.length(); will give you 4 as you have 4 tokens, and you have to use j=tokens[i].length(); to get the length of a token itself. j=tokens[i].length()-1; tokens[i].charAt(j) is what you need to find the last char, but StringUtils.isNumeric(tokens[i]) should check first if currency symbol is present. if you need to convert to integer, num=Integer.parseInt(arg); does this; arg=tokens[i] if currency symbol NOT present, or j=tokens[i].length()-1;arg=tokens[i].sunString(0,j-1); if it is. the order of operations may change to your need, but operations are as described.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.