Calculate average of population data read from a text file - java

I wrote a program that processes population data from 1950 till 1990. I'm trying to get the average from a text file. Everything in the program compiles but I'm getting 0 for the output. Why isn't this working?
Here is the Java program I wrote:
import java.util.Scanner;
import java.io.*;
public class PopulationData
{
public static void main(String[] args) throws IOException
{
final int SIZE = 42;
int[] number = new int[SIZE];
int i = 0;
int total = 0;
int average;
File file = new File("USPopulation.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext() && i < number.length)
{
number[i] = inputFile.nextInt();
i++;
total += number[i];
}
average = total / number.length;
System.out.println("The average annual change in population is: " + average);
inputFile.close();
}
}
USPopulation.txt:
151868 153982 156393 158956 161884 165069 168088 171187 174149 177135 179979 182992 185771 188483 191141 193526 195576 197457 199399 201385 203984 206827 209284 211357 213342 215465 217563 219760 222095 224567 227225 229466 231664 233792 235825 237924 240133 242289 244499 246819 249623

Change this :
number[i] = inputFile.nextInt();
i++;
total += number[i];
to this :
number[i] = inputFile.nextInt();
total += number[i];
i++;

I'm trying to get the average from a text file everything in the
program complies but I'm getting 0 for the output.
You are doing integer division. Make average and total double instead of int.

Related

Java IO "NaN" issue

I have a file named Numbers.txt with the following content:
8.5
83.45, 90.2
120.00, 11.05
190.00
I have written code that uses the contents of the file to compute the sum and average of the numbers in the file however when I run the code, for the average the result is "NaN"
CODE:
package lab13;
import java.util.Scanner;
import java.io.*;
public class problem1 {
public static void main(String[] args) throws IOException
{
double sum = 0;
int count = 0;
double num,total = 0;
double average = total/count;
File file = new File("Numbers.txt");
Scanner scan = new Scanner(file);
while (scan.hasNext())
{
double number = scan.nextDouble();
sum = sum + number;
}
while (scan.hasNextDouble())
{
num = scan.nextDouble();
System.out.println(num);
count++;
total += num;
}
scan.close();
System.out.println("The sum of the numbers in " +
"Numbers.txt is " + sum );
System.out.println("The average of the numbers in " +
"Numbers.txt is " + average );
}
}
Output:
The sum of the numbers in Numbers.txt is 503.2
The average of the numbers in Numbers.txt is NaN
You need to do
double average = total/count;
after you have the values for total and count
But also note that
when while (scan.hasNext()) stream is exhausted then while (scan.hasNextDouble()) will also be exhausted
This can be overcome but just looping once

Trouble finding data from text file

I've been having trouble extracting the data from a text file and using it. I've got an assignment that requires me to get 10 doubles from the file and find the min, max, and average of the numbers. This is what I've got so far.
import java.util.*;
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
public class DataAnalysis
{
static double i;
public static void main(String args[])
{
double sum =0;
Scanner inputFile = new Scanner("input.txt");
double min = inputFile.nextDouble();
double max = inputFile.nextDouble();
for(i = inputFile.nextDouble(); i < 10; i++)
{
if(i < min)
{
min = i;
}
else
{
if(i > max)
{
max = i;
}
}
}
double average = sum/ 10;
System.out.println("Maximum: " + max);
System.out.println("Minimum: " + min);
System.out.println("Average: " + average);
}
}
It compiles just fine, but I get a Scanner InputMismatchException
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at DataAnalysis.main(DataAnalysis.java:20)
Any help with this would be appreciated!
It might be locale dependent. Decimal numbers are e.g written as 0,5 in Sweden.
Change your code so that it says e.g.:
Scanner scan = new Scanner(System.in);
scan.useLocale(Locale.US);

Having some trouble with File I/O

I have a homework assignment to read data from a file which contains names and scores per game of basketball players. The program is supposed to output the names and scores of the players, as well as tally each player's average score per game, and finally display the player with the highest average. I am currently stuck on trying to get the average and a newline character for each player.
Here is a pic of the input file I am reading the data from.
and here is my code:
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
public class BasketballTeam
{
public static void main(String[] args) throws IOException
{
File f = new File("BasketballData.txt");
if (f.exists())
{
Scanner input = new Scanner(f);
int games = 0;
int totalScore = 0;
double avg = 0.0;
while (input.hasNext())
{
String s = input.next();
System.out.printf("%-9s", s);
int a = input.nextInt();
while (input.hasNextInt())
{
if (a == -1)
{
avg = (double)totalScore/games;
System.out.printf("%14s%.2f\n", "Average of ", avg);
games = 0;
totalScore = 0;
s = input.next();
}
else
{
System.out.printf("%5s", a);
games++;
totalScore = totalScore + a;
a = input.nextInt();
}
}
}
}
}
}
When I run the program, my output is just a single line that looks like:
Smith 13 19 8 12Badgley 5Burch 15 18 16Watson......and so on
Why am I not getting any newline characters or my average? I want my output to look like this:
Smith 13 19 8 12 Average of 13
Badgley 5 Average of 5
Burch 15 18 16 Average of 16.33
.....and so on
Thanks in advanced for any suggestions/corrections.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class BasketballTeam
{
public static void main(String[] args) throws IOException
{
File f = new File("BasketballData.txt");
if (f.exists())
{
Scanner input = new Scanner(f);
int games = 0;
int totalScore = 0;
double avg = 0.0;
while (input.hasNext())
{
String s = input.next();
System.out.printf("%-9s", s);
while (input.hasNextInt())
{
int a = input.nextInt();
if(a != -1)
{
System.out.printf("%5s", a);
games++;
totalScore = totalScore + a;
}
}
avg = (double)totalScore/games;
System.out.printf("%14s%.2f\n", "Average of ", avg);
games = 0;
totalScore = 0;
System.out.println();
}
input.close();
}
}
}
This is what you are looking for. You don't even need the -1 at the end of each line in the file you can get rid of that if you want unless it is part of the specification. It will work without the -1. Your inner loop you just want to add up your totals then outside of the inner loop get your average and display. Then reset your variables. You were pretty close just needed to change a couple things. If you have any questions on how this works just ask away. Hope this helps!
Try
avg = ((double)totalScore/(double)games);
and replace \n with \r\n:
System.out.printf("%14s%.2f\r\n", "Average of ", avg);
I would highly recommend using a FileReader:
File file = new File("/filePath");
FileReader fr = new FileReader(file);
Scanner scanner = new Scanner(fr);
//and so on...
In this line a = input.nextInt(), you already advance to the next int, so the test input.hasNextInt() will be false when you reach -1.
One possible solution is to change the loop to:
while (input.hasNext()) {
String s = input.next();
System.out.printf("%-9s", s);
int a = 0;
while (input.hasNextInt()) {
a = input.nextInt();
if (a == -1) {
avg = (double) totalScore / games;
System.out.printf("%14s%.2f\n", "Average of ", avg);
games = 0;
totalScore = 0;
} else {
System.out.printf("%5s", a);
games++;
totalScore = totalScore + a;
}
}
}

Store ints into array from a file and find mean JAVA

In this program, you will find a menu with options to perform different functions on an array. This array is taken from a file called "data.txt". The file contains integers, one per line. I would like to create a method to store those integers into an array so I can call that method for when my calculations need to be done. Obviously, I have not included the entire code (it was too long). However, I was hoping that someone could help me with the first problem of computing the average. Right now, the console prints 0 for the average because besides 1, 2, 3 being in the file, the rest of the array is filled with 0's. The average I want would be 2. Any suggestions are welcome. Part of my program is below. Thanks.
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Calculation Program!\n");
startMenus(sc);
}
private static void startMenus(Scanner sc) throws FileNotFoundException {
while (true) {
System.out.println("(Enter option # and press ENTER)\n");
System.out.println("1. Display the average of the list");
System.out.println("2. Display the number of occurences of a given element in the list");
System.out.println("3. Display the prime numbers in a list");
System.out.println("4. Display the information above in table form");
System.out.println("5. Save the information onto a file in table form");
System.out.println("6. Exit");
int option = sc.nextInt();
sc.nextLine();
switch (option) {
case 1:
System.out.println("You've chosen to compute the average.");
infoMenu1(sc);
break;
case 2:
infoMenu2(sc, sc);
break;
case 3:
infoMenu3(sc);
break;
case 4:
infoMenu4(sc);
break;
case 5:
infoMenu5(sc);
break;
case 6:
System.exit(0);
default:
System.out.println("Unrecognized Option!\n");
}
}
}
private static void infoMenu1(Scanner sc) throws FileNotFoundException {
File file = new File("data.txt");
sc = new Scanner(file);
int[] numbers = new int[100];
int i = 0;
while (sc.hasNextInt()) {
numbers[i] = sc.nextInt();
++i;
}
System.out.println("The average of the numbers in the file is: " + avg(numbers));
}
public static int avg(int[] numbers) {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum = (sum + numbers[i]);
}
return (sum / numbers.length);
}
Just modify your method as follows:
public static int avg(int[] numbers, int len) where len is the actual numbers stored.
In your case you call:
System.out.println("The average of the numbers in the file is: " + avg(numbers, i));
And in your code for average:
for (int i = 0; i < len; i++) {
sum = (sum + numbers[i]);
}
I.e. replace numbers.length with len passed in
And do return (sum / len);
Instead of using a statically-sized array you could use a dynamically-sized List:
import java.util.List;
import java.util.LinkedList;
// . . .
private static void infoMenu1(Scanner sc) throws FileNotFoundException {
File file = new File("data.txt");
sc = new Scanner(file);
List<Integer> numbers = new LinkedList<Integer>();
while (sc.hasNextInt()) {
numbers.add(sc.nextInt());
}
System.out.println("The average of the numbers in the file is: " + avg(numbers));
}
public static int avg(List<Integer> numbers) {
int sum = 0;
for (Integer i : numbers) {
sum += i;
}
return (sum / numbers.size());
}
This has added the benefit of allowing you to read in more than 100 numbers. Since the LinkedList allows you to perform an arbitrary number of add operations, each in constant time, you don't need to know how many numbers (or even an upper-bound on the count) before reading the input.
As kkonrad also mentioned, you may or may not actually want to use a floating-point value for your average. Right now you're doing integer arithmetic, which would say that the average of 1 and 2 is 1. If you want 1.5 instead, you should consider using a double to compute the average:
public static double avg(List<Integer> numbers) {
double sum = 0;
for (Integer i : numbers) {
sum += i;
}
return (sum / numbers.size());
}
I think sum should be a double and double should be the return type of your avg function
Please change your average function in such a way
private static void infoMenu1(Scanner sc) throws FileNotFoundException {
.
.
.
System.out.println("The average of the numbers in the file is: " + avg(numbers,i));
}
public static int avg(int[] numbers,int length) {
int sum = 0;
for (int i = 0; i < length; i++) {
sum = (sum + numbers[i]);
}
return (sum / length);
}
While calling average function pass i (which you counted in infoMenu1 for number of entries in data.txt) as well and use that in loop and dividing the sum. with this your loop will not run for 100 iterations and code of lines also reduced.

Empty string in number formatting

This is my assignment:
Here are my questions:
How can I fix this error:
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1012)
at java.lang.Double.parseDouble(Double.java:527)
at extracredit.Main.readData(Main.java:72)
at extracredit.Main.main(Main.java:27)
Are there any other problems that you can see with this program?
Here's my code so far:
import java.io.*;
import javax.swing.JOptionPane;
import java.util.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
String fname = "data.txt"; //Read in the data file for use in the array
String pass= JOptionPane.showInputDialog("Please enter the " +
"password to continue:"); /*Have the user enter the password to
access the file. */
checkPass(pass); // Verify that the password is correct before continuing.
readData (fname); // Read data, print output and save output file.
}
private static void checkPass (String pass)
{
String password= "INF260";
int passCount= 0;
if (pass.equals(password)) {
System.out.println("The password is correct. Continuing...");
}
else {
do {
pass= JOptionPane.showInputDialog("Please re-enter the" +
"password:");
passCount++;
} while (!pass.equals(password) && passCount < 2);
if (!pass.equals(password)) {
System.out.println("You have tried to enter the " +
"password too many times. Exiting...");
System.exit(0);
}
else {
System.out.println("The password is correct. Continuing...");
}
}
}
public static void readData (String data) throws IOException{
FileReader inputData= new FileReader (data);
BufferedReader findNum= new BufferedReader (inputData);
String str= findNum.readLine ();
int count=-1;
int countNum= 0;
double total= 0;
double min= 0;
double max= 0;
double average= 0;
FileWriter writeFile = new FileWriter("sales.txt");
PrintWriter printFile = new PrintWriter(writeFile);
while (str != null)
{
double num= Double.parseDouble (str);
if (count == 0){
countNum++; // counter of Reciepts to use
}
str = findNum.readLine();
}
double [][] input = new double [countNum][10];
total= getCurrentTotal(input); /*This will get the total
from the method getCurrentTotal.*/
min= getCurrentMin(input); /*This will get the minimum value from
the method getCurrentMin.*/
max= getCurrentMax (input); /*This will get the maximum value from
the method getCurrentMax.*/
average= (total / countNum); //Calculate the average.
System.out.println("The List of Today's Sales:");
for (int row = 0; row < input.length; row++){
System.out.println ();
System.out.println("Customer " + row + "\t");
for (int column = 0; column < input[row].length; column++){
if (input [row].length < 10){
System.out.println(input[row][column] + "\t");
str = findNum.readLine();
}
else{
System.out.println ("There are too many receipts" +
" for one Customer.\n");
System.exit (0);
}
}
}
System.out.println ("There are " + countNum + "receipts in the list.");
/*This will print the total of receipts in the list.*/
System.out.println ("The total of today's sales is $" + total); /*
This will print the total of the sales for the day.*/
System.out.println ("The average of today's sales is $" + average); /*
This will print the average sale total.*/
System.out.println ("The highest receipt is $" + max); /* This will print
the highest sale.*/
System.out.println ("The lowest receipt is $" + min); /* This will print
the lowest sale.*/
Date date = new Date();
System.out.println ("\n The current time is:" + date.toString()); /* This
will print the current date and time */
}
public static double getCurrentTotal (double [][] input){
double totalAmount = 0;
for (int row = 0; row < input.length; row++){
for (int column = 0; column < input [row].length; column++){
totalAmount += input [row][column];
}
}
return totalAmount;
}
public static double getCurrentMin (double [][] input) {
double currentMin = input[0][0];
for (int row = 0; row < input.length; row++){
for (int column = 0; column < input [row].length; column++){
if (currentMin > input[row][column])
currentMin = input[row][column];
}
}
return currentMin;
}
public static double getCurrentMax (double [][] input){
double currentMax = input[0][0];
for (int row = 0; row < input.length; row++){
for (int column = 0; column < input [row].length; column++){
if (currentMax < input[row][column]){
currentMax = input[row][column];
}
}
}
return currentMax;
}
}
The best solution is:
study your course material
start with a subset of the problem like just reading the file.
test it
loop over:
continue to improve and enhance the program until it fulfills all the requirements.
test it
hand it in
// from your main method
String fname = "data.txt";
readData (fname);
// the method being called
public static void readData (String data[][]){
BufferedReader br = new BufferedReader(new FileReader(data));
We have an incompatibility here.
fname is a String
The method takes a String[] as a parameter.
the constructor newFileReader() takes a string, not 2d array.
All of these three should be the same data type.
How can I separate each "receipt" with zero (like shown in the image link above)?
You don't have to. You have to READ from that file with the zeros in it.
I would recommend you write a method something like this:
public double[] readOneReceipt(BufferedReader reader);
This method should
Read line by line until it encounters a 0 entry
for each entry it reads convert the value into a number (double?)
Store the number in a temporary structure.
When you encounter the "0", create a new array of the correct size and copy the read values into it.
How can I write the output into a separate file?
With a java.io.FileWriter
The hardest bit of this IMO is the fact that you are told to store the data in a 2d array, but you don't exactly what size to make the array until you've read the data.
Which means that you either use a temporary dynamic structure, or read the file twice - once to find out how many receipts there are so that you can make the array, and then again to actually read the receipt data.

Categories

Resources