reading a file and printing the average from strings and integers - java

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);
}
}

Related

Deduplication from text file using scanner without arrays (Java)

I'm trying to read a text file that contains integers on different lines that are already sorted from least to greatest. Said integers have to be transported to another text file but without any duplicates and without using any sort of arrays, array list, maps, sets, or any other sort of data structure.
Currently I've tried to read numbers from the first text file,and use a while loop to check if the next numbers are similar, with the Scanner. The only problem is that the loop gets the next integer in it as well so this algorithm only works if all numbers are duplicated. This'll make my day if somebody could at least point me in the right direction, thanks in advance!
Example Text File One (all integers are on a new line): 5 5 5 5 5 8 8 9 9 9 9 10 10 11
My output: 5 8 9 10
Expected Output: 5 8 9 10 11
public static void deduplicateFiles(String inputFileName,String outputFileName){
Scanner scan = null;
try{
scan = new Scanner(new FileInputStream(inputFileName) );
}catch(FileNotFoundException e){
System.out.println(e.getMessage() );
}
PrintWriter writer = null;
try{
writer = new PrintWriter(outputFileName);
}catch(FileNotFoundException e){
System.out.println(e.getMessage());
}
while(true){
int firstInt = scan.nextInt();
scan.nextLine();
//if(scan.nextInt() != firstInt)
int counter = 1;
while(scan.nextInt() == firstInt && scan.hasNext() != false){
System.out.println("counter" +counter);
counter++;
scan.nextLine();
}
System.out.println("The integers:" + firstInt);
writer.println(firstInt);
if(scan.hasNext() == false)
break;
}
writer.flush();
writer.close();
}
Read all the integers from the file first. Add them to a Set and then write from the set to a file. You can use LinkedHashSet to keep the order.
I've modified the second part of your code, adding a comparison between numbers to the variable 'nextInt'. It was mainly about entries in the right places, I hope it resolve your problem:
public void deduplicateFiles (String inputFileName, String outputFileName){
Scanner scan = null;
try {
scan = new Scanner(new FileInputStream(inputFileName));
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
PrintWriter writer = null;
try {
writer = new PrintWriter(outputFileName);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
while (true) {
//this two lines are initial
int firstInt = scan.nextInt();
int counter = 1;
//next lines are compare adjacent values
while (scan.hasNextLine()) {
int nextInt = scan.nextInt();
if (nextInt == firstInt) {
counter++;
} else {
System.out.println("counter " + counter);
counter = 1;
System.out.println(firstInt);
writer.println(firstInt);
firstInt = nextInt;
}
}
//this three lines terminate adding
writer.print(firstInt);
System.out.println("counter " + counter);
System.out.println(firstInt);
break;
}
writer.flush();
writer.close();
}

Counting characters in a file

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;
}
}
}

Average Word Length .txt

I am having trouble finding the avg word length of a text file. The output I am getting is 0 for some reason. This program also finds the total number of words in a text file, which I have down, just having trouble with finding the average word length.
public class WordCount {
public static void main(String[] args) throws FileNotFoundException {
while (true) {
System.out.println("Enter File name: ");
Scanner input=new Scanner (System.in);
String fileName= input.nextLine();
FileReader wordReader;
File file = new File("text.txt");
try {
wordReader=new FileReader(fileName);
BufferedReader reader=new BufferedReader(wordReader);
String wordCounter;
int numberWords=0;
double avgWord=0;
double chara=0;
while((wordCounter=reader.readLine()) !=null) {
String []words=wordCounter.split(" ");
for(int i=0;i<words.length;i++)
{
numberWords++;
}
}
while((wordCounter=reader.readLine()) !=null) {
String []charWords=wordCounter.split("");
for (int j=0;j<charWords.length;j++) {
chara++;
}
avgWord=chara/numberWords;
}
System.out.println("Total words: "+ numberWords);
System.out.println("Average word length: "+ avgWord);
}catch (FileNotFoundException ex) {
System.out.println("File not found");
System.out.println("Example of a valid input: /Users/Marcus/Documents/text.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The second while-loop will return immediately since reader has already been depleted.
while((wordCounter=reader.readLine()) !=null) {
You must first create a new reader.

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();
}

Scanner adding blank lines with scanning in from a file

I am trying to read in from a file using a Scanner then append these to an Array. However when I do so the Scanner seems to be picking up blank lines and assigning these blanks lines to indexes in the array.
I've tried a fair few different ways of working to no avail and was just wondering if any came along the same problem and new why it would be doing this?
The format of the file is as follows:
F:\Data\SFW3\FOLDER
F:\Data\SFW3\FOLDER
F:\Data\SFW3\FOLDER
F:\Data\SFW3\FOLDER
Any ideas would be greatly welcomed.
public void scanFiles() throws NoSuchElementException {
Scanner sc = null;
System.out.println("Sage 2015 is Installed on this machine");
int i = 0;
try {
String line;
File companyFile = new File(sageFolders[8] + "\\COMPANY");
sc = new Scanner(new BufferedReader(new FileReader(companyFile)));
while(sc.hasNextLine()) {
line = sc.nextLine();
System.out.println(line);
System.out.println(i);
currentFolders.add(i,line);
System.out.println("At Index" + i + ": " + currentFolders.get(i));
i++;
}
sc.close();
}
catch(FileNotFoundException e) {
System.out.println("File not Found: Moving onto next Version");
}
catch(IOException e) {
System.out.println("IO Error");
}
}
Use String.trim().length() to find out if it is a blank line and if not do not add it
System.out.println(i);
if (String.trim().length() > 0) {
currentFolders.add(i,line);
System.out.println("At Index" + i + ": " + currentFolders.get(i));
}
i++;
To achieve your task, try below code:
while(sc.hasNextLine())
{
line = sc.nextLine();
if(null != line && line.trim().length() > 0){
System.out.println(line);
System.out.println(i);
currentFolders.add(i,line);
System.out.println("At Index" + i + ": " + currentFolders.get(i));
i++;
}
}

Categories

Resources