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.
Related
Write the complete java program called Temperature that includes a for loop structure, prompting the user to enter 5 temperature values. The program should add up each temperature entered within the loop and this is stored in a variable called total. Using a system statement, output the total temperature value and the average temperature value. Use the sample output below as a guide:
The total temperature =
The average temperature =
My answer is the statement below but im still getting errors:-
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner temp = new Scanner (System.in);
double total = 0;
for(int=1;int<=5;int++);
{
System.out.println ("Enter temperature #" + temp +":");
double temperature = temp.nextDouble ();
total = temperature;
}
System.out.println("The total temperature =" +total);
System.out.println("The average temperature=" +(double)(total/5));
}
}
The OP does not state what errors you are getting exactly, but I can guess some of them are from:
for(int=1;int<=5;int++);
You cannot use int like that. It is a type and should be used like the following:
for(int itr = 1; itr <= 5; itr++) { ...
Also, the semi-colon on your for loop doesn't need to be there.
for(int i=1;i<=5;i++) {
System.out.println ("Enter temperature #" + temp +":");
double temperature = temp.nextDouble ();
total += temperature;
}
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 am in the process of writing code that asks the user for their name, how many jobs they have, and the income of those jobs. Then the code finds the highest and lowest paying incomes, and the average of the jobs they entered.
Im having issues with the highest and lowest paying portion, along with finding the average, while still maintaining what the user entered in order to recite it later.
Ex:
Inputs: 10000 30000 50000
"Hello Audrey. You have had 3 jobs. The highest paying job paid $50000. The lowest paying job paid $10000. The average pay for the jobs entered is $30000
**** heres the code I have edited, but it is not running properly. I believe it has to do with int and double. Im not sure which code should be double and which ones should be int.****
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class JobIncome {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner (System.in);
System.out.println("What is your first name? ");
String firstName = input.nextLine();
Scanner scan = new Scanner (System.in);
System.out.println("How many jobs have you had? ");
int jobNum = scan.nextInt();
//Declarations
int total = 0;
int average = 0;
//for loop asks for the incomes of the user's previous
//jobs and stores them into an array
int arrayOfIncomes[] = new int[jobNum];
for(int i = 1; i <= arrayOfIncomes.length; i++){
System.out.println("Enter the income of job #" + i + " : ");
arrayOfIncomes[i] = scan.nextInt();
total = total + arrayOfIncomes[i];
}
average = total/jobNum;
//Start of the code that will find the min and max
int min = arrayOfIncomes[0];
int max = arrayOfIncomes[0];
for (int i = 1; i < arrayOfIncomes.length; i++) {
if (arrayOfIncomes[i] > max) {
max = arrayOfIncomes[i];
}
}
for (int i = 1; i < arrayOfIncomes.length; i++) {
if (arrayOfIncomes[i] < min) {
min = arrayOfIncomes[i];
}
}
//Print statement that gives the user all their information
System.out.println("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");
//Prompt asking the user if they would like to print their info into a text file
System.out.println("Would you like to output your information into a text file, yes or no? ");
String yesNo = input.nextLine();
if(yesNo.equals("yes")){
System.out.println("");
} else {
System.out.println("Goodbye.");
}
//Output code
Scanner console = new Scanner(System.in);
System.out.print("Your output file: ");
String outputFileName = console.next();
PrintWriter out = new PrintWriter(outputFileName);
//This code prints the information into the output text file
out.print("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");
out.close();
}
Fix the code by instantiating an array, jobIncomes with the length equivalent to the number of jobs. You could keep a running average, but you would lose precision when rounding. You will also need to instantiate three integer variables: total, max and min, each at zero.
For every iteration of the loop, you should add the following code:
jobIncomes[i-1]=s.nextInt();
if (jobIncomes[i-1]<min)
{ min=jobIncomes[i-1];}
if (jobIncomes[i-1]>max
{max=jobIncomes[i-1];}
total+=jobIncomes[i-1];
When you print the average, you can cast the formula average = total/jobNum. You might also want to change the array values to read from 0 to jobNum-1, if you want to index simply by i in the if statements.
Create an int variable sum. Add the sum as you get input from the user then divide the sum with the variable jobNum while casting at least one variable to double.
Example:
double ave = (double) sum / jobNum;
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);