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
Related
So I wrote this code that reads the User's lowest and highest float number. However, it reads the highest number fine, but it doesn't read the lowest number. I'm not
sure what I did wrong.
public static void main(String []args)
{
float cat=(float) 0.0;
float highest = (float) 0.0;
float lowest = (float) 0.0;
Scanner scan = new Scanner(System.in);
for (double i=0.00; i<2; i++) {
System.out.print("Enter a number:");
cat = scan.nextFloat();
if (cat > highest) {
highest = cat;
}
else if(cat < lowest) {
lowest = cat;
//I think it has something to do with the line above with lowest=cat
}
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
}}
The test for highest and lowest are independent. You should not have an "else" joining them.
You should also consider what would happen if all the number are negative.
First, initialize highest with a value lower than anything the user is likely to enter (and lowest with a value greater than anything the user is likely to enter). You don't use i other than as a loop counter, so I would make it an int. You don't use cat except as a local variable containing the current user input (so I would limit the scope to the loop body). Finally, you can use Math.max(float, float) and Math.min(float, float) to simplify your logic. Like,
public static void main(String[] args) {
float highest = Float.MIN_VALUE;
float lowest = Float.MAX_VALUE;
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
System.out.print("Enter a number:");
float cat = scan.nextFloat();
highest = Math.max(highest, cat);
lowest = Math.min(lowest, cat);
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
}
You always compare your input with lowest value 0.your code will only show exact output when you will take negative value input but not for positive one. here is the exact solution of your code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float cat=(float) 0.0;
float highest = (float) 0.0;
float lowest = (float) 0.0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number:");
cat = scan.nextFloat();
highest=cat;
lowest=cat;
//assignt first input to both so it can compare with next input
for (int i=0; i<(number_of_input -1); i++) { //here i compare with (number of input -1) beacuse you have already taken a input before
System.out.print("Enter a number:");
cat = scan.nextFloat();
if (cat > highest) {
highest = cat;
//System.out.println("Highest number is: " + highest);
}
else if(cat < lowest) {
lowest = cat;
//System.out.println("Lowest number is: " + lowest);
}
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
}
}
I'm writing a program where at the end I have to display the numbers I entered and the maximum and minimum of those entered numbers. However I'm running into a little problem, here is my code,
import java.util.*;
public class question3controlstructures {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
numbersinput ++;
System.out.println("do you want to enter another number?");
answer = in.next();
sum = sum + numberEntered;
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
}
}
The above comment are absolutely useful. However, here is little code
package com.mars;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Question3controlstructures {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (scan.hasNextInt()) {
list.add(scan.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
int sum = 0;
int i = 0;
for ( ; i < nums.length; i++) {
sum = sum + nums[i];
}
System.out.println("sum..." + sum);
System.out.println("The average is: " + sum / i);
System.out.println(i);
System.out.println("max.. "+Collections.max(list));
System.out.println("min.. "+Collections.min(list));
scan.close();
}
}
As suggent in comments , you need a list to store the multiple numbered entered.
just compare the min and max every time you enter a number
int min = Integer.MAX_VALUE
int max = Integer.MIN_VALUE
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
System.out.println("YOU HAVE ENTERED: " + numbersEntered);
if (min > numberEntered) min = numberEntered;
if (max < numberEntered) max = numberEntered;
numbersinput ++;
sum = sum + numberEntered;
System.out.println("do you want to enter another number?");
answer = in.next();
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
//you can print your min max here.
The IntSummaryStatistics class together with Java 8's Stream API may be less verbose than dealing with min, max, sum and avg calculation manually.
public static void main(String[] args) {
// Get user input.
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
// No user friendly way to gather user input, improve!
numbers.add(scanner.nextInt());
}
// Transform input to statistics.
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer.intValue()));
// Print statistics.
String jointNumbers = numbers.stream()
.collect(Collectors.joining(", "));
System.out.printf("You entered %d numbers: %s\n, stats.getCount(), jointNumbers);
System.out.println("Min: " + stats.getMin());
System.out.println("Max: " + stats.getMax());
System.out.println("Sum: " + stats.getMax());
System.out.println("Avg: " + stats.getAverage());
}
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.
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);
I need to Skip over text or integers. It reads a .dat file that has numbers (int/doubles) and strings in it. It also Calculates and prints max, min, sum, and the count of the number of words in the file. How do I do the average? Thank you!!
import java.io.*;
import java.util.*;
public class ProcessFile {
public static void main(String [] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.print("Enter file name: ");
String n = console.next();
File f = new File(n);
while(!f.exists()){
System.out.print("Doesn't exist. Enter a valid filename: ");
n = console.next();
f = new File(n);
}
Scanner input = new Scanner(f);
int minInt = Integer.MAX_VALUE;
int maxInt = Integer.MIN_VALUE;
int countInt;
int averageInt =
double minDouble = Double.MIN_VALUE;
double maxDouble = Double.MAX_VALUE;
double countDouble;
double averageDouble = //sum / countDouble
while(input.hasNext()){
if (input.hasNextInt()){
int next = input.nextInt();
maxInt = Math.max(next, maxInt);
minInt = Math.min(next, minInt);
countIntC++;
averageInt =
System.out.println("The results for the integers in the file :");
System.out.printf(" Max = %d\n", maxInt);
System.out.printf(" Min = %d\n", minInt);
System.out.printf(" Count = %d\n", countInt);
System.out.printf(" averageInt = %d\n", averageInt);
} else if (input.hasNextDouble()) { //can I read it as a double
double = next2 = input.nextDouble();
maxDouble = Math.max(next2, maxDouble);
minDouble = Math.min(next2, minDouble);
countDouble++;
averageDouble =
System.out.println("The results for the integers in the file:");
System.out.printf(" Max = %f\n", maxDouble);
System.out.printf(" Min = %f\n", minDouble);
System.out.printf(" Count = %f\n", countDouble);
System.out.printf(" averageInt = %f\n", averageDouble);
} else { //it is String
}
}
}
}
I see three problems
1) you need to initialize countDouble
countDouble = 0;
you're trying to do this countDouble++ before it's been ititialized
2) double = next2 = input.nextDouble();
I believe should be this
double next2 = input.nextDouble();
3) there no such variable countIntC
you're trying to countIntC++
should be countInt++
To calculate, I think you want to do this
averageInt = (maxInt + minInt) / countInt; // I THINK, depending on your logic
All in all, I have a feeling there's alot going on in your code, that can be thrown out.