hi, this is a little example I made in java to count the letters, uppcase and lowercase spaces, digits in a string.
anyway hope you like it, note I am still learning java so there maybe things I can do betters comments are welcome.
Code:import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Scanner; public class Main { //Checks for words not including digits or other symbols public static boolean isWord(String S){ boolean flag; char[] chars = S.toCharArray(); flag = true; for(char c : chars){ if(!Character.isLetter(c)){ flag = false; break; } } return flag; } public static void main(String[] args) { int letters = 0; int spaces = 0; int numbers = 0; int words = 0; int upperCase = 0; int lowerCase = 0; int other = 0; int lines = 0; if(args.length == 0){ System.out.println("Source Input Required."); return; } try { //Read all bytes from the filename. String s = new String(Files.readAllBytes(Paths.get(args[0]))); //Use scanner to split the string. Scanner scan = new Scanner(s); //Count words while (scan.hasNext()){ if(isWord(scan.next())) { words++; } } //Close scanner obj scan.close(); //Convert string to char array char[] chars = s.toCharArray(); //Count chars for(char c : chars){ //Check for new lines if(c == '\n') { lines++; }else if(Character.isSpaceChar(c)){ //Above checks for spaces spaces++; }else if(Character.isDigit(c)){ //Above checks for digits numbers++; }else if(Character.isUpperCase(c)){ //Above checks for uppercase. upperCase++; }else if(Character.isLowerCase(c)){ //Above checks for lowercase lowerCase++; }else{ other++; } } letters = (upperCase + lowerCase); System.out.println("Letters : " + letters); System.out.println("Uppercase : " + upperCase); System.out.println("Lowercase : " + lowerCase); System.out.println("Words : " + words); System.out.println("Numbers : " + numbers); System.out.println("Spaces : " + spaces); System.out.println("Lines : " + lines); System.out.println("Other : " + other); }catch (IOException e){ System.out.print(e.getMessage()); } } }




Reply With Quote