return the sum of int[ [duplicate] - java

This question already has answers here:
How do you find the sum of all the numbers in an array in Java?
(28 answers)
Closed 1 year ago.
This is my code using loops. Assume that num is not null or empty;
public int[] num;
public double[] sumNum() {
double[] sum;
for (int i = 0; i < num.length; i++) {
sum = sum + num[i];
}
return sum;
}

If you want to devise a function to sum the values of an array, consider the below:
public int sumNum(int[] num) {
int sum = 0;
for (int i = 0; i < num.length; i++) {
sum = sum + num[i];
}
return sum;
}
It doesn't make sense to return a double for a function like this, but you still can. I changed it to int since num is always int as per its declaration. I'm only making an assumption to what you really wanted.
Also consider taking num as argument for the function, thereby giving it local scope within the function. You could keep it global but again, I'm making an assumption of what you really want. Plus, it allows for re-using this function if you ever wanted to find the sum of something else.
You also want some initial value for sum: since you're summing the values in an array, I initialized sum to 0. Otherwise, when you do sum = sum + num[i], what exactly is sum initially? You need some starting point.

Related

Cannot convert double into double[][] error in java?

Okay so I'm still working on a matrix project for my APCS class, and I am currently trying to figure out how to get the user to input all the numbers for the matrix. Right now I have a setNums class that uses the Rows and Columns already inputted to throw up a bunch of inputboxes and then inputs those numbers into a 2 dimensional array like so:
public void setNums(String Matrixnum){
for (int i = 1; i <= myRows; i++){
for(int j = 1; j <= myColumns; j++){
String StrNum = JOptionPane.showInputDialog(null, Matrixnum + " Row " + i + " Column " + j + " enter number:");
myNums[i][j] = Double.parseDouble(StrNum);
}
}
}
I then have a getNums class that should go through the array and return them one by one, when I need the numbers later on for adding, subtracting, and multiplying the matrices:
public double[][] getNums(){
for(int i = 1; i <= myRows; i++) {
for(int j = 1; j <= myColumns; j++) {
return myNums[i][j];
}
}
}
The issue is that when I try to return myNums, it says "cannot convert from double to double[][]" I don't understand why the code thinks it's a double and not a double[][]. I initialized it correctly:
private double[][] myNums;
...and I made sure my parsedouble was outputting to the array, which was the issue in a similar thread I found. This is my first time working with 2 dimensional arrays, so I bet there's something simple here that I don't understand. Any help is greatly appreciated. Thanks!
The compiler returns this error Cannot convert double into double[][]
because your are actually returning single double number instead of your double array double[][] that you defined as return type of your method getNums()
Instead you can fix the problem by returning only myNums array:
public double[][] getNums(){
return myNums;
}
Also you can declare another method if you want to get any specific number from your array by using array indexes i and j:
public double getNumber(int i, int j){
return myNums[i][j];
}

Java returning numbers below the avg

ne of my projects assigned was to create an array for 10 variables which the user inputs and to have the program output the average of the input number as well as listing the numbers below the average. I am able to obtain the average without an issue but my code to return the numbers below the average seems to not be doing the job. For example if I input into the array the values [1,2,3,4,5,6,7,8,9,10] the average outputs as 5.5 (which is good) but the output I want from BelowAverage is 1,2,3,4,5 can anyone help me?
public static double BelowAverage(ArrayList<Double> Averages) {
int i, aveless = 0; double avg = 0;
for(i = 0; i < Averages.size(); i++)
avg = Averages.get(i);
avg /= Averages.size();
for(i = 0; i < Averages.size(); i++)
if(Averages.size() < avg)
aveless++;
return aveless;
}
No need to use wrappers, you could use double instead of Double.
Your variable naming is weird, why do you have an ArrayList of averages instead of numbers?
Follow Java naming conventions:
firstWordLowerCaseVariable
firstWordLowerCaseMethod()
FirstWordUpperCaseClass
ALL_WORDS_UPPER_CASE_CONSTANT
and use them consistently
You already have a method that calculates the average, why not use it?
So, for example, your code might look like this (with slight modifications):
public static int belowAverage(List<Double> numbers) {
double avg = calculateAverages(numbers); //Go, get the average using the method you already have
int aveless = 0;
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) < avg) { //Instead of comparing the numbers array size, compare the number against the average.
aveless++;
}
}
return aveless;
}
I added opening and closing curly braces for the for loop as I think it's easier to read that way.
I also changed the return type to int instead of double on this method as you only want to count, so, decimal point is not needed and moved the System.out.println() call inside the calculateAverage() method to the main method.
I also changed the parameter type to the interface one (from ArrayList to List)
Your problem seems to bee on this line:
if(Averages.size() < avg) aveless++;
You should be checking Averages.get(i) < avg instead, otherwise what is the point of looping?
If I understand correctly, and you want a list with all the numbers below the average, you should change the return value and the code, like this:
public static ArrayList<Double> BelowAverage(ArrayList<Double> Averages) {
// You already have a method for calculating the average, so use it
double avg = CalculateAverages(Averages);
ArrayList<Double> aveless = new ArrayList<Double>();
int i;
for(i = 0; i < Averages.size(); i++){
double number = Averages.get(i);
if(number < avg){
aveless.add(number);
}
}
return aveless;
}
There are several problems with your code. Let's go through them one at a time.
First problem:
for(i = 0; i < Averages.size(); i++)
avg = Averages.get(i); //this line
avg /= Averages.size();
You are simply reassigning the value of avg in the loop. What you want to do is to keep adding values to it. Replace = with += to get avg += Averages.get(i);.
Second problem:
for(i = 0; i < Averages.size(); i++)
if(Averages.size() < avg)
aveless++;
Here you are checking whether avg is larger than the size of the list which is not what you want to be doing. What you wonder is whether avg is larger than the values in the list. You need to replace Averages.size() with Averages.get(i). This is a relatively easy mistake to spot because the loop is not really achieving anything right now, so look out for things like this.
Edit: There are a few other problems as well. avg should be a double and not an int, because ints cannot store decimal places and there is no guarantee that your average is a whole number, so you will get a rounding error. Furthermore, your method should return an int instead of a double because "the number of values below average" is always an integer.
To count the number of 'numbers' which have less value than the average, you should compare each element inside that array with the average, not with the size of the array. Try it as follows:
public static double BelowAverage(ArrayList<Double> Averages) {
int i, aveless = 0; double avg = 0;
for(i = 0; i < Averages.size(); i++)
avg = Averages.get(i);
avg /= Averages.size();
for(Double a : Averages)
if(a < avg) aveless++;
return aveless;
}

Making a method for an array

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.

Why wont my array average all numbers?

i have to create an array and a method call for the average. but for some reason it is not average all numbers, its only returning the last number. I have asked my instructor for help and she said the math is correct it should work. But no other help from her. What have I done wrong?
public static void main(String[] args) {
double[] myArray = new double[2];
initialize(myArray);
double avg = getAverage(myArray);
System.out.println(avg);
output(avg);
}
public static void initialize(double[] myArray) {
//myArray = new double[1000];
for(int i = 0; i < myArray.length; i++) {
myArray[i] = (int) ((Math.random()*500)*1);
System.out.println(myArray[i]);
}
}
/**
*
* #param myArray
* #return
*/
public static double getAverage(double[] myArray) {
int sum = 0;
for (int i = 0; i < myArray.length; i++) {
sum += myArray[i];
}
return sum / myArray.length;
}
public static void output(double avg) {
System.out.println("The average is " + avg);
}
The key is in this line:
sum / myArray.length
...since both sum and myArray.length are integers, Java performs integer division, not floating point division, which essentially means it drops the decimal component of the result.
Casting one of the values to a double first will force a floating point division to occur.
You're also storing the sum as an int, which could again introduce a source of error since the array contains doubles. In this case you're ok because you're casting everything you put into the array to an int first, which begs the question as to why you're using a double array in the first place?
As an aside, this is a bit odd:
((Math.random()*500)*1);
There's no need to multiply the result by 1 here - that won't do anything.
What is the problem here? The answers are coming correctly. Please check again. The interesting fact is that the third number is always same as the average of all three. But the average computation is correct. That may be how Math.random() generates random numbers internally. The third is the average of the other two. Try out four or five numbers instead of three numbers and check your answers.

How to perform a sum of an int[] array [duplicate]

This question already has answers here:
How do you find the sum of all the numbers in an array in Java?
(28 answers)
Closed 5 years ago.
Given an array A of 10 ints, initialize a local variable called sum and use a loop to find the sum of all numbers in the array A.
This was my answer that I submitted:
sum = 0;
while( A, < 10) {
sum = sum += A;
}
I didn't get any points on this question. What did I do wrong?
Once java-8 is out (March 2014) you'll be able to use streams:
int sum = IntStream.of(a).sum();
or even
int sum = IntStream.of(a).parallel().sum();
Your syntax and logic are incorrect in a number of ways. You need to create an index variable and use it to access the array's elements, like so:
int i = 0; // Create a separate integer to serve as your array indexer.
while(i < 10) { // The indexer needs to be less than 10, not A itself.
sum += A[i]; // either sum = sum + ... or sum += ..., but not both
i++; // You need to increment the index at the end of the loop.
}
The above example uses a while loop, since that's the approach you took. A more appropriate construct would be a for loop, as in Bogdan's answer.
int sum=0;
for(int i:A)
sum+=i;
int sum = 0;
for(int i = 0; i < A.length; i++){
sum += A[i];
}
When you declare a variable, you need to declare its type - in this case: int. Also you've put a random comma in the while loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:
int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
sum += numbers[i];
}
System.out.println("The sum is: " + sum);
Here is an efficient way to solve this question using For loops in Java
public static void main(String[] args) {
int [] numbers = { 1, 2, 3, 4 };
int size = numbers.length;
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
System.out.println(sum);
}

Categories

Resources