Printing 3 decimal numbers for a double [duplicate] - java

This question already has answers here:
Best way to Format a Double value to 2 Decimal places [duplicate]
(2 answers)
Closed 5 years ago.
I am supposed to find the average of a bunch of given numbers after adding all of them up then dividing by the number of numbers given to me and the average must have 3 decimal numbers so for instead of 45.0 it would be 45.000 and mine works but only if the last number is not 0.
import java.util.Scanner;
import static java.lang.System.*;
public class Average
{
private String line;
private double average, sum, count;
public Average()
{
setLine("");
}
public Average(String s)
{
setLine(s);
}
public void setLine(String s)
{
line = s;
sum = 0.0;
count = 0.0;
average = 0.0;
}
public double getCount()
{
int num = 0;
while(num<line.length())
{
if(line.charAt(num) == 32)
{
count ++;
num ++;
}
else
num ++;
}
count ++;
return count;
}
public double getSum()
{
Scanner bobby = new Scanner(line);
while(bobby.hasNextInt())
sum = sum + bobby.nextInt();
return sum;
}
public double getAverage()
{
average = getSum()/getCount();
average = average*1000;
if(average%10>4)
{
average = Math.floor(average);
average ++;
average = average/1000.0;
}
else
{
average = Math.floor(average);
average = average/1000.0;
}
return average;
}
public String getLine()
{
return line;
}
public String toString()
{
return "";
}
}
This is my runner file
import java.util.Scanner;
import static java.lang.System.*;
public class AverageRunner
{
public static void main( String args[] )
{
String s = "9 10 5 20";
Average bob = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob.getAverage());
System.out.println();
s = "11 22 33 44 55 66 77";
Average bob1 = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob1.getAverage());
System.out.println();
s = "48 52 29 100 50 29";
Average bob2 = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob2.getAverage());
System.out.println();
s = "0";
Average bob3 = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob3.getAverage());
System.out.println();
s = "100 90 95 98 100 97";
Average bob4 = new Average(s);
System.out.println("Find the average of the following numbers :: "+s);
System.out.println("Average = " + " " + bob4.getAverage());
}
}

Use DecimalFormat:
DecimalFormat df = new DecimalFormat("#.000");
System.out.println("Nummber: " + df.format(1.2345));

Related

Receive average scores and check the number of scores in a range | Java

Write a java program that reads the grades of 10 students, which is from 1 to 100, from the entrance, specifying that the scores of some people are from 90 to 100, some people are from 60 to 89 and some people are from 1 to 59. The program should print the average scores at the end.
This is code for average, how can i add else and if or while to review how much numbers are in range 1 to 59 or 60 to 89 or 90 to 100?
import java.util.Scanner;
public class EhsanNp {
public EhsanNp() {
String getStr = getUserNums();
double result = userAvg(getStr);
printAverage(result, getStr);
}
public String getUserNums() {
Scanner in = new Scanner(System.in);
System.out.println("Please enter ten numbers separated by spaces: ");
return in.nextLine();
}
public static double userAvg(String str) {
String[] arr = str.split(" ");
double sum = 0.0;
double average = 0.0;
for (int i = 0; i < arr.length; i++) {
sum += Integer.parseInt(arr[i]);
}
if (arr.length > 0) {
average = sum / arr.length;
}
return average; // how do I get the program to count what to divide by since user can input 5- 10?
}
public static void printAverage(double average, String userNumInput) {
System.out.printf("The average of the numbers " + userNumInput + "is %.2f", average);
}
public static void main(String[] args) {
new EhsanNp();
}
}
You can simply add three variables which store the number of grades between 1 to 59, 60 to 89 and 90 to 100 and increment them in the for loop. For example:
import java.util.Scanner;
public class EhsanNp {
int lowGrades;
int middleGrades;
int highGrades;
public EhsanNp() {
lowGrades = 0;
middleGrades = 0;
highGrades = 0;
String getStr = getUserNums();
double result = userAvg(getStr);
printAverage(result, getStr);
}
public String getUserNums() {
Scanner in = new Scanner(System.in);
System.out.println("Please enter ten numbers separated by spaces: ");
return in.nextLine();
}
public static double userAvg(String str) {
String[] arr = str.split(" ");
double sum = 0.0;
double average = 0.0;
for (int i = 0; i < arr.length; i++) {
sum += Integer.parseInt(arr[i]);
if (Integer.parseInt(arr[i]) >= 1 && Integer.parseInt(arr[i]) <= 59) {
lowGrades++;
}
else if (Integer.parseInt(arr[i]) >= 60 && Integer.parseInt(arr[i]) <= 89) {
middleGrades++;
}
else {
highGrades++;
}
}
if (arr.length > 0) {
average = sum / arr.length;
}
return average; // how do I get the program to count what to divide by since user can input 5- 10?
}
public static void printAverage(double average, String userNumInput) {
System.out.printf("The average of the numbers " + userNumInput + "is %.2f", average);
}
public static void main(String[] args) {
new EhsanNp();
}
}
Then you can do whatever you want with the variables like displaying them for example.

I couldn't get average, largest and smallest value from text file

Why couldn't I calculate all the integer value in my score.txt file to get the average, smallest and largest result printed on to the console correctly?
Task is to store each record(name and score) in an array and able to process the array of the objects to determine:
The average of all scores
The largest score and
The smallest score
my score.txt file :
name: score:
James 10
Peter 40
Chris 20
Mark 24
Jess 44
Carter 56
John 21
Chia 88
Stewart 94
Stella 77
My Source code:
public class Q2
{
private String name = "";
private int point = 0;
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//prompt user for input file name
System.out.println("Enter file name: ");
String findFile = keyboard.next();
//invoke readString static method
readFile(findFile);
//output the file's content
System.out.println(readFile(findFile));
}//end of main
public static String readFile(String file)
{
String text = " ";
try
{
Scanner scanFile = new Scanner(new File (file));
ArrayList<Q2> list = new ArrayList<Q2>();
String name = "";
int score = 0;
int count =0;
while(scanFile.hasNext())
{
name = scanFile.next();
while(scanFile.hasNextInt())
{
score = scanFile.nextInt();
count++;
}
Q2 data = new Q2(name, score);
list.add(data);
}
scanFile.close();
for(Q2 on : list)
{
on.calAverage();
on.smallAndLarge();
System.out.println(on.toString());
}
}
catch (FileNotFoundException e)
{
System.out.println("Error: File not found");
System.exit(0);
}
catch(Exception e)
{
System.out.println("Error!");
System.exit(0);
}
return text;
}//end of readFile
/**
* Default constructor for
* Score class
*/
public Q2()
{
this.name = "";
this.point = 0;
}
public Q2(String name, int point)
{
this.name = name;
this.point = point;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
this.point = point;
}
/**
* This calAverage void method is
* to compute the average of
* total point value
*/
public void calAverage()
{
double average = 0.0;
int sum = 0;
//compute the sum of point
sum += getPoint();
//compute the average of sum
average = sum / 10;
System.out.println("The Average score is " + average );
}//end of calAverage method
public void smallAndLarge()
{
int smallest = 0;
int largest =0;
smallest = point;
for(int index = 2; index < 11; index++)
{
if(point > largest)
largest = point;
if(point < smallest)
smallest = point;
}
System.out.println("The largest num is :" + largest);
System.out.println("The Smallest num is : " + smallest);
}
public String toString()
{
return String.format("\n%s %d\n", getName(), getPoint());
}
}
The output I got when invoked:
Enter file name:
scores.txt
The Average score is 1.0
The largest num is :10
The Smallest num is : 10
James 10
The Average score is 4.0
The largest num is :40
The Smallest num is : 40
Peter 40
The Average score is 2.0
The largest num is :20
The Smallest num is : 20
...etc...
What I want my program to output to:
The Average score is 47.4
The largest num is : 94
The Smallest num is : 10
If you have an array int[] scores, you can the IntSummaryStatistics class and its methods to calculate avg, min and max of the array like below:
int[] scores = { 10, 40, 20, 24, 44, 56, 21, 88, 94, 77 };
IntSummaryStatistics stats = IntStream.of(scores).summaryStatistics();
System.out.println(stats.getAverage()); //<-- 47.4
System.out.println(stats.getMin()); //<-- 10
System.out.println(stats.getMax()); //<-- 94
Using Java 8 collection framework:
public static void printResult(List<Q2> list)
{
IntSummaryStatistics summarizedStats = list.stream().collect(Collectors.summarizingInt(Q2::getPoint));
System.out.println("The Average score is " + summarizedStats.getAverage());
System.out.println("The largest num is :" + summarizedStats.getMax());
System.out.println("The Smallest num is : " + summarizedStats.getMin());
}

java: loop produces incorrect output when reading from file?

This loop is producing the average values of hours and amount paid, but the output is mathematically incorrect. How can I edit this code to produce the correct average hours value and average paid values?
Scanner openFile = new Scanner(inFile);
while (openFile.hasNext()) {
if (openFile.hasNextDouble()) {
totalHours += openFile.nextDouble();
numOfHourInputs++;
}
if (openFile.hasNextDouble()) {
totalPaid += openFile.nextDouble();
numOfCharges++;
}
else {
openFile.next(); }
}
averageHours = (totalHours/numOfHourInputs);
averagePaid = (totalPaid/numOfCharges);
Below is my file:
The first column is unimportant for calculating the averages. The second column contains the numbers of hours. The third column contains the charges.
This file can have more data added to it by the user - the values inside of the file can be changed.
a 10.0 9.95
b 10.0 13.95
b 20.0 13.95
c 50.0 19.95
c 30.0 19.95
Remove the else:
else {
openFile.next(); //this consumes all input
}
The following code
Double[][] values = {{10.0, 9.95},
{10.0, 13.95},
{20.0, 13.95},
{50.0, 19.95},
{30.0, 19.95}};
Double totalHours = 0.;
int numOfHourInputs = 0;
Double totalPaid = 0.;
int numOfCharges = 0;
for (final Double[] value : values) {
totalHours += value[0];
numOfHourInputs++;
totalPaid += value[1];
numOfCharges++;
}
final double averageHours = (totalHours / numOfHourInputs);
System.out.println("averageHours = " + averageHours);
final double averagePaid = (totalPaid / numOfCharges);
System.out.println("averagePaid = " + averagePaid);
produced the result
averageHours = 24.0
averagePaid = 15.55
so that it's clearly not a mathematical problem. Check your input code especially for the line
openFile.next();
You still need to skip the first token but in the right spot:
public static void main(String[] args)
{
double totalHours = 0.0;
int numOfHourInputs = 0;
double totalPaid = 0.0;
int numOfCharges = 0;
Scanner openFile = null;
try
{
openFile = new Scanner(new File("c:\\temp\\pay.txt"));
}
catch (Exception e)
{
throw new RuntimeException("FNF");
}
try
{
while (openFile.hasNext())
{
// skip the first token
String token = openFile.next();
if (openFile.hasNextDouble())
{
totalHours += openFile.nextDouble();
numOfHourInputs++;
}
if (openFile.hasNextDouble())
{
totalPaid += openFile.nextDouble();
numOfCharges++;
}
}
}
finally
{
openFile.close();
}
double averageHours = (totalHours/numOfHourInputs);
double averagePaid = (totalPaid/numOfCharges);
System.out.println("Total hours: " + totalHours);
System.out.println("Num hours input: " + numOfHourInputs);
System.out.println("----------------------------------------");
System.out.println("Average hours: " + averageHours);
System.out.println("");
System.out.println("Total payments: " + totalPaid);
System.out.println("Num payments input: " + numOfCharges);
System.out.println("----------------------------------------");
System.out.println("Average paid: " + averagePaid);
}
Here is the output that I get:
Total hours: 120.0
Num hours input: 5
----------------------------------------
Average hours: 24.0
Total payments: 77.75
Num payments input: 5
----------------------------------------
Average paid: 15.55

Calculating Avg, Max, and Min using a .txt input file with both integers and strings mixed

Please help. I've looked everywhere and am stumped on how to finish this program. I need to calculate the average, max, and min from a data input file. They need to look like this:
System.out.println("The average total score of the class is: " + total/27);
System.out.println(maxName + "got the maximum score of: " + maxVal);
System.out.println(minName + "got the maximum score of: " + minVal);
For the average I don't know why the while loop in my main isn't working. It calculates a value of zero. I also don't know how I can make it so the 27 isn't hard coded. For the max and min values, I have no clue about those. i don't even have a guess. A lot of things I've looked at for these use ways we haven't been taught (like a buffered something for instance, or using the Collections class which we haven't learned about that either. I just need a basic way of accomplishing these. I will include everything I have so far. Any help is appreciated. Thank you.
Input File:
9
Andy Borders
200
250
400
John Smith
120
220
330
Alvin Smith
225
300
278
Mike Borell
250
250
500
Jim Jones
325
325
155
Robert Fennel
200
150
350
Craig Fenner
230
220
480
Bill Johnson
120
150
220
Brent Garland
220
240
350
Main:
import java.util.Scanner;
import java.io.*;
public class Project5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the file name: ");
String fileName = in.nextLine();
try {
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
String SnumStudents = inputFile.nextLine();
int numStudents = Integer.parseInt(SnumStudents);
Student [] studentList = new Student[numStudents];
for (int i = 0; i < numStudents; i++)
{
String line = inputFile.nextLine();
String score1 = inputFile.nextLine();
String score2 = inputFile.nextLine();
String score3 = inputFile.nextLine();
studentList [i] = new Student(line, Integer.parseInt(score1), Integer.parseInt(score2), Integer.parseInt(score3));
}
System.out.println("Name\t\tScore1\tScore2\tScore3\tTotal");
System.out.println("---------------------------------------------");
for (int i=0; i< studentList.length;i++){
System.out.println(studentList[i].getName() + "\t" + studentList[i].getScore1() + "\t" + studentList[i].getScore2() + "\t" + studentList[i].getScore3() + "\t" + studentList[i].getTotal());
}
System.out.println("---------------------------------------------");
System.out.println("The total number of students in this class is: " + studentList.length);
int total = 0;
while (inputFile.hasNextInt())
{
int value = inputFile.nextInt();
total = total + value;
}
System.out.println("The average total score of the class is: " + total/27);
System.out.println(maxName + "got the maximum score of: " + maxVal);
System.out.println(minName + "got the maximum score of: " + minVal);
inputFile.close();
} catch (IOException e) {
System.out.println("There was a problem reading from " + fileName);
}
finally {
}
in.close();
}
}
Student Class:
public class Student {
private String name;
private int score1;
private int score2;
private int score3;
private int total;
private double average;
public Student(String n, int s1, int s2, int s3){
name = n;
score1 = s1;
score2 = s2;
score3 = s3;
total = s1 + s2 + s3;
}
public String getName(){
return name;
}
public int getScore1(){
return score1;
}
public int getScore2(){
return score2;
}
public int getScore3(){
return score3;
}
public int getTotal(){
return total;
}
public double computeAverage(){
return average;
}
}
Your while loop is never getting executed. By the time you finish reading lines of the file in your for loop, there are no more lines of the file to consume. So, inputFile.hasNextInt() is never true.
The 27 is hard-coded because of the line
System.out.println("The average total score of the class is: " + total/27);
You need to change the 27 here to some variable that will represent the total number of scores.
You are storing all of the scores for each person. To find the min (max) you just need to go through each of the values and find the smallest (largest) one and store them.

Java 2 dimensional arrays and average

Can someone please help me with this homework?
I have tried something but I'm not sure if my solution covers all the tasks.
I have to write a Java program, which initializes a two-dimensional array with the marks from the 5th semester (there are only 5 marks, as you know) of n students (the user should input the number of students).
The program should outputs as a result:
The average grade of all students for 5th semester;
The number of the student with the highest average grade;
The number of the student with the lowest average grade;
The number of students with an average grade greater than the average grade of all students;
The number of students with an average grade less than the average grade of all students;
The program should do data validation as follows: student’s marks should be between 2 and 6, and the number of students should not exceed 30.
and here is my solution so far :
package ocenki;
public static void main(String[] args) {
Scanner scan = new Scanner (System.in ) ;
System.out.println ("Enter notes here:") ;
double [] marks= new double [5] ;
for ( int i=0; i<=4; i++)
{
System.out.println ("Please, input mark for " + i +(" subject")) ;
marks[i] = scan. nextDouble () ;
while (marks[i]<2 || marks[i]>6)
{
System.out.println ("Please, input marks between 2 and 6:") ;
marks[i] = scan.nextDouble () ;
}
}
double sum=0;
double min=marks[0];
double max=marks[0];
for ( int i=0; i<=4; i++)
{
sum = sum+marks[i] ;
if(marks[i]>max)
{
max=marks[i];
}
if(marks[i]<min)
{
min=marks[i];
}
}
System.out.println("The average is " + sum/5 + ", the minimum is " + min + " and the maximum is " + max);
}
Please find the solution for your Q-4 AND Q-5
Solution
double avg= sum/5;
for ( int i=0; i<=4; i++)
{
if(marks[i]>avg)
{
moreAvg++;
}
if(marks[i]<avg)
{
lessAvg++;
}
}
FULL CODE -
public static void main(String[] args) {
Scanner scan = new Scanner (System.in ) ;
System.out.println ("Enter notes here:") ;
double [] marks= new double [5] ;
for ( int i=0; i<=4; i++)
{
System.out.println ("Please, input mark for " + (i+1) +(" subject")) ;
marks[i] = scan. nextDouble () ;
while (marks[i]<2 || marks[i]>6)
{
System.out.println ("Please, input marks between 2 and 6:") ;
marks[i] = scan.nextDouble () ;
}
}
double sum=0;
double min=marks[0];
double max=marks[0];
int lessAvg=1,moreAvg=0;
for ( int i=0; i<=4; i++)
{
sum = sum+marks[i] ;
if(marks[i]>max)
{
max=marks[i];
}
if(marks[i]<min)
{
min=marks[i];
}
}
double avg= sum/5;
for ( int i=0; i<=4; i++)
{
if(marks[i]>avg)
{
moreAvg++;
}
if(marks[i]<avg)
{
lessAvg++;
}
}
System.out.println("The average is " +avg + ", the minimum is " + min + " and the maximum is " + max);
System.out.println("4.The number of students with an average grade greater than the average grade of all students"+moreAvg);
System.out.println("5.The number of students with an average grade less than the average grade of all students"+lessAvg);
}

Categories

Resources