How to get the sum of an Integer arraylist? - java

Basically Im trying to make a program that allows a teacher to input grades for a test for each student then after they've inputted the grades it gives the teacher a sum of all the grades they inputted
public static void grades(){
List<Integer> grade = new ArrayList<Integer>();
int gradetotal = IntStream.of(grades).sum;/* sum */
int gradelistnumber = 1;
int inputedgrade = 0;
while(inputedgrade != -1){
System.out.println("Enter Grade for student " + gradelistnumber + " (1-50): ");
inputedgrade = sc.nextInt();
grade.add(inputedgrade);
gradelistnumber++;
}
System.out.println("Class Average: " + gradetotal / 50 * 100);
}
I'm trying to figure out how to get the sum of the array list grades .

Here's how you sum a Collection using java 8:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String args[]) throws Exception {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(3);
numbers.add(5);
System.out.println(numbers.stream().mapToInt(value -> value).sum());
}
}
In your code, you would do this to the grade list. You can set this to gradetotal after your loop.
value -> value is saying "take each argument and return it". stream() returns a Stream which doesn't have sum(). mapToInt returns an IntStream which does have sum(). That value -> value tells the code how to convert each element in the Stream into an Integer. Because each element is already an Integer, we merely have to return each element.

Instead of maintaining an array, why not just keep two temporary variables - a count and a summation?
int gradetotal = 0;
int gradelistnumber = 0;
int inputedgrade = 0;
while(inputedgrade != -1){
System.out.println("Enter Grade for student " + gradelistnumber + " (1-50): ");
inputedgrade = sc.nextInt();
gradetotal = gradetotal + inputedgrade;
gradelistnumber++;
}

Related

User Input to determine the length of an array in Java

I am currently taking an intro to java class at my school due to my growing interest in programming.
I am to create a program that takes user input for a min and max integer. I am also to take user input for the size of the array as well as whether or not the user would like both the sorted and unsorted lists printed out.
After I collect this information, I need to generate random values within the given min/max range and sort those values(I had no problem completing these steps).
My code:
//Third Project by John Mitchell
package thirdProject;
//Imported library
import java.util.*;
//First class
public class thirdProject {
//Created scanner and random class as well as variables
public static Scanner scan = new Scanner(System.in);
public static Random rand = new Random();
public static int min, max, rand_num, sum, total, temp, i, j;
public static boolean sorted;
public static int[] values = new int[];
//Allowing for the average output to be of type double
public static double average;
//Main method
public static void main(String[] args) {
//Prompt user to enter minimum value to be sorted
System.out.println("Please enter a minimum value: ");
min = scan.nextInt();
//Prompt user to enter maximum value to be sorted
System.out.println("\nPlease enter a maximum value: ");
max = scan.nextInt();
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
//Prompt the user whether or not they would like both lists
System.out.println("\nWould you like to see both the sorted and unsorted lists? Please enter 'True' for yes or 'False' for no.");
sorted = scan.nextBoolean();
//Prints lists that were generated
if (sorted == true) {
gen_random_val();
System.out.println("\nThe unsorted list is: " + Arrays.toString(values) + ".");
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
} else {
gen_random_val();
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
}
}
//Second method
public static void gen_random_val() {
//For loop that generates values within the range of values given
for(int i = 0; i < values.length; i++) {
values[i] = rand_num = Math.abs(rand.nextInt(max) % (max - min + 1) + min);
sum = sum + values[i];
average = (sum*1.0) / values.length;
}
}
//Third method
public static void sort_values() {
//For loop that sorts values
for(i=0; i<(total-1); i++) {
for(j=0; j<(total-i-1); j++) {
if(values[j] > values[j+1]) {
temp = values[j];
values[j] = values[j+1];
values[j+1] = temp;
}
}
}
}
}
Currently, the hard codes length of 10 values in the array works fine as I have recycled part of my code from a previous project. I am looking for guidance on how to simply make the size determined by user input.
Thank you.
For example you can do this:
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
values = new int[total];
You don't have to give values to variables when you declare them.

Setter sets value for every object in class

I have a program that takes students' names and grades as user input and then performs some operations on them, which are irrelevant for the scope of the question. The code is as follows:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Student {
// Four attributes that define Student
private String name;
private double points;
private int startYear;
private int[] grades;
public Student(String name, double points, int startYear, int[] grades) {
this.name = name;
this.points = points;
this.startYear = startYear;
this.grades = grades;
}
//Constructor. Everyone starts with 0 points and this year
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //Create scanner
System.out.println("Please enter the number of students:");
int count = sc.nextInt(); // Number of students
System.out.println("Please enter the number of grades:");
int count1 = sc.nextInt(); // Number of grades
Student students[] = new Student[count]; // Create array of student objects based on previously entered value
int[] temp = new int[count1]; // Temporary array for storing grades entered
for (int i = 1; i < count + 1; i++) {
System.out.println("Please enter the name of student " + i);
String name = sc.next();
students[i - 1] = new Student(name,0.0,2018,temp); // Creating student object
System.out.println("Please enter grades of " + name);
for (int k = 0; k < count1; k++) {
int personal_grades = sc.nextInt();
temp[k] = personal_grades; //filling the temporary array
//System.out.println(grades.length); //for debugging
}
students[i - 1].setGrades(temp); //transferring from temporary array to student object array
students[i-1].printGrades();
}
System.out.println((students[0].name));
System.out.println((students[1].name));
System.out.println(Arrays.toString(students[0].grades));
System.out.println(Arrays.toString(students[1].grades));
for(int i = 0; i < count; i++) {
System.out.println("Grades of " + students[i].name + " are:");
//students[i].printGrades();
}
for(int i = 0; i < count; i++) {
System.out.println("Average of " + students[i].name + " is:");
// students[i].average();
}
int passed=0;
for(int i = 0; i < count; i++) {
if(students[i].average()>5.5)
{
passed++;
}
}
System.out.println(passed+" students passed!");
}
public void setGrades(int[] temp) {
this.grades = temp;
}
public int[] getGrades() {
return grades;
}
public void printGrades() {
System.out.println(Arrays.toString(grades));
}
public float average (){
int k = 0;
int sum=0;
float average=0;
while (k < this.grades.length) {
sum=sum+this.grades[k];
k++;
}
average = sum/(float)this.grades.length;
System.out.println(average);
return average;
}
}
The problem I am having with the code is as follows: the setter method appears to set the values for all of the objects that were ever created. Take this test run as an example:
You can see that the grades for the last student entered appear in every student's record. I have debugged and found that it is the setGrades method that causes this. However, I am using the this keyword - why does it set the value for all the objects then?
You need to move the
int[] temp = new int[count1]; // Temporary array for storing grades entered
inside the outer for loop, otherwise all created Students will have a reference to same grades array and all will end up with the grades of the last student.
It's because you are using the same array for all the grades of everyone.
Moving
temp = new int[count1]; inside the first loop should fix it
Note how both Student's constructor and Student::setGrades() get grades by reference.
This means that for each Student's instance, its grades field points to the parameter that was received during its initialization.
However, you only initialize temp once and therefore all the instances point to the same grades array. Once this array is changed, calling student.printGrades() will print the shared array's contents.
This can be solved by initializing temp on every iteration, before creating a new Student instance; Or by copying the array by value inside setGrades() method:
public void setGrades(int[] temp) {
this.grades.clone(temp);
}
Move the array (temp) holding the grades inside the loop where you create individual Students
for (int i = 1; i < count + 1; i++) {
...
int[] temp = new int[count1]; //The array holding the grades must be *specific* for each student
students[i - 1] = new Student(name, 0.0, 2018, temp); // Creating student object
...
students[i - 1].setGrades(temp); //transferring from temporary array to student object array
students[i - 1].printGrades();
}
In your original code, you are using just one array i.,e temp was pointing to the same array all the time. After you finish initializing the first Student, when you loop populating the grades for the second student, you are mutating (or modifying) the same grades array created for the first student.

Using a scanner input to define the number of scanner inputs required

I have made it a little further. It turns out I can use loops but not arrays in my assignment. So here's the current version (keep in mind no final calculations or anything yet.) So if you look at the homework method, you can see I am asking for the "number of assignments." Now, for each assignment, I need to ask for and sum both the Earned Score and the Maximum Possible Score. So for instance, if there were 3 assignments, they might have earned scores of 18, 22, and 29, and maximum possible scores of 20, 25, and 30 respectively. I need to grab both using the console, but I don't know how to get two variables using the same loop (or in the same method).
Thanks in advance for your help!
import java.util.*;
public class Grades {
public static void main(String[] args) {
welcomeScreen();
weightCalculator();
homework();
}
public static void welcomeScreen() {
System.out.println("This program accepts your homework scores and");
System.out.println("scores from two exams as input and computes");
System.out.println("your grade in the course.");
System.out.println();
}
public static void weightCalculator() {
System.out.println("Homework and Exam 1 weights? ");
Scanner console = new Scanner(System.in);
int a = console.nextInt();
int b = console.nextInt();
int c = 100 - a - b;
System.out.println();
System.out.println("Using weights of " + a + " " + b + " " + c);
}
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.print("Number of assignments? ");
int totalAssignments = console.nextInt();
int sum = 0;
for (int i = 1; i <= totalAssignments; i++) {
System.out.print(" #" + i + "? ");
int next = console.nextInt();
sum += next;
}
System.out.println();
System.out.println("sum = " + sum);
}
}
I don't know where exactly your problem is, so I will try to give you some remarks. This is how I would start (of course there are other ways to implement this):
First of all - create Assignment class to hold all informations in nice, wrapped form:
public class Assignment {
private int pointsEarned;
private int pointsTotal;
public Assignment(int pointsEarned, int pointsTotal) {
this.pointsEarned = pointsEarned;
this.pointsTotal = pointsTotal;
}
...getters, setters...
}
To request number of assignments you can use simply nextInt() method and assign it to some variable:
Scanner sc = new Scanner(System.in);
int numberOfAssignments = sc.nextInt();
Then, use this variable to create some collection of assignments (for example using simple array):
Assignment[] assignments = new Assignment[numberOfAssignments];
Next, you can fill this collection using scanner again:
for(int i = 0; i < numberOfAssignments; i++) {
int pointsEarned = sc.nextInt();
int pointsTotal = sc.nextInt();
assignments[i] = new Assignment(pointsEarned, pointsTotal)
}
So here, you have filled collection of assignments. You can now print it, calculate average etc.
I hope above code gives you some remarks how to implement this.

I need to get from the user input random

import java.util.Scanner;
public class hh {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int numbers = input.nextInt();
// Declare an array called numbers with a size of 10
int[] numbers1 = new int[numbers];
insertRandomNumbers(numbers1);
// Print size of numbers
System.out.println("Initial Array: ");
for (int i = 0; i < numbers1.length; i++) {
System.out.print(numbers1[i] + " ");
}
System.out.println("");
//Print First and Last Elements
System.out.println();
System.out.println("First and Last Elements");
int [] lastStep = lastStep(numbers1);
for (int i = 0; i < lastStep.length; i++) {
System.out.print(lastStep[i] + ", ");
}
} // end main
public static int[] lastStep(int[] numbers1) {
//to get first
int [] firstElement= numbers1.get(0);
//last number
int [] lastElement= numbers1.get(numbers1.size()-1);
}
return lastStep;
public static void insertRandomNumbers(int[] x) {
for (int i = 0; i < x.length; i++) {
x[i] = random();
// System.out.print(x[i] + " ");
}
// System.out.println();
}
public static int random() {
int r = 0 + (int) (Math.random() * (101 - 0)) + 0;
return r;
}
My program ask the user to enter a number, then if 10 is entered 10 random numbers are created. With those 10 numbers I need to get the first and last numbers. The way I have my method right now I am getting ERROR: Cannot invoke get(int) on the array type int[]
WHEN I USE
public static int[] lastStep(int[] numbers1) {
//to get first
int [] firstElement= numbers1.array[0];
//last number
int [] lastElement= numbers1.array[numbers1.size()-1];
}
return lastStep;
I get that array cannot be resolved or is not a field
That's because you're using an Array not an ArrayList. Try using numbers1[0] and numbers1[numbers.length - 1]
You should consider changing your lastStep function. From what I can see, it does nothing, because the return statement is outside the function braces. There is also no variable lastStep inside the function that can be returned. Try the following:
public static string firstAndLast(int[] numberArray)
{
return numberArray[0] + ", " + numberArray[numberArray.length - 1];
}
Then just call it like:
System.out.println(firstAndLast(numbers1));
You can't use .get(0) on an array, you have to use array[0].
In your case it would be: numbers1[0]
Use Array List for to add random numbers , then print the last and first one.

Sorting the two highest numbers in an array

I'm sorry to ask, but I'm having trouble with an exercise in my book, and I am unsure how to fix it. After entering the student's name and score, I am to find the highest and second highest score. However I cannot find a proper way to find the two highest scores.
The current way I use works, but fails the user enters scores from low to high, such as 70, 80, and 90. If done 90, 80, and 70, it sorts the numbers appropriately.
Is there anything I could change/do/read to put me on the right path?
import java.util.Scanner;
public class StudentSort {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// For finding highest scores with corresponding array
double firstHighest = 0;
int firstEntry = 0;
double secondHighest = 0;
int secondEntry = 0;
System.out.print("Enter the number of students: ");
int studentCount = input.nextInt();
// Length of arrays set
int[] studentScores = new int[studentCount];
String[] studentName = new String[studentCount];
// Go through loop to set scores and names of each student
for (int i = 0; i < studentCount; i++) {
System.out.print("Enter a student name: ");
studentName[i] = input.next();
System.out.print("Enter a student score: ");
studentScores[i] = input.nextInt();
}
// Find out the highest and second highest scores
// Problem with secondHighest/Entry
for (int i = 0; i < studentScores.length; i++) {
if (studentScores[i] > firstHighest) {
secondHighest = firstHighest;
firstHighest = studentScores[i];
firstEntry = i;
} else if (studentScores[i] > secondHighest) {
secondHighest = studentScores[i];
secondEntry = i;
}
}
System.out.println("Top two students: ");
System.out.println(studentName[firstEntry] + "'s score is " + firstHighest);
System.out.println(studentName[secondEntry] + "'s score is " + secondHighest);
}
}
As always, I thank you for any help that you can provide.
It looks like you just forgot to update secondEntry when you get a new highest score. Before the line:
firstEntry = i;
Try adding:
secondEntry = firstEntry;
The problem is here
if (studentScores[i] > firstHighest) {
secondHighest = firstHighest;
firstHighest = studentScores[i];
firstEntry = i;
}
you successfully update the values for both secondHighest and firstHighest but you don't fix secondEntry;
you need to add
secondEntry = firstEntry;
before
firstEntry = i;
There are more than 1 ways to solve this problem. The most intuitive way would be akin to picking up a hand of cards (i.e insertion sort). Think of the inputs as a continuous list of cards. It doesn't really matter what order they come in as most players will sort them going from lowest to highest (or the other way around).
So in your input loop:
while(...some_condition_that_ensures_more_input){
//this can be a list for instance, which you keep in order
list = insert_into_correct_place(input);
}
/**
Assuming
a)you sort from lowest to highest
b)there is more than 1 input entered):
*/
highest = list.get(list.length()-1)
second_highest = list.get(list.length()-2)
Another intuitive way (and actually faster) way is to just keep track of two variables:
int [] highest = {Integer.MIN_VALUE(), Integer.MIN_VALUE()};
while(...){
highest = replace_lowest(input, highest);
}
/**
* arr is sorted from lowest to highest : arr[0] is always <= arr[1]
*/
int [] replace_lowest(int input, int [] arr){
//Case 0 : input is less than both the highest 2 numbers
// or is equal to one of them
if (input < arr[0] || input == arr[0] || input == arr[1]) { return arr; }
//Case 1 : input is greater than one of the highest 2, but not both
if (input > arr[0] && input < arr[1]) { arr[0] = input; return arr; }
//Case 2 : input is greater than both of the highest 2 numbers
second_highest = arr[1]; arr[0] = arr[1]; arr[1] = input;
return arr;
}
The first approach is a bit more flexible (it would allow you to pick out X highest numbers instead of just two). The second approach is faster if you know that you will never have to readjust the number of output variables.
You can simply use the java.util.Arrays class and its sort() method. Here's what the code might look like:
Arrays.sort(studentScores);
int firstHighest = studentScores[studentScores.length - 1];
int secondHighest = studentScores[studentScores.length - 2];
Hope this helps.
I wrote you a method with the help of an inner class; it returns an array, the first element is the Student with the heighest score, the second Student the one with the second score.
import java.util.Arrays;
import java.util.Comparator;
public class StudentSort {
static class Student {
Student(int score, String name) {
this.score = score;
this.name = name;
}
int score;
String name;
}
private static Student[] test(int[] studentScores, String[] studentNames) {
Student[] students = new Student[studentScores.length];
for(int i = 0; i < studentScores.length; i++) {
students[i] = new Student(studentScores[i], studentNames[i]);
}
Arrays.sort(students, new Comparator<Student>() {
#Override
public int compare(Student o1, Student o2) {
return new Integer(o1.score).compareTo(o2.score);
}
});
return new Student[]{students[0], students[1]};
}
public static void main(String[] args) {
int[] studentScores = new int[] {5, 9, 7};
String[] studentNames = new String[]{"Jan", "Bert", "Piet"};
Student[] students = test(studentScores, studentNames);
System.out.println("heighest: " + students[0].name + ": " + students[0].score);
System.out.println("second: " + students[1].name + ": " + students[1].score);
}
}

Categories

Resources