Average of numbers in a .txt file using a scanner - java

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
}

Related

How to scan the amount of integers within an ArrayList index

I'm trying to make a program that checks an ArrayList and makes sure that each index includes only 2 integers per line, and doesn't include any doubles or strings.
If the arraylist is:
0 1
2 34
32 51 32
it would pull up an error message for the third line for having 3 integers. The program needs to check that it has only two integers per line, is only 12 lines long, and doesn't include any doubles or strings. This is what I have so far:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class TextFileReader {
public static void main(String[] args) {
int fileCount = 0;
ArrayList<String> inputFile = new ArrayList<String>(20);
try (Scanner fileScanner = new Scanner(new File("perfect_file.txt"))) {
while (fileScanner.hasNext()) {
inputFile.add(fileScanner.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("Error reading generic answers, program ending.");
System.exit(1);
}
if (inputFile.size() > 12) {
System.out.println("Error: Lines exceed 12");
}
if (inputFile.size() < 12) {
System.out.println("Error: Not enough lines");
}
}
}
I would really appreciate any help on this. Thank you!
Use String split, it's look like
try (Scanner fileScanner = new Scanner(new File("perfect_file.txt"));) {
while (fileScanner.hasNextLine()) {
String[] line = fileScanner.nextLine().split("\\s+");
if (line.length == 2) {
// Ok, do something
// System.out.println("First: " + line[0] + ", Second: " + line[1]);
} else {
// Wrong
System.out.println("The number of line " + line.length);
}
}
}

How to remove commas from a line and write it to an output file

This is my assignment - Write a program that reads a file and removes all comma’s from it and writes it back out to a second file. It should print to the console window, at the end, the number of comma’s removed.
The program needs to:
Prompt the user for the name of the file to read.
Reads file
Write the non-comma characters to output.txt, including all spaces.
When done reading the input file, write the total number of comma’s removed to the console window.
For example, if the input file contains 3+,2 = 5m, 7%,6 =1 hello
Then the output.txt file should contain:
3+2=5m 7%6=1 hello
And the console window should print “Removed 3 commas”.
Right now I'm having trouble actually removing commas from my input file, I think I would write the line under my last if statment.
Tried figuring out how to remove commas from the input file
package pkg4.pkg4.assignment;
import java.util.Scanner;
import java.io.*;
/**
*
* #author bambo
*/
public class Assignment {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the inputfile?");
String inputfile = keyboard.nextLine();
File f = new File(inputfile);
Scanner inputFile = new Scanner(f);
System.out.println("Please enter the output file");
String outputfile = keyboard.nextLine();
FileWriter fw = new FileWriter(outputfile);
PrintWriter pw = new PrintWriter(fw);
int lineNumber=0;
while(inputFile.hasNext());
lineNumber++;
int commacount = 0;
String line = inputFile.nextLine();
if (line.length () != 0)
commacount++;
for(int i=0; i< line.length(); i++)
{
if(line.charAt(i) == ',');
{
commacount++;
}
pw.println("removed " + commacount + "commas");
}
}
}
According to your requirement for program i am suggesting you to use java 8 classes.for simplicity.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) throws IOException {
String content = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfile = keyboard.nextLine();
content = new String(Files.readAllBytes(Paths.get(inputfile)));
long total_numbers_of_char = content.chars().filter(num -> num == ',').count();
System.out.println("Please enter the output file");
content = content.replaceAll(",", "");
String outputfile = keyboard.nextLine();
Files.write(Paths.get(outputfile), content.getBytes());
System.out.println("removed " + total_numbers_of_char + " commas");
keyboard.close();
}
}
To print on console you should be using :
System.out.println("removed " + commacount + "commas");
To write the line in the output file without the commas :
pw.println(line.replaceAll(",",""));

Java - Getting NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a problem with where I am getting a NullPointerException on line 59 of my code.
The program's purpose is to prompt the user for the file location (which has the digits of PI). The program should then accept any number of digits (say k digits) via the Scanner class. Then, the program must read k digits of PI from the file. Using the Scanner class, the program should then obtain a number for 0-9 from a user and print the first and last position in which it appears and also the number of times it appears. Only digits after the decimal point are to be considered. The program should be able to accept 100,000 digits of PI.
The sample output of the code is below:
Give the location of the file:
C:\Users\Joe\Desktop\pi.txt
Number of digits of PI to parse:
10
Give any number between 0-9:
1
1 appears 2 times
First position in which appears: 1
Last position in which appears: 3
Any help would be much appreciated.
Below is my code:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
public class Problem2 {
#SuppressWarnings("null")
public static void main(String[] args) throws Exception {
FileInputStream inputstream = null;
BufferedReader reader = null;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
try {
System.out.println("Give the location of the file (example: C:\\Users\\Joe\\Desktop\\pi.txt):");
String fileloc = input.nextLine();
inputstream = new FileInputStream(fileloc);
reader = new BufferedReader(new InputStreamReader(inputstream));
String stringinput;
System.out.println("Number of digits of PI to parse: ");
int parsenum = input.nextInt() + 2;
String[] stringarray = new String[parsenum];
while((stringinput = reader.readLine()) != null) {
stringinput = stringinput.substring(2, parsenum);
for(int i = 0; i < stringinput.length(); i++) {
stringarray = stringinput.split("");
}
}
System.out.println("Give any number between 0-9: ");
String searchnum = input.next();
int count = 0;
for(int i = 1; i < parsenum - 1; i++) {
if(searchnum == stringarray[i]) {
count++;
}
else count++;
}
System.out.println(searchnum + " appears " + count + " time(s)");
for(int i = 1; i < parsenum - 1; i++) {
System.out.print(stringarray[i]);
}
System.out.println();
System.out.println("First position in which " + searchnum + " appears: " + stringinput.indexOf(searchnum));
System.out.println("Second position in which " + searchnum + " appears: " + stringinput.lastIndexOf(searchnum));
}
catch (FileNotFoundException exception) {
System.err.println("File not found, please try again");
main(null);
}
catch (Exception e) {
System.err.println("Invalid input entered");
e.printStackTrace();
System.exit(0);
}
finally {
reader.close();
}
}
}
while((stringinput = reader.readLine()) != null)
The above while loop will run untill reader.readLine is null and so will be stringinput.
Now after the while loop your using stringinput:
stringinput.indexOf(searchnum)
stringinput.lastIndexOf(searchnum)
and thus getting the NullPointerException.

How do I get the list of numbers off of a file that the user inputs in Java?

I am using Java eclipse and I would like to have the user input the filename to retrieve a list of scores from the file. My goal is to take the average of those numbers. What line of code do I need just to get the user to input a file name and for the program to take those numbers so that I can compute with them? Currently I can have the user input scores, But I need to get the numbers from the file instead. I have visited numerous resources on this site. Here are a few:
BufferedReader, Error finding file, Getting a list from a file
package Average;
/**An average of scores*/
import java.util.Scanner;
public class Average2 {
public static void main(String[] args) {
int grade = 0;
int students = 0;
float total = 0;
double average = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students: ");
students = input.nextInt();
if (students <= 10) {
System.out.println("Enter the grades of the students: ");
for(int i = 0; i < students; i++) {
do {
grade = input.nextInt();
} while(grade < 0 || grade > 100);
total += grade;
}
average = (total/students);
int median = ((82+84)/2);
System.out.println("The average is " + average);
System.out.println("The mean is " + median);
}
}
}
Update since above post!
package trials;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class trials2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
// Grab the name of the file
System.out.println("Enter filename: ");
String fileName = in.next();
// Access the file
Scanner fileToRead = new Scanner(new File(fileName));
// While there is still stuff in the file...
double sum = 0;
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble()) {
sum += fileToRead.nextDouble();
} else {
fileToRead.next();
}
}
{
fileToRead.close();
}
System.out.println(sum);
}
}
The results I get from this:
Enter filename:
esp.txt <--entered by me
501.0
Given that you want to find the average of numbers in a file, you could do something like this:
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
// Grab the name of the file
System.out.println("Enter filename: ");
String fileName = in.next();
// Access the file
Scanner fileToRead = new Scanner(new File(fileName));
// Initialize our relevant counters
double sum = 0.0;
int numStudents = 0;
// While there is still stuff in the file...
while (fileToRead.hasNext()) {
// Is this next line consisting of just a number?
if (fileToRead.hasNextDouble()) {
// If it is, accumulate
sum += fileToRead.nextDouble();
numStudents++;
}
else { // Else, just skip to the next line
fileToRead.next();
}
}
// Close the file when finished
fileToRead.close();
// Print the average:
System.out.println("The average mark is: " + (sum / numStudents));
This code will create a new Scanner object that will read input from your keyboard. Once it does that, you type in the file name, and it gets access to this file by opening another Scanner object. After that, we initialize some counters to help us calculate the average. These are sum, which will add up all of the marks we encounter and numStudents, which keeps track of how many students there are in the file.
The while loop will keep looping through each line of this file until it reaches the end. What is important is that you check to see whether or not the line you are reading in next consists of a single number (double). If it is, then add this to our sum. If it isn't, skip to the next line.
Once you're finished, close the file, then display the average by taking the sum and dividing by the total number of students we have encountered when reading the numbers in the file.
Just took a look at your profile and your profile message. You have a long road ahead of you. Good luck!
Look at the Java tutorial on Scanning: http://docs.oracle.com/javase/tutorial/essential/io/scanning.html, particularly the ScanSum example. It shows how to scan double values from a text file and add them. You should be able to modify this example for your project.
Scanner userInput = new Scanner(System.in);
System.out.println("ENter filename");
String fileName = userInput.next();
Scanner fileScan = new Scanner(new File(fileName));
then use scanner methods to process lines or string tokens you are interested in.

storing a sentence from a file to a string java

How can I store a sentence from a file to a string, and then store the next line, which is made up of numbers, to a string?
When I use hasNextline or nextLine, none of it works. I am so confused.
Scanner kb = new Scanner(System.in);
String secretMessage = null;
String message, number = null;
File file = new File(System.in);
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext())
{
message = inputFile.nextLine();
number = inputFile.nextLine();
}
System.out.println(number + "and " + message);
You're looping over the entire file, overwriting your message and number variables, and then just printing them once at the end. Move your print statement inside the loop like this so it will print every line.
while(inputFile.hasNext())
{
message = inputFile.nextLine();
number = inputFile.nextLine();
System.out.println(number + "and " + message);
}
One suggestion I would have for reading lines from a file would be to use the Files.readAllLines() method.
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class Display_Summary_Text {
public static void main(String[] args)
{
String fileName = "//file_path/TestFile.txt";
try
{
List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
String eol = System.getProperty("line.separator");
for (int i = 0; i <lines.size(); i+=2)
{
System.out.println(lines.get(i).toString() + "and" + lines.get(i+1) + eol);
}
}catch(IOException io)
{
io.printStackTrace();
}
}
}
Using this set up, you can also create a stringBuilder and Writer to save the output to a file very simply if needed.

Categories

Resources