How to display methods in the console that read from a file? - java

I need to be able to display the Average, ColumnTotal, Highest/Lowest in row, RowTotal. I'm not sure whether it depends on something I did in the methods themselves that has to be changed, or if I can simply that call them with the correct arguments to read from a file. The text file that it reads from basically just inputs two integers that are separated by a space on the same line, those are the arguments I would like to be able to input. I'm not entirely sure how to do this. This is just an assignment from a College text book basically amped up by my Instructor called "TwoDimArray" which I've been able to find many examples of online but none of them had the 'read from file' portion that I have to do here, they all just used a normal array input such as "int[][] array = {{22, 37, 48, 68}} for the main method. I'm going to include the entire program in order to show exactly what I need to be displayed via println. I've been thinking about how to do this for quite a few hours now and decided that I definitely need help. Any help would be greatly appreciated! Thanks ahead of time.
import javax.swing.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TwoDimArray {
private int arr[][];
public TwoDimArray() {
loadArray();
}
public void loadArray(){
/**
* loadArray() method loads user defined filename
* #return text file's contents
*/
String fileName = "";
try {
fileName = JOptionPane.showInputDialog("Enter file name: ");
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "can not open " + fileName + " to read");
return;
}
try {
Scanner in = new Scanner(new File(fileName));
int rows, cols;
rows = in.nextInt();
cols = in.nextInt();
arr = new int[rows][cols];
for(int i = 0; i < rows; ++i){
for(int j = 0; j < cols; ++j){
arr[i][j] = in.nextInt();
}
}
in.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "can not open " + fileName + " to read");
}
}
public int getArrayMaxValue(){
/**
* #return the max vale of the array
*/
int maxVal = Integer.MIN_VALUE;
for(int i = 0; i < arr.length; ++i){
for(int j = 0; j < arr.length; ++j){
if(arr[i][j] > maxVal){
maxVal = arr[i][j];
}
}
}
return maxVal;
}
public int getArrayMinValue(){
/**
* #return the minimum value of the array
*/
int minVal = Integer.MAX_VALUE;
for(int i = 0; i < arr.length; ++i){
for(int j = 0; j < arr.length; ++j){
if(arr[i][j] < minVal){
minVal = arr[i][j];
}
}
}
return minVal;
}
public static int getTotal(int[][] array) {
int total = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
total += array[row][col];
}
}
return total;
}
public static int getAverage(int[][] array) {
return getTotal(array) / getElementCount(array);
}
public static int getRowTotal(int[][] array, int row) {
int total = 0;
for (int col = 0; col < array[row].length; col++) {
total += array[row][col];
}
return total;
}
public static int getColumnTotal(int[][] array, int col) {
int total = 0;
for (int row = 0; row < array.length; row++) {
total += array[row][col];
}
return total;
}
public static int getHighestInRow(int[][] array, int row) {
int highest = array[row][0];
for (int col = 1; col < array[row].length; col++) {
if (array[row][col] > highest) {
highest = array[row][col];
}
}
return highest;
}
public static int getLowestInRow(int[][] array, int row) {
int lowest = array[row][0];
for (int col = 1; col < array[row].length; col++) {
if (array[row][col] < lowest) {
lowest = array[row][col];
}
}
return lowest;
}
public static int getElementCount(int[][] array) {
int count = 0;
for (int row = 0; row < array.length; row++) {
count += array[row].length;
}
return count;
}
public static void main(String[] args){
/**
* what to put in int[][] array to allow println of average, getrowtotal,
* etc..
*/
int[][] array = ???;
TwoDimArray twoDimArray = new TwoDimArray();
System.out.println("Max value: " + twoDimArray.getArrayMaxValue());
System.out.println("Min value: " + twoDimArray.getArrayMinValue());
System.out.println(getAverage(array));
}
}

0) Create numbers.txt in the root of your project. This is the file you will load array from. Example content as follows (2 rows, 3 columns):
2 3
1 2 3
4 5 6
1) You don't need your explicitly created int[][] array = ??? because there is already existing private int arr[][] which will be automatically loaded from file after you type it's name as intended in TwoDimArray constructor.
2) Since main method located at the same class as private int arr[][], you can access this private array without public getter/setter, and get average value like this:
// you don't need following line at all
// int[][] array = ???;
TwoDimArray twoDimArray = new TwoDimArray();
System.out.println("Max value: " + twoDimArray.getArrayMaxValue()); // Max value: 5
System.out.println("Min value: " + twoDimArray.getArrayMinValue()); // Min value: 1
// Average value
System.out.println(getAverage(twoDimArray.arr)); // 3, because 21 / 6 = 3
3) You probably got confused because getArrayMaxValue is signed as public int, and got invoked as twoDimArray.getArrayMaxValue(), whereas getAverage is public static int and must be called in different way.
I suggest marking getAverage as public int instead of public static int, and use private int arr[][] instead of int[][] array provided from arguments, so you will be able to call it the same way you do with other methods:
// Somewhere up
public int getAverage() {
return getTotal(arr) / getElementCount(arr);
}
// In your main method
System.out.println(twoDimArray.getAverage());

Basically, what you have there is a jagged array, it is not a bidimensional array. I will explain you the idea, you do the rest. That it is not a bidimensional array. This is an array of array, in each position you are pointing to a new array of int. If you never instantiated a new array on each position, then you have a position with a null value.
So going back with your question, you should read the entire line with the two integers that are on the same line. Be sure that the line in your file has in the first line 2 numbers separated by a space.
Then use the next() method to get the complete string
String line = in.next();
String[] parts = line.split(" ");
int val1 = Integer.parseInt(parts[0]);
int val2 = Integer.parseInt(parts[1]);
For this question:
what to put in int[][] array to allow println of average, getrowtotal,
int[][] array = new int[4];
array[0] = new int[] {10,20,30,40,50};
array[1] = new int[] {60,71,80,90,91};
array[2] = new int[] {1};
Hope this helps
Now, what do you think you have in array[3]? The answer is: NULL

you already read the array from file in your method loadArray...
Use it instead of trying to load the same thing again, remove static modifier from all method and use field arr instead of parameter array
private int getTotal() {
int total = 0;
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
total += arr[row][col];
}
}
return total;
}
private int getAverage() {
return getTotal() / getElementCount();
}
private int getElementCount() {
int count = 0;
for (int row = 0; row < arr.length; row++) {
count += arr[row].length;
}
return count;
}
public static void main(String[] args) {
TwoDimArray twoDimArray = new TwoDimArray();
System.out.println("Max value: " + twoDimArray.getArrayMaxValue());
System.out.println("Min value: " + twoDimArray.getArrayMinValue());
System.out.println(twoDimArray.getAverage());
}

Related

Finding rows and columns with the maximum number of 1s in a randomly generated binary matrix

The output of this program works fine. But there's one thing I've not been able to implement. In some cases, I don't have a row or column with the highest number of 1s. Sometimes I have 2 or more rows/columns which have the same "HIGHEST" number of ones. But my program only returns 1 row/column.
I want a case whereby If i have more than 2 rows/columns with the same highest number of 1s. Both rows will be displayed. e.g. "Row(s) with the most 1's: 1,2" or if it's a column it can say "Row(s) with the most 1's: 1,2".
Please I need help with this. I'm stuck.
import java.util.Random;
import java.util.Scanner;
public class LargestRowColumn
{
// declare a 2 dimensional array or an array of arrays
private static int[][] randArray;
public static void main(String[] args)
{
do
{
// Create a scanner to get Input from user.
Scanner scanner = new Scanner(System.in);
System.out.print("\nEnter the array size n:");
int rows = scanner.nextInt();
int cols = rows;
randArray = new int[rows][cols];
// loop through the number of rows in thw array
for (int i = 0; i < randArray.length; i++)
{
// loop through the elements of the first array in the array
for (int j = 0; j < randArray[0].length; j++)
{
// set a random int 0-1 to the array
randArray[i][j] = getRandomInt(0, 1);
// print the number just assigned
System.out.print(randArray[i][j]);
}
// make a linebreak each row.
System.out.println();
}
System.out.print("Row(s) with the most 1's: " + scanRow(randArray) + "\n");
System.out.print("Columns(s) with the most 1's: " + scanColumn(randArray) + "\n");
}
while(true);
}
// quick method I made to get a random int with a min and max
public static int getRandomInt(int min, int max)
{
Random rand = new Random();
return rand.nextInt(max-min+1)+min;
}
public static int scanRow(int[][] array)
{
int result = -1;
int highest = -1;
for (int row = 0; row < array.length; row++)// Here we are about start looping through the matrix values
{
int temp = 0; // Setting the first index to 0.
for (int col = 0; col < array[row].length; col++)//
{
//Assign current location to temporary variable
temp = temp + array[row][col];
}
if (temp > highest)
{
highest = temp;
result = row + 1;
}
}
return result;
} // end of row method
private static int scanColumn(int[][] array)
{
int result = -1;
int highest = -1;
// declare and initialize the variable(here you've 'created' it, to then call it on if statement)
int col = 0;
for (int row = 0; row < array.length; row++)
{
int temp = 0;
//declare the variable in the for loop
for (col = 0; col < array[row].length; col++)
{
//Assign current location to temp variable
temp = temp + array[row][col];
}
if (temp > highest)
{
highest = temp;
result = col;
}
}
return result;
}
}
I would suggest a different approach, first thing why do you need to loop all over the 2D array again , u can figure out the highest 1's in rows and columns while inserting them and insert them in an array ( array of rows and array for columns) the carry will be of custom type which is a class with two parameters , score(which is number of 1's) and index( which is the number of the row or column), then sort the arrays and print the indexes related to top scores.
if you are expecting to receive the array with the inputs you can do the same but with new loop.
so your insert loop will be like this
List<Wrapper> rowsList = new ArrayList<Wrapper>(rows);
List<Wrapper> colsList = new ArrayList<Wrapper>(cols);
for(int i=0;i<cols;i++) {
colsList.add(new Wrapper(i,0));
}
// loop through the number of rows in thw array
for (int i = 0; i < rows; i++)
{
int sum =0;
// loop through the elements of the first array in the array
for (int j = 0; j < cols j++)
{
// set a random int 0-1 to the array
randArray[i][j] = getRandomInt(0, 1);
// print the number just assigned
System.out.print(randArray[i][j]);
sum+=randArray[i][j];//add for row
colsList.get(j).setScore(colsList(j).getScore() +randArray[i][j]);//add for column
}
rowsList.add(new Wrapper(i,sum));
// make a linebreak each row.
}
Collections.sort(rowsList,new Comparator<Wrapper>() {
#Override
public int compare(Wrapper obj1,Wrapper obj2) {
if(obj1.getScore() > obj2.getScore())
return -1;
if(obj1.getScore() < obj2.getScore())
return 1;
return 0;
}
});
if(rowsList.isEmpty())
return -1;
int max = rowsList.get(0).getScore();
for(Wrapper obj:rowsList) {
if(obj.getScore()< max)
break;
System.out.println(obj.getIndex);
}
//DO THE SAME FOR COLUMNS
your wrapper class will be
public class Wrapper {
private int index;
private int score;
public Wrapper(int index,int score) {
this.index = index;
this.score = score;
}
public int getIndex() {
return this.index;
}
public int getScore() {
return this.score;
}
public void setScore(int score) {
this.score = score
}
}
This is in keeping with the OP use of arrays.
Instead of returning an int, which would be one row, you can return int[].
Personally, I would init the int[] to the number of rows in the array, because what if every row has the same number of 1's?
int[] results = new int[array[0].length];
Then, instead of adding in the rows, I would have a variable used to designate which spot to add the row to, i.e., results[0] etc.
int index = 0;
Then, all it takes is a small adjustment to how you add your results to the array.
public static int[] scanRow(int[][] array)
{
int highest = -1;
int index = 0; //ADD HERE
int[] results = new int[array[0].length]; //ADD HERE
... //Your code here
if (temp > highest)
{
highest = temp;
//CLEAR THE RESULT LIST
for(int x = 0; x < results.length; x++){
results[x] = -1;
}
index = 0; //RESET THE INDEX
results[index] = row + 1;
index ++;
} else if (temp == highest{
highest = temp;
results[index] = row + 1;
index ++;
}
}
return results;
} // end of row method
Personally, I would use an ArrayList for these types of things, so heres how I would do it using it.
I would make the return type of the method an ArrayList<int>.
public static ArrayList<int> scanRow(int[][] array)
Then declare my ArrayList<int>
ArrayList<int> results = new ArrayList<>();
and the if statements are a little easier to handle, since ArrayList as a clear() and add() method.
if (temp > highest)
{
highest = temp;
//CLEAR THE RESULT LIST
results.clear();
results.add(row+1);
} else if (temp == highest{
highest = temp;
results.add(row + 1);
}
EDIT
Don't forget to edit your print statements accordingly.

2D Array Methods & Demo

I have an assignment to design and implement methods to process 2D Arrays.
It needs to have an implementation class (Array2DMethods) that has the following static methods:
readInputs() to read the number of rows and columns fro the user then reads a corresponding entry to that size. Ex: if a user enters 3 for # of rows and 3 for # of columns it'll declare an array of 10 and reads 9 entries.
max(int [][] anArray) it returns the max value in the 2D parameter array anArray
rowSum(int[][] anArray) it returns the sum of the elements in row x of anArray
columnSum(int[][] anArray) it returns the sum of the elements in column x of anArray **careful w/ rows of different lengths
isSquare(int[][] anArray) checks if the array is square (meaning every row has the same length as anArray itself)
displayOutputs(int[][] anArray) displays the 2 Dim Array elements
It also needs a testing class (Arrays2DDemo) that tests the methods.
I've commented the parts I'm having problems with. I'm not sure how to test the methods besides the readInputs method and also not sure how to format the part where you ask the user to enter a number for each row.
Here's my code so far:
import java.util.Scanner;
class Array2DMethods {
public static int [][] readInputs(){
Scanner keyboard = new Scanner(System.in);
System.out.print(" How many rows? ");
int rows = keyboard.nextInt();
System.out.print(" How many columns? ");
int columns = keyboard.nextInt();
int [][] ret = new int[rows][columns];
for (int i = 0; i<ret.length; i++) {
for (int j = 0; j < ret[i].length; j++) {
System.out.print("please enter an integer: "); //Need to format like Enter [0][0]: ... Enter [0][1]: ...etc.
ret[i][j] = keyboard.nextInt();
}
}
return ret;
}
public static int max(int [][] anArray) {
int ret = Integer.MIN_VALUE;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
if (anArray[i][j] > ret) {
ret = anArray[i][j];
}
}
}
return ret;
}
public static void rowSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i<anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static void columnSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static boolean isSquare(int[][]anArray) {
for (int i = 0, l = anArray.length; i < l; i++) {
if (anArray[i].length != l) {
return false;
}
}
return true;
}
public static void displayOutputs(int[][]anArray) {
System.out.println("Here is your 2Dim Array:");
for(int i=0; i<anArray.length; i++) {
for(int j=0; j<anArray[i].length; j++) {
System.out.print(anArray[i][j]);
System.out.print(", ");
}
System.out.println();
}
}
}
Class Arrays2DDemo:
public class Arrays2DDemo {
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int [][] anArray = Array2DMethods.readInputs();
Array2DMethods.max(anArray);
Array2DMethods.rowSum(anArray);
//need to print out and format like this: Ex Sum of row 1 = 60 ...etc
Array2DMethods.columnSum(anArray);
//need to print out and format like this: Ex Sum of column 1 = 60 ...etc.
Array2DMethods.isSquare(anArray);
//need to print out is this a square array? true
Array2DMethods.displayOutputs(anArray);
//need it to be formatted like [10, 20, 30] etc
}
}
Assuming you want anArray to be the array you read in during your inputting, you should name that variable, as such...
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int[][] anArray = Array2DMethods.readInputs();
System.out.println("max " + Array2DMethods.max(anArray));
Array2DMethods.rowSum(anArray);
Array2DMethods.columnSum(anArray);
System.out.println("Square " + Array2DMethods.isSquare(anArray));
Array2DMethods.displayOutputs(anArray);
}
Say you have a function f which takes a single input x. The problem is you're asking the computer to evaluate f(x) without ever telling it what x is. If you give x a value, however, such as x = 3, then asking f(x) becomes legal, because it becomes f(3), which can be evaluated.

print 2 dimentional array center aligned

Hi I am trying to print a two dimensional array that is center aligned but the numbers point to the memory cell if im correct. How would I go about getting them to print the actual numbers, Ive tried creating a display method and that didnt work. Here is my code so far. I am also going to be finding the min, max and avg after I figure this out.
import java.util.Scanner;
public class Print2DArray {
public static void main(String[] args) {
Scanner print2d = new Scanner(System.in);
System.out.println("Please enter the number of rows: ");
int rows = print2d.nextInt();
System.out.println("Please enter the number of columns: ");
int columns = print2d.nextInt();
int array[][] = new int[rows][columns];
System.out.println("\nVictor - 002017044\n");
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[x].length; y++) {
int value = (int) (Math.random() * 10000);
value = (int) (Math.round((value * 100)) / 100.0);
array[x][y] = value;
}
}
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[x].length; y++) {
printArray(array);
}
System.out.println();
}
int max = 0;
int avg = 0;
int min = 0;
System.out.println("\nMaximum: " + max + "\nAverage: " + avg
+ "\nMinimum: " + min);
}
private static void printArray(int [][] array){
int width = 6;
int leftSP = (width - array.length)/2;
int rightSP = width - array.length - leftSP;
for (int i = 0; i < leftSP; i++) {
System.out.print(" ");
}
System.out.print(array);
for (int i =0; i < rightSP; i++) {
System.out.print(" ");
}
}
}
I'm not quite sure what you mean by center aligned in this context. Centering something requires you to know how much space you are allowed to print to and then evenly distributing what you are displaying to both sides of the width/2. For example, by default, in cmd.exe you are limited to 80 characters across, but this can be changed. However, I think the core of this answer is here:
Can I find the console width with Java?
Basically, you can't center it. The best you can hope for is to left align it (or attempt to center it based on some arbitrary pre-determined width).
Based on what you wrote though, and what I see in printArray, your other issue is that you don't know how to print out a value at an index of an array. Before I address that, I must address something you wrote
but the numbers point to the memory cell if im correct
This is actually incorrect. This is the default functionality of the toString method, per the java.lang.Object#toString method:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString%28%29
Your print method should probably look like:
private static void printArray(int [][] array){
if(array == null || array.length < 1 || array[0].length < 1)
throw new IllegalArgumentException("array must be non-null, and must have a size of at least \"new int[1][1]\"");
for (int i = 0; i < array.length; i++) {
for(int j = 0; j < array[0].length; j++)
System.out.print("[" + array[i][j] + "]");
System.out.println();
}
}
EDIT:
I saw a comment you made in which you specify what you mean by center aligned. Basically you will want to record the maximum length of any int you are placing into the array, like the following:
//global max value
public static int maxLength = 0;
...
//inside of Print2DArray.main(String [] args)
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[x].length; y++) {
value = (int) (Math.round((value * 100)) / 100.0);
int numberOfDigits = String.valueOf(value).length();
if(numberOfDigits > Print2DArray.maxLength)
Print2DArray.maxLength = numberOfDigits;
array[x][y] = value;
}
}
Then you will want to adjust your printArray function's print from
System.out.print("[" + array[i][j] + "]");
to
System.out.printf("[%" + Print2DArray.maxLength + "d]", array[i][j]);
first fix bug
for (int y = 0; y < array[x].length; y++) {
printArray(array[x][y]);//chage printArray(array) to printArray(array[x][y])
}
second modify printlnArray
private static void printArray(int v){
System.out.format("%-8s",String.valueOf(v));
}
center-align
private static int[] widthes = {9,99,999,9999,99999};
private static int numberWidth(int v) {
for (int i = 0; i < widthes.length; i++) {
if(widthes[i] > v) return (i+1);
}
return -1;
}
private static void printArray(int v){
int width = 8;
int numberWidth = numberWidth(v);
int left = (width-numberWidth)/2;
int right = width - numberWidth - left;
for (int i = 0; i < left; i++) {
System.out.print(" ");
}
System.out.print(v);
for (int i = 0; i < right; i++) {
System.out.print(" ");
}
}
more reference
How to align String on console output

Exception in thread main error in array program

// getting exception in thread main error in result[row][col]= arrayfirst [row][col] + arraysecound [row[col];
public class apples
public static void main(String args[])
{
int arrayfirst[] [] ={{1,2,3},{2,3,4}};
int arraysecound[] [] ={{3,4,5},{6,7,8}};
int result[][]= new int [2][2];
for(int row =0; row<arrayfirst.length; row++)
{
for(int col =0; col<arrayfirst[row].length; col++)
{
result[row][col]= arrayfirst [row][col] + arraysecound [row][col];
}
}
for(int row =0; row<arrayfirst.length; row++) {
for(int col =0; col<arrayfirst[row].length; col++) {
System.out.print(" "+result[row][col]);
}
System.out.println();
}
}
}
// BUT THESE SIMILAR PROGRAMS RUNS CORRECTLY WHY
public static void main(String args[])
{
int arrayA[][] = {{1,4,3,5},{3,8,1,2},{4,3,0,2},{0,1,2,7}};
int arrayB[][] = {{6,1,0,8},{3,2,1,9},{5,4,2,9},{6,5,2,0}};
int arrayC[][] = new int[4][4];
for(int i = 0; i < arrayA.length; i++) {
for(int j = 0; j< arrayA[0].length; j++) {
arrayC[i][j] = arrayA[i][j] + arrayB[i][j];
// System.out.print(arrayC[i][j] + " ");
} // end j for loop
} // end i for loop
for (int i = 0; i < arrayC.length; i++) {
for (int x = 0; x < arrayC[i].length; x++) {
System.out.print(arrayC[i][x] + " | ");
}
System.out.println();
}
} // end main
} // end class
int arrayfirst[] [] ={{1,2,3},{2,3,4}};
int arraysecound[] [] ={{3,4,5},{6,7,8}};
here, arrayfirst and arraysecound contain two rows and three columns each (The number of inner curly braces separated by Comma signify number of rows, and the numbers written within these inner curly braces signify number of columns), so when you add their elements and try to store the result, you again need an array that has two rows and three columns.
so, just replace
int result[][]= new int [2][2];
with
int result[][]= new int [2][3];
Your result array in the first program is too small.
Change following
int result[][]= new int [2][2];
to
int result[][]= new int [2][3];
Also, to learn more about arrays in java, have a look at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

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