I am creating a text analyzer using java, what I'm trying to do is to search through the text document, and count how many Capital letter there are.
public static void main(String[] args) {
Scanner sc = new Scanner(CapitalCount.class.getResourceAsStream("test.txt"));
String s = sc.nextLine();
int upperCaseCount = 0;
int linecount = 0;
while (sc.hasNextLine()) {
sc.nextLine();
linecount++;
}
for (int i = 0; i < s.length(); i++) {
for (char c = 'A'; c <= 'Z'; c++) {
if (s.charAt(i) == c) {
upperCaseCount++;
}
}
}
System.out.println(upperCaseCount + "");
}
}
I think that i will have to do some sort of count on how many lines there are, this is why i have added a line count at the top, although I am unsure on how to implement this with the capital count that only works on the first line.
You don't need CapitalCount class to scan a file.
Below is my working solution:
public static void main(String[] args) {
Scanner sc = null;
try {
sc = new Scanner(new File("test.txt"));
int count = 0;
while(sc.hasNext()){
String line = sc.nextLine();
for(int i = 0 ; i < line.length(); i++){
if(line.charAt(i) >= 'A' && line.charAt(i) <= 'Z'){
count ++;
}
}
}
System.out.println("The number of capital letters are : "+count);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
finally{
sc.close();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With