A bit of a beginner with programming so do bear with me.
I've created an ArrayList inside a HashMap so that all my values can be added up to become a sum so that I can then divide the sum, by the number of entries to the ArrayList, which would give me my average... which is all working fine EXCEPT:
My first entry into my ArrayList is always coming back as 0.0 even when in the GUI I'm entering like 45 or whatever. How can I change it so that my ArrayList stops putting 0 on my first entry? As I've created an averaging program that would work if my first ArrayList entry was retrieving the correct entry, as oppose to the 0 it is bringing back everytime.
Here is my code:
public void addModRes( String mod, Integer res ) {
ArrayList<Integer> nums = myMap.get(mod);
if (nums == null) {
nums = new ArrayList<Integer>();
}
double sum = 0;
double test =0;
double avg =0;
for (Integer number : nums) {
sum += number;
}
//except sum is missing out the first entry in the ArrayList
System.out.println("The Sum of all the numbers in the array is " + sum);
nums.add(res);
myMap.put(mod, nums);
test = nums.size();
//System.out.println("This is the size of the array list "+
numbers.size());
avg = sum/test;
System.out.println("this is the average: "+ average);
}
I tried to understand your code and my guess is that you want something like this:
You want a HashMap<String, ArrayList<Interger>> that stores lists of numbers (the ArrayList<Integer> from the HashMap) that can be identified with their id (the String in the HashMap).
Add a new list to the HashMap
Let's assume that we have an instance variable listMap in our class.
public int createList(String listId) {
this.listMap.put(listId, new ArrayList<Integer>() );
return this.listMap.size();
}
This will add a new ArrayList<Integer> to the listMap.
Add numbers to a certain list
We now write a new method to add numbers to a certain list
public int addNumberToList(String listId, Integer number) {
this.listMap.get(listId).add(number);
return this.listMap.get(listId).size();
}
Calculate the average for a certain list
Now we can use the lists to calculate their average
public double averageForList(String listId){
double sum = 0;
double average = 0;
for (Integer number : this.listMap.get(listId) )
{
sum += number;
}
if (this.listMap.get(listId).size() != 0) average = sum / this.listMap.get(listId).size();
return average;
}
And that should be it.
Related
I'm new to Java and I'm stuck on this problem:
"Create a second add() method which has a single parameter of an array of doubles and, inside the method, adds the values of the array, returning the result as a double. Sample test data:
double[] dblArr = {11.82,88.23,33};
I have a separate class file with the following so far:
public double add(double[] values) {
int sum = 0;
for (double i : values)
sum += i;
return sum;
}
This is the method to add the array's and return the total sum.
And this is the code I have in my "main" document to call the method
double dblArr;
utils.print("Please enter an array of 5 numbers: ");
dblArr = input.nextDouble();
double sum = calc.add(dblArr);
System.out.println(dblArr);
I know I'm quite off scope so some advice would be really appreciated, thank you
"calc" is what I'm using to call the other document
Calculate calc = new Calculate();
You are most of the way there, you just need to use a double array to gather the inputs, and you need to use a loop to save all the inpets to the array:
//use an array instead of a single double
double[] dblArr = new double[5];
int inputs = 0;
//Use a loop to gather 5 inputs
while(inputs < 5){
utils.print("Please enter the next of 5 numbers: ");
dblArr[inputs] = input.nextDouble();
inputs++;
}
//We have changed the add method to static, so you can just use `add(dblArr)` instead of making an instance of the class with the add method
double sum = add(dblArr);
//Finally print out the sum result not the dblArr array
System.out.println("The total is " + sum);
Then just change the method to static so that you can call it directly:
//Add static to this line as shown, because we don't need an instance of this method
public static double add(double[] values) {
int sum = 0;
for (double i : values)
sum += i;
return sum;
}
I want to loop through my array list roster and for each Student item I want to return the average of an array of grades. I know there are 3 grades so this code works, but how can I implement this if I don't know how many grades are in the Student's grades array before hand?
public static void printAverageGrades(){
System.out.println("Print Average Grades");
for(Student item : roster)
{
double div = roster.size();
**double average = (item.getGrades()[0] + item.getGrades()[1] + item.getGrades()[2]) / div;**
System.out.printf("%.2f \n", average);
}
}
You can do this two ways. The more preferable Java 8 way is listed first.
Use Arrays.stream to encapsulate the array as a stream, then getting the average is just a couple of method calls away.
double avg = Arrays.stream(item.getGrades()).average().getAsDouble();
Use another for loop and keep a running total of the elements. Don't forget to manually coerce your numerator to a double or you'll run into integer division.
int sum = 0;
for(int i : item.getGrades()) {
sum += i;
}
double avg = (sum * 1.0) / item.getGrades().length;
In practice, never hard-code your index locations. You can always get the length of an array using .length.
You can just use this function, in which would iterate through the array, by dynamically iterating through for loop, we compute sum.
Then average would be divided by the length of array.
double getAverage(double[] data)
{
double sum = 0.0;
for(double a : data)
sum += a;
return sum/data.length;
}
I know this is quite basic but I am having trouble understanding to use < when testing against objects in an array.
I want to test the ruleGrades which are stored in an 2D array against minimum (a double), and then multiply it with a probability (double).
ArrayList<Double[][]> ruleGrades = new ArrayList<Double[][]>();
ArrayList<Double> min= new ArrayList<Double>();
double minimum;
System.out.println("Rule Grades: "+ruleGrades.toString());
for(int a=0;a<ruleGrades.size();a++)
{
minimum=2.0;
System.out.println("A: "+a);
for(Double[] grades : ruleGrades.get(a))
{
if(grades<minimum) //error over here
{
Double prob=rule.getRules().get(a).getProbability();
minimum=grades.doubleValue()*prob.doubleValue(); //error
}
}
min.add(minimum);
}
max=0.0; //finding largest
for (int b = 0; b< min.size(); b++ )
{
if( min.get(b) > max)
{
max = min.get(b);
}
}
}
UPDATE:
Okay I see that i dont need a multidimensional array, I can just use a Double[] to have 2 values in the first element. Here is my updated code:
ArrayList<Double[]> ruleGrades = new ArrayList<Double[]>();
ArrayList<Double[]> min= new ArrayList<Double[]>();
System.out.println("Rule Grades: "+ruleGrades.toString());
for(int a=0;a<ruleGrades.size();a++)
{
Double [] minimum={2.0,2.0};
System.out.println("A: "+a);
for(Double grades : ruleGrades.get(a))
{
if(grades<minimum[0])
{
Double prob=rule.getRules().get(a).getProbability();
minimum[0]=grades.doubleValue()*prob.doubleValue();
}
if(grades<minimum[1])
{
Double prob=rule.getRules().get(a).getProbability();
minimum[1]=grades.doubleValue()*prob.doubleValue();
}
}
min.add(minimum);
}
Double [] max= {0.0,0.0}; //finding largest
for (int b = 0; b< min.size(); b++ )
{
for(Double mins : min.get(b))
{
if( mins> max[0])
{
max = min.get(b);
}
}
}
}
So in my first IF statement I want to check if the first double is less than 2.0, then multiple it by the probability and then add it to the arraylist min.
But how would I do that for the second value in the same element.
For example ruleGrades contains: [1.7,1.9],[1.2,1.3] ....
Then i take 1.7 multiply by prob (lets just say its 1) and add to the Double[] in the min arraylist, so min will look like this [1,7]. But then I wish to the same for 1.9 and put it in the same element as 1.7, so then the min array will look like [1.7,1.9].
Thats why i have added another IF statement , is this correct?
After all the grades have been multiplied by the prob and added to the min arraylist, i need to find the biggest one. So i made a Double max[] is that correct ?
Sorry about this, I am trying to read but I am really confused.
Thanks for all the help so far.
Actually you have declared array in inner for loop and comparing the whole array to a single double value.
grades < minimum is the problem
for(Double[] grades : ruleGrades.get(a))
{
if(grades is an array of Double < minimum is a double ) //error over here
{
I have an array that takes student grades from an input. I have to make a method that will find the average of the numbers within the array. Here is the code i have so far...
int mark = Integer.parseInt(input.getText());
if(mark <= 100){
marks.add(Integer.parseInt(input.getText()));
input.setText("");
warningLbl.setText("");
}
else{
warningLbl.setText("Please enter an number between 0-100");
}
I want to take the contents in the array 'marks' and get an average for them then append it in my text area
public static double getAverage(int[] marks)
{
int sum = 0;
for(int i : marks) sum += i;
return ((double) sum)/marks.length;
}
This is the method i have to find the average, but i dont know how to use this method and get it to print in a text area
If you want to find the average stored in an array , try the following function.
public static double average(int[] marks)
{
int sum = 0;
double average;
for(int element: marks)
{
sum = sum + element;
}
average = (double)sum / marks.length;
return average;
}
Hope it helps ! :)
The above method is used to find average in an array(primitive type) , but to find average in List type array(wrapper class) , we have to iterate through each element in the list by this way and do the required calculations :
public static String average(Integer[] marks)
{
int sum = 0;
double average;
for (int i = 0; i < marks.size(); i++)
{
sum = sum + marks.get(i);
}
average = (double) sum / marks.size();
String averageString = Double.toString(average);
return averageString;
}
This returns your average in string type directly.
There are several problems with your current code.
Using input.getText(); twice will mean it's going to prompt for input twice. Have a single line like int mark = Integer.parseInt(input.getText()); then use the mark variable wherever it's needed.
In order to test if the number is between 0 and 100 (I'm assuming this needs to be inclusive), that if statement would need to be (mark >= 0 && mark <= 100).
I assume you want to get multiple students' grades/marks, so it may be a good idea to enclose your code in a for or while loop, depending on how you want it to operate. However, since this will be of variable length I'd recommend using a List over an array for resizing.
Finding the average is easy. Just use a foreach loop to sum up all the numbers, then divide that by the array length.
I"m trying to make a program that retrieves an endless amount of numbers that user inputs, and then it tells you how many numbers that you inputted, the sum of all the numbers, and then the average of the numbers. Here is the code I have so far. I don't know why it does not work. I get no errors, but it just does not get a valid sum or average.
import javax.swing.*;
public class SumAverage {
public static float sum;
public static float averageCalculator;
public static float average;
public static void main(String[]args) {
float numbers[] = null;
String userInput = JOptionPane.showInputDialog(null, "Ready to begin?");
if(userInput.equalsIgnoreCase("no"))
{
System.exit(0);
}
for(int i = 0; i != -2; i++)
{
numbers = new float[i + 1];
userInput = JOptionPane.showInputDialog(null, "Input any number. Input * to exit");
if(userInput.length() == 0 || userInput.equals("*") || userInput.equals(null))
{
break;
}
else
{
numbers[i] = Float.parseFloat(userInput);
}
}
for (int i = 0; i < numbers.length; i++)
{
sum += numbers[i];
}
average = sum / numbers.length;
JOptionPane.showMessageDialog(null, "The sum of all your numbers is " + sum + ". The average is " + average + ". You entered a total of " + numbers.length + " numbers.");
}
}
The problem is in this line:
numbers = new float[i + 1];
You are creating a new array, but you aren't copying the values from the previous array assigned to numbers into it.
You can fix this in two ways:
copy the values using System.arraycopy() (you'll need to use a new variable to make the call then assign it to numbers)
Don't use arrays! Use a List<Float> instead, which automatically grows in size
In general, arrays are to be avoided, especially for "application logic". Try to always use collections - they have many powerful and convenient methods.
If you wanted to store the numbers for later use, try making your code look like this:
List<Float> numbers = new ArrayList<Float>();
...
numbers.add(Float.parseFloat(userInput));
...
for (float n : numbers) {
sum += n;
}
average = sum / numbers.size(); // Note: Don't even need a count variable
And finally, if you don't need to store the numbers, just keep a running sum and count and avoid any kind of number storage.
Unrelated to the Q, but note also you can compute a running count/average without storing all the input data - or assuming you want to keep the input - without traversing over it each iteration. Pseudocode:
count = 0
sum = 0
while value = getUserInput():
count++
sum += value
print "average:" + (sum / count)
with
numbers = new float[i + 1];
you are creating a whole new array on every iteration. That means you are always creating a new array that will increase its size by 1 on each iteration but only having one field filled with the current user input and having all the other fields been empty.
Delete this line and initialize the array before.
If the size of the array should grow dynamically within the loop
do not use an array at all and use a dynamic data structure like a List or an ArrayList instead.
Further i would suggest to use
while (true) {
//...
}
to realize an infinite loop.