You can do something like this:
Scanner in = new Scanner(new File(fileName));
String input = "";
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))) {
//code here
}
سؤال
I am currently trying to create a Java program that allows a scanner to read 100 integers from a .txt file and then for the program to output the average of the 100 numbers. It must also check for errors whilst reading from the code. E.G (there is a letter in .txt file, instead of an integer).
Here is the code I have so far:
package NumFile;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Scanner;
public class NumFile {
public static void main (String [] args) throws FileNotFoundException {
try {
int counter = 0; // Counter for number of numbers in the txt file
double sum = 0; // Sum of all digits in the txt file
String line = null; // The line that is read in the txt file
Scanner userIn = new Scanner(System.in);
System.out.println("Type the name of the file located");
String fileName = userIn.nextLine();
BufferedReader in = new BufferedReader(new FileReader(Workbook1.txt));
Object input;
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))) {
counter++;
sum += Double.parseDouble(line);
}
double average = sum/counter;
System.out.println("The average of the numbers is: " + format(average));
System.out.println("The sum of the numbers is: " + sum);
System.out.println("The number of digits is " + counter);
}
catch (IOException e) {
System.out.println("Input/Output exception");
}
}
public static String format(double number) {
DecimalFormat d = new DecimalFormat("0.00");
return d.format(number);
}
}
With this code, I am having a few errors. Here are the errors that display:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Workbook1 cannot be resolved to a variable
The method hasNextLine() is undefined for the type BufferedReader
The method nextLine() is undefined for the type BufferedReader
at NumFile.NumFile.main(NumFile.java:27)
If I remove:
Object input;
// Loop until the end of the file
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))){
then the program starts to run, however it cannot find the .txt file containing the integers!
المحلول
You can do something like this:
Scanner in = new Scanner(new File(fileName));
String input = "";
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))) {
//code here
}