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

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());
}

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.

Array storage Java

I want my array of students to have their name and grade associated. So when I call on them after the fact I can display the top two performing students. This is homework So I don't need to have the whole code completed but I would like some help with making sure the inputs are properly stored. Right now my variables are x and i, x being the number of students, and i being the counter. Again my issues are with associating the grades of the students inputted with the names. I hope there is enough information.
import java.util.Scanner;
public class Q3 {
public static void main(String[] args) {
int x = 0;
double average = 0;
int i = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please eneter how many students you have: ");
x = in.nextInt();
int students = 0;
int sum = 0;
int grades[] = new int[x];
String[] names = new String[x];
for(i = 0; i <= x; i++) {
System.out.println("Please enter student name: ");
String name = in.nextLine();
names[i] = name;
System.out.println("Grade: ");
int grade = in.nextInt();
grades[i] = grade;
students++;
sum += grade;
x++;
}
if(students>0) {
average = (double) sum/students;
}
System.out.println("The average is " + average);
System.out.println("There are " + students + " students");
System.out.println("The top two students are: " + grades);
}
}
The problem with your current code is that the for loop will never end, as you keep increasing the value of x, which is also used in the end condition.
Here are some suggestions:
Just store the number of students when you read it and remove the x variable:
int students = in.nextInt();
int grades[] = new int[students ];
String[] names = new String[students ];
Then read in this number of sudents:
for(i = 0; i < students; i++) {
To find the top two students you'd use the following logic (assumes 2 or more students)
if grade[0] >= grade[1]
max1 = 0
max2 = 1
else
max1 = 1
max2 = 0
for i from 2 to students-1
if grade[i] >= grade[max1]
max2 = max1
max1 = i
else if grade[i] > grade[max2]
max2 = i
The top two students are then at positions max1 and max2 in the names and grades array.
Probably overkill, but maybe someone will find it useful.
I store all the students in a TreeSet. I assume that each student has a unique name. I use a special Comparator to sort the students in the TreeSet according to their grades. A descending Iterator of the TreeSet will return the students from highest grade to lowest grade, so the first two items returned by this Iterator are the top two students.
import java.util.Comparator;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
/**
* A student name and her grade.
*/
public class StudentGrade {
/** Name of student. */
private String studentName;
/** Grade for this student. */
private int studentGrade;
/**
* Creates and returns instance of this class.
*
* #param name - student name
* #param grade - student grade
*/
public StudentGrade(String name, int grade) {
studentName = name;
studentGrade = grade;
}
/**
* #return Student's name.
*/
public String getStudentName() {
return studentName;
}
/**
* #return Student's rgade.
*/
public int getStudentGrade() {
return studentGrade;
}
/**
* Two instances of this class are equal if they both have the same name.
*/
#Override // java.lang.Object
public boolean equals(Object obj) {
boolean isEqual = false;
if (obj != null) {
Class<?> objClass = obj.getClass();
if (objClass.equals(getClass())) {
StudentGrade other = (StudentGrade) obj;
isEqual = studentName.equals(other.getStudentName());
}
}
return isEqual;
}
#Override // java.lang.Object
public int hashCode() {
return studentName.hashCode();
}
#Override // java.lang.Object
public String toString() {
return String.format("%s [%d]", studentName, studentGrade);
}
/**
* Start here.
*/
public static void main(String[] args) {
// Stores all student grades, sorted by grade in ascending order.
TreeSet<StudentGrade> studentSet = new TreeSet<>(new StudentGradeComparator());
Scanner in = new Scanner(System.in);
System.out.print("Please enter how many students you have: ");
int students = in.nextInt();
int index = students;
int sum = 0;
while (index > 0) {
// make sure we consume the newline character since 'nextInt()' does not
in.nextLine();
System.out.print("Enter student name: ");
String name = in.nextLine();
System.out.printf("Enter grade for %s: ", name);
int grade = in.nextInt();
sum += grade;
StudentGrade sg = new StudentGrade(name, grade);
studentSet.add(sg);
index--;
}
double average;
if (students > 0) {
average = (double) sum / students;
}
else {
average = 0.0d;
}
System.out.println("The average is " + average);
String verb = students == 1 ? "is" : "are";
String plural = students == 1 ? "" : "s";
System.out.printf("There %s %d student%s.%n", verb, students, plural);
if (students > 1) {
Iterator<StudentGrade> iter = studentSet.descendingIterator();
System.out.printf("The top two students are: %s, %s%n", iter.next(), iter.next());
}
}
}
/**
* Compares 'StudentGrade' instances according to their grades.
*/
class StudentGradeComparator implements Comparator<StudentGrade> {
/**
* Returns a positive number if 'sg1' grade is larger than that of 'sg2'.
* Returns a negative number if 'sg1' grade is less than that of 'sg2'.
* Returns zero if 'sg1' grade is equal to 'sg2' grade.
*/
#Override
public int compare(StudentGrade sg1, StudentGrade sg2) {
if (sg1 == null) {
if (sg2 != null) {
return -1;
}
else {
return 0;
}
}
else {
if (sg2 == null) {
return 1;
}
else {
return sg1.getStudentGrade() - sg2.getStudentGrade();
}
}
}
}
Here is a sample run:
Please enter how many students you have: 3
Enter student name: George
Enter grade for George: 70
Enter student name: Diego
Enter grade for Diego: 90
Enter student name: Edson
Enter grade for Edson: 65
The average is 75.0
There are 3 students.
The top two students are: Diego [90], George [70]

Printing 3 decimal numbers for a double [duplicate]

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));

Calculate average value in array

I am working on a project in Java that requests user inputs information like name, id, score in array.I need to help about calculate a average grade that user input and how to find out who have highest score. Here is my code:
package finalproject;
import java.util.Scanner;
public class FinalProject {
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Cis84[] student = new Cis84[50];
int option;
for (int c = 0; c < 50; c++)
student[c] = new Cis84();
do {
System.out.print("");
System.out.println("1) Add Information");
System.out.println("2) Show report");
System.out.println("3) Exit");
System.out.print("\nEnter option: ");
option = input.nextInt();
switch (option) {
case 1:
String n;
double g;
int index,
i;
System.out.println("Which position of the student?");
index = input.nextInt();
System.out.println("What is the student's name:");
n = input.nextLine();
n = input.nextLine();
System.out.println("What is student's Id");
i = input.nextInt();
System.out.println("What is student's score");
g = input.nextDouble();
student[index].setName(n);
student[index].setGrade(g);
student[index].setId(i);
break;
case 2:
for (int c = 0; c < 50; c++)
System.out.println(student[c]);
break;
case 3:
System.out.println("You are done");
break;
default:
System.out.println("Try again");
break;
}
} while (option != 3);
}
}
and class
package finalproject;
public class Cis84 {
private String name;
private int id;
private double grade;
public Cis84() {
name = "not input yet";
id = 00000;
grade = 0.0;
}
public Cis84(String n, int i, double g) {
name = n;
id = i;
grade = g;
}
public void setName(String n) {
name = n;
}
public void setId(int i) {
id = i;
}
public void setGrade(double g) {
grade = g;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public double getGrade() {
return grade;
}
public String toString() {
return String.format("%s\n%d\n%.2f\n", name, id, grade);
}
}
This is for homework, clearly, and I don't feel comfortable giving you a straight answer. However, what you will want to do is when it is time to display the averages, go through the entire students array and sum up the scores, then divide by the size of the array, likely using a for loop. You could keep track of the size of the array by having a counter increased anytime option 1 of the switch-case is called.
To find the highest score, you should be able to use the average-calculation for loop mentioned above, and check the grade against the previous highest grade. Record the index of whichever has the highest grade and print it out.
Have some pseudocode!
for(size of array which isn't NULL){
add indexed grade to sum;
check to see if this index has the highest grade;
}
display (sum/size); //the average
display highest grade;
calculating average would be something like the below code. Remember, average is the sum of all the values divided by the total number of values
double sum = 0, divisor = 0;
for (int k = 0; k < student.length; k++){
sum += student[k].getGrade();//add up all the grades
divisor = k;//get the number of total items
}
return sum/divisor; //divide
private static double calculateAverage(Cis84[] students) {
double sum = 0;
for (Cis84 student : students) {
sum += student.getGrade();
}
return sum / students.length;
}
private static double calculateHighestScore(Cis84[] students) {
double highestScore = 0;
for (Cis84 student : students) {
if (student.getGrade() > highestScore) {
highestScore = student.getGrade();
}
}
return highestScore;
}
Then, to show the information:
case 2:
System.out.println("Average:");
System.out.println(calculateAverage(student));
System.out.println("Highest score:");
System.out.println(calculateHighestScore(student));

Cannot run the Threshold correctly Java

Main.java
import java.util.*;
public class Main{
static Student[] students = new Student[10];//creates an array of 10 students to be entered
public static int inputThreshold(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Threshold: \n");
int threshold = scan.nextInt();
return Threshold();
}
public static Student inputStudent(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter students surname: \n");//instructs the user to enter a surname
String name = scan.nextLine();//allows the user to input sdtudents surname
System.out.println("Enter student score between 0 and 30: \n");
int score = scan.nextInt();//allows the user to input students score
return new Student(name, score);
}
public static void printStudent(Student student){
int percentage = student.getScore()*10/3;//retrieves the percentage of the score submitted out of 30
System.out.println("Surname: " + student.getName() + " Score: " + student.getScore() + " Percentage: " + percentage + "%");
//prints out the surname, score and percentage achieved by the student
}
public static void printThreshold(int threshold){
int percentage = student.getScore()*10/3;//retrieves the percentage of the score submitted out of 30
if (percentage < threshold){
System.out.println("Surname: " + student.getName() + " Score: " + student.getScore() + " Percentage: " + percentage + "%");
//prints out the surname, score and percentage achieved by the student
}
}
public static Student getWinner(Student[] student){
Student x = student[0];
for(int i = 1; i < 10; i++){
if(student[i].getScore() > x.getScore()){
x = student[i];
}
}
return x;
}
public static void main(String[] args){
for (int i = 0; i = 1; i++){
threshold = inputThreshold;
}
for (int i = 0; i < 10; i++){
students[i] = inputStudent();
}
for(int i = 0; i < 10; i++){
printStudent(students[i]);
}
for(int i= 0; i < 1; i++){
printThreshold(students[i]);
}
Student winrar = getWinner(students);//retrieves the winner from getWinner into a variable
System.out.println("AND WE HAVE OUR WINNER! \n" + "Name: " + winrar.getName() + " Score: " + winrar.getScore());
//prints out the highest scoring students surname, with their score
}
}
Student.java
public class Student{
private String name;//sets name to characters
private int score;//sets score to numbers
private int threshold;//sets the threshold of the score
private int max = 30;//sets max score to 30
public Student(String name, int score){
this.name = name;
if (score <= max && score >= 0) //if the score is equal to 30 or less than 0
this.score = score;//the score can be stored
else{
System.out.println("This number is too big ");//if it is larger than 30 it cannot be stored and shows errors message
System.exit(1);//this will end the program
}
}
public String getName(){
return name;
}
public int getScore(){
return score;
}
public int getThreshold(){
return threshold;
}
public void setScore(int s){
this.score = s;
}
public void setName(String n){
this.name = n;
}
public void setThreshold(int t){
this.threshold = t;
}
}
Is returns Cannot Find Symbol - method Threshold()
I'm not sure what to refer to or how to call the method to get it to run correctly. Brief: 10 users, 10 scores. There's a threshold to be achieved by each entrant. The program outputs their names, scores achieved and the percentage of their score. But it should also announce the overall winner.
Not sure here
return Threshold();
should be
return threshold;
change Threshold() to threshold.
I strongly advice you to read this article before writing another program
Objects, Instance Methods, and Instance Variables
public static int inputThreshold(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Threshold: \n");
int threshold = scan.nextInt();
return Threshold();
}
public static void main(String[] args){
for (int i = 0; i = 1; i++){
threshold = inputThreshold;
}
...rest of code in main
}
threshold is a local variable defined in inputStudent(), you can't access it in main() .Also return Threshold();, there is no Threshold() method defined in the code you've provided

Categories

Resources