Counting characters in a file - java

I am writing code that counts the number of characters, words and lines in a .txt file. My sample text file has 21 words, 2 lines, and 114 characters. My program output states there are 21 words, 2 lines and 113 characters. The file is mostly barren and is only meant for testing purposes. In the file is:
This is a test for counter function. Contents are subject to change.
This line tests if the line count is correct.
My program is:
public static void counter(){
String file_name = "input.txt";
File input_file = new File(file_name);
Scanner in_file = null;
int word_count = 0;
int line_count = 0;
int char_count = 0;
String line;
try{
in_file = new Scanner(input_file);
}
catch(FileNotFoundException ex){
System.out.println("Error: This file doesn't exist");
System.exit(0);
}
try{
while(in_file.hasNextLine()){
line = in_file.nextLine();
char_count = char_count + line.length();
String[] word_list = line.split(" ");
word_count = word_count + word_list.length;
String[] line_list = line.split("[,\\n]");
line_count = line_count + line_list.length;
}
}
catch(ArrayIndexOutOfBoundsException ex){
System.out.println("Error: The file format is incorrect");
}
catch(InputMismatchException ex){
System.out.println("Error: The file format is incorrect");
}
finally{
System.out.print("Number of words: ");
System.out.println(word_count);
System.out.print("Number of lines: ");
System.out.println(line_count);
System.out.print("Number of characters: ");
System.out.println(char_count);
in_file.close();
}
}

The correct code for this would be
public void calculateFileCharecteristics(String fileName){
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(new
File(filename)))){
String line;
int lineCount = 0;
int totalCharCount = 0;
while((line=bufferedReader.readLine())!=null){
lineCount++;
int charCount = line.split("\n").length;
totalCharCount +=charCount;
}
}
}

Related

Printwriter not writing to file

output file is created but numbers are not written.
public static void main(String[] args)
{
String file_name;
String done_string = "done";
boolean done = false;
while (!done)
{
file_name = JOptionPane.showInputDialog("Enter a file name" + " or done to exit: ");
if (file_name.equals(done_string))
{
done = true;
JOptionPane.showMessageDialog(null, "EXITING");
}
else
{
try
{
File file_in = new File(file_name);
Scanner input = new Scanner(file_in);
JOptionPane.showMessageDialog(null, "File " + file_name + " found ");
int[] hold_ints = new int[100];
for (int i = 0; i< 100; i++)
{
hold_ints[i] = input.nextInt();
}
PrintWriter output = new PrintWriter("reverse_ints");
for (int i = 99; i <= 0; i--)
{
output.print(hold_ints[i]);
output.print(" ");
}
output.close();
input.close();
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null, "File " + file_name + " not found ");
}
}
}
}
}
Program should read a file then create an output file that prints the numbers in the input file in reverse.
Actual results just shows the file but nothing is written in the file.
For-loop condition is wrong, so code in the loop is not run.
I suppose it should be
for (int i = 99; i >= 0; i--)
{
output.print(hold_ints[i]);
output.print(" ");
}

Cannot Read Next Console Line - NoSuchElementException

The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places
however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable
This is Current Method
private static void FileWritting () throws IOException {
System.out.println("\n6.7.2 Writting Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner2 = new Scanner(System.in);
String filename = Scanner2.nextLine();
FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
BufferedWriter bw = new BufferedWriter(writehandle);
int n = 10;
for(int i=1;i<n;++i)
{
double value = Math.sqrt(i);
String formattedString = String.format("%."+ (i-1) +"f", value);
System.out.println(formattedString);
// bw.write(line);
bw.newLine();
}
bw.close();
writehandle.close();
Scanner2.close();
}
Where This is the previous method
System.out.println("6.7.1 Reading Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner1 = new Scanner(System.in);
String filename = Scanner1.nextLine();
FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
BufferedReader br = new BufferedReader(readhandle);
String line = br.readLine ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println("The number of words is: " + count);
br.close();
Scanner1.close();
}
You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).
More info and a better explanation

need help about reading numbers inside file

First I create a txt file (a.txt) -- DONE
create 10 random number from - to ( like from 5 -10 ) --DONE
I write this number in txt file --DONE
I want to check its written or not -- DONE
Now I need to find: how many number, biggest, smallest, sum of numbers
But I can not call that file and search in the file (a.txt). I am just sending last part. Other parts work. I need some help to understand. It is also inside another method. not main
Scanner keyboard = new Scanner(System.in);
boolean again = true;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int a = 0;
int count = 0;
System.out.println("Enter the filename to write into all analysis: ");
outputFileName = keyboard.nextLine();
File file2 = new File(outputFileName);
if (file2.exists()) {
System.out.println("The file " + outputFileName +
" already exists. Will re-write its content");
}
try {
PrintWriter yaz = new PrintWriter(file2);
// formulas here. created file a.txt need to search into that file biggest smallest and sum of numbers
yaz.println("Numeric data file name: " + inputFileName);
yaz.println("Number of integer: " + numLines);
yaz.println("The total of all integers in file: " + numLines); //fornow
yaz.println("The largest integer in the set: " + max);
yaz.println("The smallest integer in the set " + min);
yaz.close();
System.out.println("Data written to the file.");
} catch (Exception e) {
System.out.printf("ERROR reading from file %s!\n", inputFileName);
System.out.printf("ERROR Message: %s!\n", e.getMessage());
}
So you want a code to read a text file and give you the biggest, smallest and the average.
You can use Scanner class for that and use hasNextInt() to find integers
File f = new File("F:/some_text_file.txt"); // input your text file here
if(f.exists()){
try{
Scanner sc = new Scanner(f);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int temp=0, i=0;
double sum=0;
while(sc.hasNextInt()){
temp = sc.nextInt();
if(temp>max) max = temp;
if(temp<min) min =temp;
sum+=(double) temp;
i++;
}
System.out.println("average : " +sum/i);
System.out.println("large : "+max);
System.out.println("small :"+min);
sc.close();
}catch(Exception e){
e.printStackTrace();
}
}
See if this works
You need to read the file into memory. One way to do that is to move the text of the file into a String.
This post will help you: Reading a plain text file in Java
Here's the relevant code:
try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
}

reading a file and printing the average from strings and integers

I have a text file containing on each line a name and a sequence of integers, for instance
Jules 50 60 40
Ali 45 70 70 90
Emma 45 54
I have this for my code but it does not print out the average also I'm not sure on how to read sequence of integers
public void AverageMarks(String fName, String pname) {
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(fName));
}catch(FileNotFoundException e){
System.out.println("Could not find file");
}
try{
double average = 0;
double sum = 0;
String line;
while((line = br.readLine()) != null){
String[] lines = line.split(" ");
if(pname.equals(lines[0])){
for(int i =0; i<lines.length; i++){
sum+= Double.parseDouble(lines[i+1]);
}
average = sum / lines.length;
System.out.println(average);
System.exit(0);
}
else{
System.out.println(pname + " No such name");
System.exit(0);
}
}
}catch(IOException e){
System.out.println("An error has occured");
}
finally{
System.exit(0);
}
}
For example the average is a double...
AverageMarks("myfile.txt","Jules") should print 50.0
AverageMarks("myfile.txt","Ali") should print 68.75
AverageMarks("myfile.txt","Neil") should print Neil No such name
Problem is, you should not have else block in you while loop. else block statements should be out of look to make sure that you have processed all the lines in the file and no such name exists. Also there was problem with for loop index. It should start from 1 not from 0. Try this:
public void AverageMarks(String fName, String pname) {
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(fName));
}catch(FileNotFoundException e){
System.out.println("Could not find file");
}
try{
double average = 0;
double sum = 0;
String line;
while((line = br.readLine()) != null){
String[] lines = line.split(" ");
if(pname.equals(lines[0])){
if(lines.length > 1) { // check to calculate average only when there are numbers as well in the line
for(int i = 1; i<lines.length; i++){ // loop index shold start from 1 as element at index 0 is name
sum+= Double.parseDouble(lines[i]);
}
average = sum / (lines.length - 1);
}
System.out.println(average);
System.exit(0);
}
}
// moved these lines from inside loop, to make sure all the names in the files have been checked
System.out.println(pname + " No such name");
System.exit(0);
}catch(IOException e){
System.out.println("An error has occured");
}
finally{
System.exit(0);
}
}

How would I modify this so that rather than have it break it will just request the user to enter the file name again?

The problem
When the user enters the filename into the program, it will create an exception stating that there is no file named like that in the directory.
What I want is that - instead of showing an exception - the program will repeat the message that asks the user to enter the filename.
My code:
import java.io.*;
import java.util.*;
public class reader {
static int validresults = 0;
static int invalidresults = 0;
//used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
//checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
//also checks to make sure that there are no results that are just whitespace
public static boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
//checks to make sure that the data is an integer
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
while(true){ //Runs until it is specified to break
System.out.println("Enter filename");
String fileName = sc.nextLine();
if(fileName != null && !fileName.isEmpty()){
processFile(fileName);
}else{
}
}
}
private static void processFile(String fileName) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(fileName))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
//splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
validresults = validresults + 1;
System.out.println(hteam + " " + "[" + hscore + "]" + " " + "|" + " " + ateam + " " + "[" + ascore + "]");
//output the data from the file in the format requested
}
else{
invalidresults = invalidresults + 1;
}
}
System.out.println("Total number of goals scored was " + totgoals);
//displays the the total number of goals
System.out.println("Valid number of games is " + validresults);
System.out.println("Invalid number of games is " + invalidresults);
System.out.println("EOF");
}
}
You can try determine if the file exists first by doing something like the following:
File file = new File(fileName);
if(file.exists()) {
processFile(fileName)
}
Here is the solution
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
while(true){ //Runs until it is specified to break
System.out.println("Enter filename");
String fileName = sc.nextLine();
File file = new File(fileName);
if(!file.exists()) {
continue;
}
processFile(fileName);
}
}
Use this code:
String fileName;
File file;
for(;;) {
/* read file name */
System.out.print("enter file name: ");
fileName = bufferedReader.readLine();
file = new File(fileName);
/* check path */
if (!file.exists())
System.out.println("file doesn't exist");
else if(!file.isFile())
System.out.println("file isn't a regular file");
else if (...)
...
else
break;
}
where bufferedReader is BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); if you want to read file name from keyboard.
You can check if file exists exists(), is a regular file isFile(), is a directory isDirectory(), can be read carRead(), wrote canWrite(), executed canExecute(), an so on..

Categories

Resources