Calling a void Method into a constructor - java

I have a problem that goes like this. A user inputs 5 grades into an array.
The array must then be sorted from highest to lowest and then averaged.
the methods for the selectionSort and calculateMean must be void.
How do i call them into my constructor? then i need to print the data out to a toString.
This is what i have so far.
import java.util.Scanner;
public class Average {
//the array which will contain the scores
private int data[];
//the average of the scores
private double mean;
public Average(){
Scanner sc = new Scanner(System.in);
double data[] = new double[6];
for(int i = 1; i < data.length; i++){
System.out.println("Enter score number " + i);
data[i] = sc.nextDouble();
}
/*for(int p = 1; p < data.length; p ++){
System.out.println(data[p]);
}*/
//selectionSort();
}
public void calculateMean(){
double total = 0;
double sum = 0;
double average = 0;
for(int counter = 0; counter < data.length; counter++){
sum = sum + data[counter];
average = sum / data.length;
}
}
public void selectionSort(){
int temp = 0;
for(int joey = 0; joey<data.length; joey++){
for(int i = 1; i < data.length; i++) {
if(data[i - 1] > data[i]) {
temp = data[i-1];
data[i-1] = data[i];
data[i] = temp;
}
}
}
for(int p = 0; p < data.length; p++){
System.out.println(data[p]);
}
}
public String toString(){
return null;
}
}

You can call the 2 methods in your constructor like this
// Inside constructor
selectionSort(); // call the method
calculateMean(); // call the method
System.out.println(toString()); // print the data using toString
And your toString() can look like this
public String toString() {
return Arrays.toString(data);
}
Also, the logic in your calculateMean() is a bit wrong.
for (int counter = 0; counter < data.length; counter++) {
sum = sum + data[counter];
}
average = sum / data.length; // Calculate the average after finding the sum and not at every iteration.
Moreover, I see that the mean instance variable is not. You might want to assign the average calculated in the calculateMean() method to it, and you might want to print it some method or the toString() itself, depending in your needs.
Edit:
You're shadowing your instance variable int data[]; with the local variable in the constructor, double data[] = new double[6]; and that is the reason you're getting the NPE. Remove the local variable from the constructor and instead initialize it like this
data[] = new int[5];
And the following for loop to get the input from the user to start from the index 0 and not 1.
for(int i = 0; i < data.length; i++){

Related

how to add elements in each row seperately and print output in 2D array

Lets assume i have a 2x3 matrix where row denote student and column denote marks.
eg:[[67,80,56],
[32,26,31]]
need to find the average of each row and assign a grade based on avg. if avg>40 then return "p" else return "F".
import java.util.*;
public class Solution
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=2;
int m=5;
int mark[][]=new int[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
mark[i][j]=sc.nextInt();
}
}
String result=grade(mark);
System.out.println("RESULT:"+result);
}
public static String grade(int mark[][])
{
int n=2,m=5,avg=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int sum=0;
sum=sum+ mark[i][j];
if(j==m)
{
avg=sum/m;
}
}
if(avg>=90)
{
return "A+";
}
else if(avg<40)
{
return "F";
}
}
return null;
}
}
IN the above code my my average value is initialised to 0.scope of average in for loop is not reflected in outside loop.how to correct itenter image description here
You are declaring the sum variable inside your 2nd loop it should be declared before your 2nd loop starts. If you declare it inside it will not have the calculated value from the previous iteration.
Also you can easily calculate avg outside the loop and then gor for your cheking.
EG:
int n=2;
int m=3;
int[][] mark = { { 67,80,56 }, { 32,26,31} };
// grade function
for (int i = 0; i < n; i++) {
int sum=0;
for (int j = 0; j < m ; j++) {
sum=sum+ mark[i][j];
}
int avg = sum / m;
System.out.println(avg);
//your code to check pass/fail
}
Also Don't return if you want to print values for each row. Instead of return use print there.
if(avg>=90)
{
System.out.println("GRADE")
}
First of all, if you need to print the grade of every student separately you will need to call your grade method for every student's marks. So put your method call in a for loop.
for(int i = 0; i < n; i++) {
System.out.println(grade(mark[i]))
}
Consequently, the definition of your method changes to
public static String grade(int mark[]) {
...
}
And at last, your if(j==m) check will always be false, cause in your code, j will never reach m in your for loop. It comes to a simple calculation of array element's sum.
public static String grade(int mark[][])
{
int m = 5, avg = 0;
int sum = 0;
for(int j = 0;j < m; j++) {
sum = sum + mark[i][j];
}
avg = sum / m;
if(avg >= 90)
{
return "A+";
}
else if(avg < 40)
{
return "F";
}
}

Program ignoring the last row in the file in calculation

I have a text file with data that looks like this (TestData.txt):
Name|Test1|Test2|Test3|Test4|Test5|Test6|Test7|Test8|Test9|Test10
John Smith|82|89|90|78|89|96|75|88|90|96
Jane Doe|90|92|93|90|89|84|97|91|87|91
Joseph Cruz|68|74|78|81|79|86|80|81|82|87
Suzanne Nguyen|79|83|85|89|81|79|86|92|87|88
Richard Perez|100|84|73|81|92|84|95|96|95|100
Ivan Dyer|77|91|90|75|97|94|76|89|90|92
Craig Palmer|91|84|98|89|82|75|78|96|100|97
Madeline Rogers|75|79|78|93|91|76|80|88|100|81
Chelsea Roxas|87|94|89|96|95|85|88|92|86|86
Jasper Bautista|100|83|93|100|98|97|96|97|97|98
Tyler Perez|82|89|90|78|89|96|75|88|90|96
My code parses the file and does some calculations with it.
However, in the method arrangeList() within which calls another method called getTestAvg() (calculates column means), the program ignores Tyler Perez's scores.
I noticed that the results I am getting were inaccurate so I went and printed the whole 2d array with all the test scores and the last column is nowhere to be found.
My entire code is below and I hope someone could point out what causes this.
I keep getting an IndexOutOfBounds error whenever I try to switch N (# of students) and M (# of tests) to see what happens. At first, I have 10 students and 10 tests, and all the calculations were correct, but when I added another student, the calculations became inaccurate.
I apologize in advance if my code isn't as well-designed as I'm not an experienced programmer.
import java.util.*;
import java.io.*;
public class TestAverages
{
private static int[] grades;
private static int[] testTotal;
private static int N;
private static double classTotal;
private static int M;
public static void main(String[] args) throws FileNotFoundException
{
File input = new File("TestData.txt");
Scanner in = new Scanner(input);
parseFile(in);
}
public static void parseFile(Scanner in) throws FileNotFoundException
{
TestAverages t = new TestAverages();
in.nextLine();
double total = 0.0;
ArrayList<Double> testScores = new ArrayList<Double>();
int index = 0;
while(in.hasNextLine())
{
String line = in.nextLine();
String[] data = line.split("\\|");
String name = data[0];
grades = new int[data.length - 1];
N = grades.length;
for(int i = 0; i < N; i++){
grades[i] = Integer.parseInt(data[i + 1]);
testScores.add((double)grades[i]);
}
System.out.println(name + "\t");
System.out.println("Student Average: " + t.getStudentAvg(grades) + "%\n");
total += t.getStudentAvg(grades);
M++;
}
t.arrangeList(testScores);
System.out.printf("\nClass Average: %.1f%%\n", t.getClassAvg(total));
}
public double getStudentAvg(int[] grades)
{
double total = 0.0;
double avg = 0.0;
int N = grades.length;
for(int i = 0; i < N; i++){
total += grades[i];}
avg = total / N;
return avg;
}
public double getClassAvg(double total)
{
double classAvg = total / M;
return classAvg;
}
public double[][] arrangeList(ArrayList testScores)
{
double[][] tests = new double[N][N];
int len = tests.length;
for(int i = 0; i < len; i++)
{
for(int j = 0; j < len; j++)
{
tests[i][j] = (Double) testScores.get(i*N + j);
}
}
for(int i = 0; i < len; i++)
{
double avg = getTestAvg(tests, i);
System.out.printf("\nTest " + (i + 1) + " Average: %.1f%%\n", avg);
}
return tests;
}
public double getTestAvg(double[][] testScores, int index)
{
double testAvg = 0.0;
for(int i = 0; i < N; i++)
{
testAvg += testScores[i][index];
}
return testAvg / N;
}
}
Here are the numbers I'm supposed to be getting (top) compared to what my program outputs (bottom).
As the other responses already stated, you had quite the issue with your variables and loops. I now changed N to # of students and M to # of tests to be as you stated in your question.
Next time, maybe try to improve your variable naming, so you don't get confused. (e.g. switch out n and m for s (students) and t (tests), if you like your variable names short).
This should work now. Just check against your code to see the changes.
import java.util.*;
import java.io.*;
public class TestAverages {
private static int[] grades;
private static int n = 0; // amount of students
private static int m; // amount of tests
public static void main(String[] args) throws FileNotFoundException {
File input = new File("TestData.txt");
Scanner in = new Scanner(input);
parseFile(in);
}
public static void parseFile(Scanner in) throws FileNotFoundException {
TestAverages t = new TestAverages();
in.nextLine();
double total = 0.0;
ArrayList<Double> testScores = new ArrayList<Double>();
while (in.hasNextLine()) {
String line = in.nextLine();
String[] data = line.split("\\|");
String name = data[0];
grades = new int[data.length - 1];
m = grades.length;
for (int i = 0; i < m; i++) {
grades[i] = Integer.parseInt(data[i + 1]);
testScores.add((double) grades[i]);
}
System.out.println(name + "\t");
System.out.println("Student Average: " + t.getStudentAvg(grades) + "%\n");
total += t.getStudentAvg(grades);
n++;
}
t.arrangeList(testScores);
System.out.printf("\nClass Average: %.1f%%\n", t.getClassAvg(total));
}
public double getStudentAvg(int[] grades) {
double total = 0.0;
double avg = 0.0;
for (int i = 0; i < grades.length; i++) {
total += grades[i];
}
avg = total / grades.length;
return avg;
}
public double getClassAvg(double total) {
double classAvg = total / n;
return classAvg;
}
public double[][] arrangeList(ArrayList<Double> testScores) {
double[][] tests = new double[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
tests[i][j] = (Double) testScores.get(i * m + j);
}
}
for (int i = 0; i < m; i++) {
double avg = getTestAvg(tests, i);
System.out.printf("\nTest " + (i + 1) + " Average: %.1f%%\n", avg);
}
return tests;
}
public double getTestAvg(double[][] testScores, int index) {
double testAvg = 0.0;
for (int i = 0; i < n; i++) {
testAvg += testScores[i][index];
}
return testAvg / n;
}
}
You need to account for the different sizes. I think you want primarily the number of TESTS (not students), but you can't just use len for both index bounds.
double[][] tests = new double[N][M];
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
{
tests[i][j] = (Double) testScores.get(i*N + j);
}
}
Note that it didn't just resize the array, but it changed the loop conditions to loop the proper amount for inner and outer loop.
In the line
double[][] tests = new double[N][N];
of function arrangeList
you make your test array as N X N.
I believe youh should do something like
double[][] tests = new double[M][N];
It's just a suggestion as in your code it seems M = number of students and N = number of tests, differently from what you write in your question.
In general you should review all the method arrangeList and probably getTestAvg too (loop on N, instead of M), as the loops on variable len are intended for a N X N array, which is not the case.

How to create random numbers a specific number of times?

How can i create a random number a specific numbers of time?
public class Feld {
public static void main(String[] args) {
double k = (int)(Math.random()*1000001);
int n = 1000000;
int arr[] = new int[n];
int i = 0;
for(i = 0;i<n;i++){
arr[i] = i;
}
boolean found = false;
i=0;
while (i < arr.length) {
if (arr[i] == k) {
found = true;
break;
}
i++;
}
if (found) {
i++;
System.out.println(i);
}
else {
System.out.println((arr.length + 1));
}
}
}
My problem is, that if i put k into a loop to create it more than one time i'll get an error at:
if (arr[i] == k)
!!I just found out that i made a mistake explaining my problem. The array should be filled with values from 0-1.000.000 and i am supposed to print out the position of a random generated number for a specific amount of times.
If you want to have an array full of random numbers, I suggest using the following:
int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
arr[i] = (int)(Math.random() * 1000001);
}
That will work and you don't even need the variable k.
Edit:
If you want to print at what position you find a specific value (for example x = 543), you can use the following code:
int x = 543;
int n = 1000000;
int arr[] = new int[n];
for(int i = 0; i < n; i++){
arr[i] = (int)(Math.random() * 1000001);
if(arr[i] == x) {
System.out.println(i);
break;
}
}
Edit2
One possible solution to your new problem looks like this:
public class Feld {
public static void main(String[] args) {
int n = 1000000;
int arr[] = new int[n];
int i = 0;
for(i = 0; i < n; i++){
arr[i] = i; //Filling array with values 0-1000000
}
int number = 20; //Print out position of a random generated number a specific amount of times
int randomNumber = (int)(Math.random()*1000001); //The random number
for(int j = 0; j < number; j++) { //Find number for a specific amount of times
for(int k = 0; k < arr.length; k++) { //Find number in array
if(arr[k] == randomNumber) {
System.out.println(arr[k]); //Print
break; //Number found, don't have to search anymore
}
}
}
}
}
I would write a method that returns an array of random numbers and takes an int argument that defines the length of the array.
One possible solution is this:
public static int[] createRandomArray(int length) {
// create an array of the given length
int[] result = new int[length];
// and use a single for loop that puts random int values into every index
for (int i = 0; i < result.length; i++) {
result[i] = ThreadLocalRandom.current().nextInt();
}
// then simply return the result
return result;
}
Try it as follows
public static void main(String[] args) {
// super primitive time measurement:
// take the moment in time before calling the method
Instant start = Instant.now();
// then call the method
int[] array = createRandomArray(1000000);
// and take the moment in time after the method returned
Instant end = Instant.now();
// then calculate the duration
Duration duration = Duration.between(start, end);
// and print the duration in milliseconds
System.out.printf("Array creation took %d milliseconds\n", duration.toMillis());
}
The result is the following output on my system:
Array creation took 10 milliseconds

return values to main method

Ok this is making my brain melt!! the code compiles just fine but it refuses to display the correct answers in the displayAllResults method. Im not sure how to fix this at all. Ive tried making the methods private as well as having them return values instead of being void. as an example, the method sum gets the sum of the elements in array but will not display them. Im getting 0.
//Main
public class Lab_4_Practice {
public static void main(String[] args) {
//Declaring and initializing variables
int[] randomArray = new int[10];
int maxIndex = 0;
int minIndex = 0;
int total = 0;
double average = (total / randomArray.length);
//Call Methods
random(randomArray);
displayRandom(randomArray);
largest(maxIndex, randomArray);
smallest(minIndex, randomArray);
sum(total, randomArray);
average(total, randomArray);
sortArray(randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
}
//***************************************************
//Method assigns random values to elements
public static void random(int[] randomArray) {
for (int i = 0; i <randomArray.length; i++) {
randomArray[i] = (int)(Math.random() * 300);
}
}
//Method prints random values
public static void displayRandom(int[] randomArray) {
System.out.println("Here are 10 random numbers");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i]);
}
System.out.println("*************************");
}
//Method identifies largest index and its element in array
public static void largest(int maxIndex, int[] randomArray) {
for (int l = 1; l < randomArray.length; l++) {
if (randomArray[l] > randomArray[maxIndex]) {
maxIndex = l;
}
}
}
//Method identifies smallest index and its element in array
public static void smallest(int minIndex, int[] randomArray) {
for (int i = 1; i < randomArray.length; i++) {
if (randomArray[i] < randomArray[minIndex]) {
minIndex = i;
}
}
}
//Method calculates sum of elements
public static int sum(int total, int[] randomArray) {
for (int i = 0; i <randomArray.length; i++) {
total = total + randomArray[i];
}
return total;
}
//Method calculates average of elements
public static void average(int total, int[] randomArray) {
for (int i = 0; i < randomArray.length; i++) {
i += randomArray[i];
}
}
//Method sorts array in ascending order
public static void sortArray(int[] randomArray) {
for (int i = 0; i < randomArray.length - 1; i++) {
int currentMin = randomArray[i];
int currentMinIndex = i;
for (int j = i + 1; j < randomArray.length; j++) {
if (currentMin > randomArray[j]) {
currentMin = randomArray[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
randomArray[currentMinIndex] = randomArray[i];
randomArray[i] = currentMin;
}
}
}
//Method prints array in ascending order
public static void displaySorted(int[] randomArray) {
System.out.println("These are the same numbers sorted in ascending order");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i] + " ");
}
System.out.println("*************************");
}
//Method prints results of largest smallest sum and average
public static void displayAllResults(int[] randomArray, int maxIndex, int minIndex, int total, double average) {
System.out.println("The largest index is " + maxIndex + " and its value is " + randomArray[maxIndex]);
System.out.println("The smallest index is " + minIndex + " and its value is " + randomArray[minIndex]);
System.out.println("The sum of the elements is " + total);
System.out.println("The average of the elements is " + average);
}
}
Its always recommended that you do all your calculations/manipulations in a different class rather than in the main class itself. Create a different class and inside that code something like this -
public class Example{
public void assign(int[] Array){
for(int i=0;i<Array.length;i++){
Array[i]=(int)(Math.random()*300);
}
}
public void display(int[] Array){
System.out.println("The 10 elements of the array are:");
for(int i=0;i<Array.length;i++){
System.out.println(Array[i]);
}
}
public int sum(int[] Array) {
int total =0;
for(int i=0;i<Array.length;i++){
total=total+Array[i];
}
return total;
}
//write all other methods here in this class.
}
now in the main class inside the main method just declare the array and pass the array to the different functions as per your requirement, something like this -
public static void main(String[] args) {
int[] randomArray=new int[10];
Example e=new Example();
e.assign(randomArray);//this must be called first to assign the values inside the array.
e.display(randomArray);//call this method if you wish to display the values.
System.out.println("The sum of the elements are: "+e.sum(randomArray));
}
I have done little bit changes in your code. You can compare it with your old code. Most of the places you were facing problem because of local variable. Whatever you were supplying to corresponding method and after operation changes made on local variable is not affecting your instance variables. And for largest() and small() method(), you were calling it without sorting your array, because of that it was giving wrong output.
public class StackProblem {
public static void main(String[] args) {
// Declaring and initializing variables
int[] randomArray = new int[10];
int maxIndex = 0;
int minIndex = 0;
int total = 0;
double average = 0;
// Call Methods
random(randomArray);
displayRandom(randomArray);
sortArray(randomArray);
maxIndex=largest(randomArray);
minIndex=smallest(randomArray);
total=sum(randomArray);
average=average(total, randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
}
// ***************************************************
// Method assigns random values to elements
public static void random(int[] randomArray) {
for (int i = 0; i < randomArray.length; i++) {
randomArray[i] = (int) (Math.random() * 300);
}
}
// Method prints random values
public static void displayRandom(int[] randomArray) {
System.out.println("Here are 10 random numbers");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i]);
}
System.out.println("*************************");
}
// Method identifies largest index and its element in array
public static int largest(int[] randomArray) {
int maxIndex=0;
for (int l = 0; l < randomArray.length; l++) {
if (randomArray[l] > randomArray[maxIndex]) {
maxIndex = l;
}
}
return maxIndex;
}
// Method identifies smallest index and its element in array
public static int smallest(int[] randomArray) {
int minIndex=0;
for (int i = 0; i < randomArray.length; i++) {
if (randomArray[i] < randomArray[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
// Method calculates sum of elements
public static int sum(int[] randomArray) {
int localTotal=0;
for (int i = 0; i < randomArray.length; i++) {
localTotal+=randomArray[i];
}
return localTotal;
}
// Method calculates average of elements
public static int average(int total, int[] randomArray) {
return total/randomArray.length;
}
// Method sorts array in ascending order
public static void sortArray(int[] randomArray) {
for (int i = 0; i < randomArray.length - 1; i++) {
int currentMin = randomArray[i];
int currentMinIndex = i;
for (int j = i + 1; j < randomArray.length; j++) {
if (currentMin > randomArray[j]) {
currentMin = randomArray[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
randomArray[currentMinIndex] = randomArray[i];
randomArray[i] = currentMin;
}
}
}
// Method prints array in ascending order
public static void displaySorted(int[] randomArray) {
System.out.println("These are the same numbers sorted in ascending order");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i] + " ");
}
System.out.println("*************************");
}
// Method prints results of largest smallest sum and average
public static void displayAllResults(int[] randomArray, int maxIndex, int minIndex, int total, double average) {
System.out.println("The largest index is " + maxIndex + " and its value is " + randomArray[maxIndex]);
System.out.println("The smallest index is " + minIndex + " and its value is " + randomArray[minIndex]);
System.out.println("The sum of the elements is " + total);
System.out.println("The average of the elements is " + average);
}
[Nobody supports my motion to put this on hold due to [duplicate] - so I feel compelled to write an answer here.]
This is the typical pattern for a method calculating some value from the elements of an array:
public static int largest(int[] array) {
int maxIndex = 0;
for (int l = 1; l < array.length; l++) {
if (array[l] > array[maxIndex]) {
maxIndex = l;
}
}
return maxIndex;
}
And you call it like this:
int maxIndex = largest( randomArray );
Parameters with a type of int, long, double, char, short, float, boolean are copied "by value", i.e., the corresponding expression in the call - the actual parameter - is evaluated and the result is stored in a variable with the name of the parameter. This variable is short-lived: when you return from the method call, it is gone. The only way to hand back the value is by using the return mechanism in a non-void method.
If you have an array however, things are a little different. An array is an object, and objects are handled via references, values that tell the computer where the object can be found. This reference is also copied from the point of invocation and stored in a short-lived variable, but you still can access the object it references so that changes of an array (or any object) are possible via code in a method with an object reference as a parameter.
Finally, the code for calculating the average is very much in error.
public static double average( int[] array ) {
return (double)sum( array )/array.length;
}
and you need a variable of type double to hold the result. (There is a chance that an array might have the length 0, so I'm a little careless there. Do you see why?)
The variables you are passing to each method are all zero. You need to change those within the main method, since variables in methods are only used and modified within their respective methods, even if they were passed to that method from the main method. It looks like this is what you want:
randomArray = random(randomArray);
displayRandom(randomArray);
maxIndex = largest(maxIndex, randomArray);
minIndex = smallest(minIndex, randomArray);
total = sum(total, randomArray);
average(total, randomArray); //not sure what you're trying to do here; this method does not calculate the average
average = total/randomArray.length; //you probably just want to use this instead of the average() method
randomArray = sortArray(randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
Additionally, for each method that is supposed to return a value, you will need to change the return type in the method header from void to the appropriate variable type, as well as add a return statement at the end of each method.

Write an object oriented program that randomly generates an array of 1000 integers between 1 to 1000

this code doesn't function,
it said that lessthaAverage(int) in calculateArray cannot be applied to (), I'm a beginner so I still don't understand this coding yet, this is the question ask, Write an object oriented program that randomly generates an array of 1000 integers between 1 to 1000.
Calculate the occurrences of number more than 500 and find the average of the numbers.
Count the number which is less than the average and finally sort the numbers in descending order.
Display all your output. Please do HELP ME!!!,Thank You...
import java.util.*;
import java.io.*;
//import java.util.random;
public class CalculateArray
{
//declare attributes
private int arr[] = new int[1000];
int i;
//generates an array of 1000 integers between 1 to 1000
public void genArr()
{
Random ran = new Random();
for(i = 0; i < arr.length; i++)
{
arr[i] = ran.nextInt(1000) + 1;
}
}
//Calculate the occurences of number more than 500
public int occNumb()
{
int count;
for(i = 0; i < arr.length; i++)
{
if(arr[i] > 500)
{
count++;
}
}
return count;
}
//find the average of the numbers
public int average()
{
int sum, aver;
for(i = 0; i < arr.length; i++)
{
sum += arr[i];
}
aver = sum/1000;
return aver;
}
//Count the number which is less than the average
public int lessthanAverage(int aver)
{
int cnt;
cnt = 0;
for(i = 0; i < arr.length; i++)
{
if(arr[i] < aver)
{
cnt++;
}
}
return cnt;
}
//finally sort the numbers in descending order.
public void sort(int[] num)
{
System.out.println("Numbers in Descending Order:" );
for (int i=0; i <= num.length; i++)
for (int x=1; x <= num.length; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
//Display all your output
public void display()
{
int count, aver;
System.out.println(arr[i] + " ");
System.out.println("Found " + count + " values greater than 500");
System.out.println("The average of the numbers is " + aver);
System.out.println("Found " + count + " values that less than average number ");
}
public static void main(String[] args)
{
CalculateArray show = new CalculateArray();
show.genArr();
int c= show.occNumb();
show.average();
int d=show.lessthanAverage();
show.sort(arr);
show.display();
}
}
Your method lessthanAverage is expecting a int parameter. You should store the result of the average method call into a int variable and pass it to the call to lessthanAverage.
int avg = show.average();
int d=show.lessthanAverage(avg);
Your lessthaAverage() method expects an average to be passed in as a parameter, but you are not passing it in when you call it.
It seems that your method lessthanAverage needs an int as a parameter, but you are not passing it in main
public int lessthanAverage(int aver)
In main aver is not being passed:
int d=show.lessthanAverage(); // where is aver?
But if you wanted to know the average inside the method you could call your average method inside lessthanAverage:
if(arr[i] < this.average())
and not pass any parameter at all:
public int lessthanAverage()

Categories