Count Uppercase letters
Ok i have to pass a string to the main method which is obviously stored in args[0].Then count the amount of times an uppercase letter occurs. For some reason i do not seem to be counting the uppercase occurrence properly. This is homework, any ideas? Thanks in advance.
package chapter_9;
public class Nine_Fifteen {
public static void main(String[] args) {
int caps = 0;
for(int i = 0;i < args.length;i++) {
if (Character.isUpperCase(args[0].codePointCount(i, i))){
caps++;
}
开发者_StackOverflow社区 System.out.println("There are " + caps + " uppercase letters");
}
}
}
The problem is your use of String.codePointCount
:
Returns the number of Unicode code points in the specified text range of this String. The text range begins at the specified beginIndex and extends to the char at index endIndex - 1. Thus the length (in chars) of the text range is endIndex-beginIndex. Unpaired surrogates within the text range count as one code point each.
That's not what you want - you're passing that into Character.isUpperCase
, which isn't right.
Do you definitely need to handle non-BMP Unicode? If not, your code can be a lot simpler if you use charAt(i)
to get the char
at a particular index instead. You also want to loop from 0 to args[0].length()
as Kevin mentioned. I would suggest extracting the args[0]
part to a separate string variable to start with, to avoid the confusion:
String text = args[0];
for (int i = 0; i < text.length(); i++) {
// Check in here
}
I won't complete the code for you as it's homework, but hopefully this will be enough to get you going.
args.length
is the number of args
you have (so, most likely, 1), but you want to parse the length of args[0]
(args[0].length
)
Also, use charAt(i) to test for uppercaseness.
Check that your
for
loop really loops over what you think you loop.Don't use
codePointCount()
, there's a method with a much shorter name that gives you the character at a positionYou probably don't want to print out the number of caps on every loop iteration
精彩评论