Reputation: 31
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?
Upvotes: 1
Views: 1351
Reputation: 17548
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.
Upvotes: 1