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);
Related
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
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.
The question gives 6 integers in a file, separated into lines:
5
2
3
1
3
2
The 1st line describes the total number of days, and the others describe the number of hours per day. I am supposed to print the total number of days and the average number of hours. Here is my code below:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class IFeelFine
{
public static void main(String[] args) throws IOException
{
File file = new File("Tax.txt");
Scanner in = new Scanner(file);
double count = in.nextInt();
double total = 0;
for (double i = 0; i < count; i++)
{
total += in.nextDouble();
}
double avg = total / count;
System.out.println("Total vacation time missed: " + total + " hours");
System.out.println("Average daily time missed: " + avg + " hours");
}
}
When I run this code, I get the following error message in Eclipse.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at IFeelFine.main(IFeelFine.java:15)
What does that mean, and what do I have to fix to let the program run?
Any help would be much appreciated.
Here is your solution
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class IFeelFine
{
public static void main(String[] args) throws IOException
{
File file = new File("Tax.txt");
Scanner in = new Scanner(file);
double total = 0;
double avgTotal = 0;
double counter = 0;
int line = 0;
while (in.hasNext())
{
if(line%2==0)
{
total += in.nextDouble();
}
else
{
avgTotal += in.nextDouble();
counter ++;
}
line++;
}
double avg = avgTotal / counter;
System.out.println("Total vacation time missed: " + total + " hours");
System.out.println("Average daily time missed: " + avg + " hours");
}
}
Your answer works just fine. Here is the testing result:
Total vacation time missed: 11.0 hours
Average daily time missed: 1.6666666666666667 hours
This is correct according to your rule to calculate these values.
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;
}
}
}
I would like to ask why I am getting an InputMismathException?
I have declared a variable of type double and when I assign it a point value e.g.(4.6) it throws me:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at Exercises.ComputingMeanAndStandartDeviation_5_21.main(ComputingMeanAndStandartDeviation_5_21.java:18)
Here is the code:
package Exercises;
import java.util.*;
public class ComputingMeanAndStandartDeviation_5_21
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double sum = 0;
double number = 1;
double counter = 1;
System.out.println("Enter ten numbers: ");
while(counter<10)
{
number = input.nextDouble();
sum +=number;
counter ++;
}
System.out.println(sum + " " + number + " " + counter);
double mean = sum / counter;
System.out.println("The mean is: " + mean);
}
}
Problem in locale
Locale.setDefault(Locale.US);
Scanner input = new Scanner(System.in);
US decimal delimiter "."(78.12) and not ","(78,12)