Longest and shortest line in text file behaving strangely - java

I am having some problems with my code. It is a program that reads lines from a text file and the output is the shortest and the longest string and the average size as a decimal double (x,xx). My current code is:
import java.io.*;
import java.util.*;
public class LineCalculator {
public static void main(String[] arr){
System.out.println("Enter the name of the input file");
Scanner scanner = new Scanner(System.in);
String file = scanner.nextLine();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
int sum = 0;
double average = 0;
int totallength = 0;
String shortestline = new String();
String longestline = new String();
while ((line = br.readLine()) != null) {
sum++;
if (shortestline.length() > line.length()||line!=null){
shortestline = line;
}
if(longestline.length() < line.length()){
longestline = line;
}
int temp = line.length();
totallength = totallength + temp;
average = (double) Math.round(100*totallength/(double)sum)/100;
}
System.out.println("Shortest line: "+shortestline);
System.out.println("Longest line: "+longestline);
System.out.println("Average lenght of the lines: "+ average);
} catch (FileNotFoundException e) {
System.out.println("File not found, panic!");
} catch (IOException e) {
System.out.println("The input of the file is not compatible");
e.printStackTrace();
}
}
}
which works partially, it outputs the correct average and longest line, although I do not know why it outputs the correct longest line (the < sign in this code doesn't seem correct) and the shortestline always returns the latest input in the file for some reason. Can anyone see my mistake?

Look at what this code is doing. If line is shorter than shortest OR it is not null (which is every line in the file!) we set it to be the new shortest line.
if (shortestline.length() > line.length()||line!=null){
shortestline = line;
}
It should be
if (shortestline.length() > line.length()){
shortestline = line;
}
or, if you intended to do a null check:
if (line != null && shortestline.length() > line.length()){
shortestline = line;
}
Pshemo correctly pointed out another problem, which is that you initialize shortestline to be new String(), whose length is 0. You will never encounter a string with length less than 0.

Related

Can someone help me figure out what is wrong with my WhiteSpaceCounter code?

I need a program that counts the whitespace in a text document, but it keeps giving me an insane number of whitespaces, as I think the while loop just keeps repeating. could anyone read it over and tell me what is up?
import java.io.*;
public class WhiteSpaceCounter {
public static void main(String[] args) throws IOException {
File file = new File("excerpt.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader inreader = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(inreader);
String sentence;
int countWords = 0, whitespaceCount = 0;
while((sentence = reader.readLine()) != null) {
String[] wordlist = sentence.split("\\s+");
countWords += wordlist.length;
whitespaceCount += countWords -1;
}
System.out.println("The total number of whitespaces in the file is: "
+ whitespaceCount);
}
}
You could also use this
while((sentence = reader.readLine()) != null) {
String[] wordlist = sentence.split("\\s+");
whitespaceCount += wordlist.length-1;
}
If you first line has 3 word and your second line has 10 words, then you logic is
countWords (0) += 3 -> 3
countWords(3) += 10 -> 13
So do not use +=
countWords = wordlist.length;

Find the avg of a set and the class using a text file in java

Marks for a class are stored in a text file called “marks3.txt”. The marks are saved in the following format: The first number represents the total number of (two-digit) marks stored sequentially in each line of text. Each line of text represents a set of marks.
For example (the txt file would contain the following numbers)
4567687509
569563
the marks are:
45%, 67%, 68%, 75%, 9%
56%, 95%, 63%
Write a method that will calculate the average of each set of marks as well as the overall average.
Below is the code I have created, I'm confused on how I would loop through the file until I have the two numbers that would make up the mark. Another thing I'm stuck on is how the method would be called.
import java.io.*;
public class ReadFile {
public static int calcAvg (String x) throws IOException {
int avg = 0;
int count = 0;
FileReader fr = new FileReader ("/home/sharma6a/marks.txt");
BufferedReader br = new BufferedReader (fr);
while ((x = br.readLine()) != null) {
if (count <= 2) {
}
}
br.close();
return avg;
}
considering an input file like
45676875
09569563
first I will have a method to read the file and transform it into a better structure to use.
public List<Integer> readFile() throws FileNotFoundException {
List<Integer> numbers = new ArrayList<>();
String line = "";
try {
FileReader fr = new FileReader("src/main/resources/numbers.txt");
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
for (int i = 0; i <= line.length() - 2; i+=2) {
char[] chars = line.toCharArray();
int number = Integer.parseInt(String.valueOf(chars[i]) + String.valueOf(chars[i+1]));
numbers.add(number);
}
}
} catch (Exception e) {
System.out.println(e);
}
return numbers;
}
then I will have the method to calculate the AVG
public float calcAvg(List<Integer> numbers) throws IOException {
int sum = 0;
for (int number: numbers){
sum+= number;
}
return sum/(numbers.size());
}
of course, you need a start method to make things happen
something like
public void init() throws IOException {
List<Integer> numbers = readFile();
float result = calcAvg(numbers);
System.out.println(result);
}
It's as easy as that. You practically want people to do stuff for you, but this is a question and answer site. Here you'll see some code for getting the individual percentages. You'll figure the rest out.
File f = new File(path);
try {
Scanner scanner = new Scanner(f);
String line = scanner.nextLine();
for (int i = 0; i < line.length() - 1; i+=2) {
double percentage = Double.parseDouble(line.substring(i, i+2)) / 100.0;
}
} catch (Exception e) {e.printStackTrace();}

Retrieve number of lines in file from JFileChooser Java

Is there a way in Java to know the number of lines of a file chosen?
The method chooser.getSelectedFile().length() is the only method I've seen so far but I can't find out how to find the number of lines in a file (or even the number of characters)
Any help is appreciated, thank you.
--update--
long totLength = fc.getSelectedFile().length(); // total bytes = 284
double percentuale = 100.0 / totLength; // 0.352112676056338
int read = 0;
String line = br.readLine();
read += line.length();
Object[] s = new Object[4];
while ((line = br.readLine()) != null)
{
s[0] = line;
read += line.length();
line = br.readLine();
s[1] = line;
read += line.length();
line = br.readLine();
s[2] = line;
read += line.length();
line = br.readLine();
s[3] = line;
read += line.length();
}
this is what I tried, but the number of the variable read at the end is < of the totLength and I don't know what File.length() returns in bytes other than the content of the file.. As you can see, here i'm trying to read characters though.
Down and dirty:
long count = Files.lines(Paths.get(chooser.getSelectedFile())).count();
You may find this little method handy. It gives you the option to ignore counting blank lines in a file:
public long fileLinesCount(final String filePath, boolean... ignoreBlankLines) {
boolean ignoreBlanks = false;
long count = 0;
if (ignoreBlankLines.length > 0) {
ignoreBlanks = ignoreBlankLines[0];
}
try {
if (ignoreBlanks) {
count = Files.lines(Paths.get(filePath)).filter(line -> line.length() > 0).count();
}
else {
count = Files.lines(Paths.get(filePath)).count();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
return count;
}
You could use the JFileChooser to select a file, than open the file using a file reader and as you iterate over the file just increment a counter, like this...
while (file.hasNextLine()) {
count++;
file.nextLine();
}

Benford's Law Java - Extracting first digit from a string array read from a file?

I am trying to create a program in Java that reads from a file, extracts the first digit of every number, determines the frequencies of 0-9, and prints out the frequencies (in percentages) of the numbers 0 through 9. I already figured out how to read from my file ("lakes.txt");
FileReader fr = new FileReader ("lakes.txt");
BufferedReader br = new BufferedReader(fr);
//for loop that traverses each line of the file
int count = 0;
for (String s = br.readLine(); s!= null; s = br.readLine()) {
System.out.println(s); //print out every term
count++;
}
String [] nums;
nums = new String[count];
//close and reset file readers
fr.close();
fr = new FileReader ("lakes.txt");
br = new BufferedReader(fr);
//read each line of the file
count = 0;
for (String s = br.readLine(); s!= null; s = br.readLine()) {
nums[count] = s;
count++;
}
I am currently printing out every term just to make sure it is working.
Now I am trying to figure out how to extract the first digit from each term in my string array.
For example, the first number in the array is 15,917, and I want to extract 1. The second number is 8,090 and I want to extract 8.
How can I do this?
To extract the first number from a String
Get the first letter from the String
Parse (1) into a number
For example:
String firstLetter = Character.toString(s.charAt(0));//alternatively use s.substring(0,1)
int value = Integer.parseInt(firstLetter);
This would be placed inside the file reading loop, assuming each line of the file contains a numeric value (in other words, no further processing or error handling of the lines of the file is required).
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TermReader {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader ("lakes.txt");
BufferedReader br = new BufferedReader(fr);
int[] tally = new int[]{0,0,0,0,0,0,0,0,0,0};
int total = 0;
for (String s = br.readLine(); s!= null; s = br.readLine()) {
char[] digits = s.toCharArray();
for(char digit : digits) {
if( Character.isDigit(digit)) {
total++;
tally[Integer.parseInt(Character.toString(digit))]++;
break;
}
}
}
br.close();
for(int index = 0; index < 10; index++) {
double average = tally[index] == 0 ? 0.0 : (((double)tally[index]) / total) * 100;
System.out.println("[" + index + "][" + tally[index] + "][" + total + "][" + Math.round(average * 100.0) / 100.0 + "]");
}
}
}

program that uses input file and creates a new one

I'm writing a code that uses an input file called InvetoryReport.txt in a program I am supposed to create that is supposed to take this file, and then multiply two pieces of data within the file and then create a new file with this data. Also at the beginning of the program it is supposed to ask you for the name of the input file. You get three chances then it is to inform you that it cannot find it and will now exit, then stop executing.
My input file is this
Bill 40.95 10
Hammer 1.99 6
Screw 2.88 2
Milk .03 988
(The program is supposed to multiply the two numbers in the column and create a new column with the sum, and then under print another line like this
" Inventory Report
Bill 40.95 10 409.5
Hammer 1.99 6 11.94
Screw 2.88 2 5.76
Milk .03 988 29.64
Total INVENTORY value $ 456.84"
and my program I have so far is this
package textfiles;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class LookOut{
double total = 0.0;
String getFileName(){
System.out.printIn("Type in file name here.");
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
return str;
}
void updateTotal(double d){
total = total + d;
}
double getLineNumber(int String_line){
String [] invRep = line.split(" ");
Double x = double.parseDouble(invRep[1]);
Double y = double.parseDouble(invRep[2]);
return x * y;
}
void printNewData(String = newData) {
PrintWriter pW = new PrintWriter ("newData");
pw.print(newData);
pw.close;
}
public static void main(String[] args){
String str = ("Get file name");
String str = NewData("InventoryReport/n");
File file = new File(str);
Scanner s = new Scanner(file);
while(s.hasNextLine()) {
String line = s.nextLine();
double data = getLineNumber(line);
update total(data);
NewData += line + " " + data + "/n";
Print NewData(NewData);
}
}
}
I'm getting multiple error codes that I just cant seem to figure out.
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Despite your best intentions you are in fact missing a '}'. Note that you haven't escaped the Try block before the catch. I imagine this is because you confused the closing } for the while statement as the closing } for the try block. Do this instead:
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
}
}
catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Also, your indentation is ALL OVER THE PLACE. This should be a lesson to you in why you should format your code properly! It is so easy to miss simple syntax errors like that if you're not formatting properly. It's also hard for others to read your code and figure out what's wrong with it.

Categories

Resources