1

What I am trying to do here is read a file and count each character. Each character should add +1 to the "int count" and then print out the value of "int count".

I hope that what I am trying to do is clear.

import java.io.*;
import java.util.Scanner;

public class ScanXan {

public static void main(String[] args) throws IOException {

    int count = 0;
    Scanner scan = null;
    Scanner cCount = null;

    try {
        scan = new Scanner(new BufferedReader(new FileReader("greeting")));

        while (scan.hasNextLine()) {
            System.out.println(scan.nextLine());
        }
    }

    finally {
        if (scan != null) {
            scan.close();
        }
    }

    try {

        cCount = new Scanner(new BufferedReader(new  FileReader("greeting")));
        while (cCount.hasNext("")) {
            count++;
        }
    }

    finally {
        if (cCount != null) {
            scan.close();
        }
    }

    System.out.println(count);

}

}
Morgan
  • 87
  • 10
  • Whenever I try to print the "int count" it returns 0 which tells me that its not counting anything. – Morgan May 09 '15 at 15:31

4 Answers4

3
  1. Add a catch block to check for exception
  2. Remove the parameter from hasNext("")
  3. Move to the next token

        cCount = new Scanner(new BufferedReader(new  FileReader("greeting")));
        while (cCount.hasNext()) {
                count = count + (cCount.next()).length();
        }
    
singhakash
  • 7,891
  • 6
  • 31
  • 65
  • That worked perfect and allowed me to use the code I had without adding anything special or making too many modifications. Thank you. – Morgan May 09 '15 at 15:55
1

Using java 8 Stream API, you can do it as follow

package example;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CountCharacter {

    private static int count=0;

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("greeting");
        try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
            count = lines.collect(Collectors.summingInt(String::length));
        }
        System.out.println("The number of charachters is "+count);
    }

}
MChaker
  • 2,610
  • 2
  • 22
  • 38
  • I tried it here on my IDE and it works perfectly ;) @SashaSalauyou – MChaker May 09 '15 at 15:49
  • Yes, I see, `count` is static in your code. Btw, using `count = lines.collect(Collectors.summingInt(String::length));` would be cleaner and avoid mentioned problem if you declare `count` in another scope. – Alex Salauyou May 09 '15 at 15:52
0

Well if your looking for a way to count only all chars and integers without any blank spaces and things like 'tab', 'enter' etc.. then you could first remove those empty spaces using this function:

st.replaceAll("\\s+","")

and then you would just do a string count

String str = "a string";
int length = str.length( );
singhakash
  • 7,891
  • 6
  • 31
  • 65
Alex
  • 132
  • 1
  • 1
  • 9
  • Wouldn't that require me to copy the information from the file to a string first and then count the characters? Also I'm not concerned about ignoring the whitespace or commas etc. – Morgan May 09 '15 at 15:42
  • oh, well yes, generally this can be done in one line by using a library like Guava or Commons / IO. check out this thread: http://stackoverflow.com/questions/12559917/java-how-to-convert-a-file-object-to-a-string-object-in-java it's from 2012 but hope it helps – Alex May 09 '15 at 16:21
0

First of all, why would you use try { } without catch(Exception e)

BufferedReader reader = null;
try {
reader = new BufferedReader(new    FileReader("greetings.txt"));
String line = null;
String text = "";
while ((line = reader.readLine()) != null) {
     text += line;
}
int c = 0; //count of any character except whitespaces
 // or you can use what @Alex wrote
 // c = text.replaceAll("\\s+", "").length();    
for (int i = 0; i < text.length(); i++) {
    if (!Character.isWhitespace(text.charAt(i))) {
        c++;
    }
}
System.out.println("Number of characters: " +c);
} catch (IOException e) {
     System.out.println("File Not Found");
} finally {
     if (reader != null) { reader.close();
     }
}