Having trouble adding methods - java

Add three methods, one that will return the maximum value in the array (FindMax), one that will return the minimum value in the array (FindMIn) and one that will return the average of the values in the array (FindAvg).
import java.util.Scanner;
public class methods {
public static void main(String[] args) {
int [] numbrs;
numbrs = new int[25];
int i = 0;
System.out.println();
populateArray(numbrs, numbrs.length);
System.out.println("\n********** the array reversed is **********\n");
for (i = numbrs.length - 1; i >= 0; i--)
System.out.println(numbrs[i]);
System.out.println("\n***** end of Array01.java *****");
} // end of main method
/* ********************************************************
Pre Condition: an array of n integers where n is given.
Post Condition: an array populated with randomly
generated integers in the range of 1 to limit
specified by the user.
******************************************************** */
public static void populateArray(int [] arry, int lm) {
Scanner kBd;
int lim = 0;
kBd = new Scanner(System.in);
System.out.print("Enter the upper limit of random numbers...");
lim = kBd.nextInt();
System.out.println();
int x = 0;
for(int i = 0; i < lm; i++) {
arry[i] = getRandomInt(lim);
System.out.println(arry[i]);
}
} // end of populateArray method
/* ********************************************************
Pre Condition: an integer for the upper limit of the
random number to generate.
Post Condition: an integer in the range of 1 to limit
******************************************************** */
public static int getRandomInt(int limit) {
return (1 + (int)(Math.random() * limit));
} // end of getRandomInt method
public static int max(int highest) {
} // end of class Array01

Merry Christmas. I am in a giving mood today. This is how you figure out the greatest value in the array:
public static int max(int[] array)
{
int highest = array[0];
for (int i = 1; i < array.length; i++)
{
if (array[i] > highest)
{
highest = array[i];
}
}
return highest;
}
Basically, assume the first stored value is the greatest value and compare it to the next value. If the next value is the greatest, assign to highest variable. Continue iterating through the array until you examine each and every value. One pass, and you are done.

Related

invoke a method named printArray that prints my random numbers array

So far i have made a random numbers array but i am stuck on how to make a printarray method that i can call within the main. I need to invoke print array in the same class and print out all elements separated by one space
public class HunterIsaacsHw6
{
public static void main(String[] args)
{
System.out.println("Java, Online, Hunter Isaacs, hw6");
// define the range
int max = 100;
int min = 1;
int range = max - min + 1;
// combining both statements in one
double doubleArray[] = new double[10];
// generate random numbers within 1 to 10
for (int i = 0; i < 10; i++) {
doubleArray[i] = (Math.random() * range) + min;
}
}
public static double printArray(doubleArray[]){
for(double n: doubleArray){
System.out.println(n+" ");
}
}
Your method declaration is incorrect and you are not even calling it. Try:
public static void main(String [] args)
{
System.out.println("Java, Online, Hunter Isaacs, hw6");
// define the range
int max = 100;
int min = 1;
int range = max - min + 1;
// combining both statements in one
double doubleArray[] = new double[10];
// generate random numbers within 1 to 10
for (int i = 0; i < 10; i++) {
doubleArray[i] = (Math.random() * range) + min;
}
printArray(doubleArray);
}
public static void printArray(double doubleArray[]){
for(double n: doubleArray){
System.out.println(n);
}
}
Also, nothing is being returned from printArray so it should be declared as void
Also I prefer the declaration as double[] doubleArray
edit
Also System.out.println(n); is sufficient, there is no need to append a space

Calculating the sum and average of a random array

I am trying to create 3 methods which calculate the sum and average of a random array then outputting the result.
I am trying to get an output similar to -
java RandomArray 5
9 7 2 1 4
Sum: 23
Mean: 4.6
but I am getting "Usage: java RandomArray . Example: java RandomArray 5"
if you can spot the errors in my code and help with how to get this output.
public class RandomArray {
private int[] numbers; //instance variable
/**
* Constructor
*
*#param size The size of the array
*/
public RandomArray(int size){
numbers = new int[size];
for(int i=0; i<numbers.length;i++){
numbers[i] = (int)(Math.random()*10); // a random number between 0-9
}
}
/**
* a method to print the array elements
*/
public void printArray() {
for (int i = 0; i < numbers.length; i++)
System.out.print(i + " ");
}
/**
* A method to calculate the sum of all elements
*
*#return The sum
*/
public int calSum(){
int sum = 0;
for (int value : numbers) {
sum += value;
}
return sum;
}
/**
* A method to calculate the mean of all elements
*
*#return The mean
*/
public double calMean() {
int sum = calSum();
int length = numbers.length;
return (double) sum / length;
}
/**
* a method to print the array elements in reverse order
*/
public void printReverse(){
}
/**
* A main method to test
*/
public static void main(String[] args) {
// Check to see if the user has actually sent a paramter to the method
if (args.length != 1){
System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
System.exit(-1);
}
// Create an instance of the class
RandomArray test = new RandomArray(Integer.parseInt(args[0]));
// Print the array
test.printArray();
// Calculate the sum of all the values in the array and print it
System.out.println("Sum: "+ test.calSum());
// Calculate the mean of all the values in the array and print it
System.out.println("Mean: "+ test.calMean());
System.out.print("Reverse: ");
test.printReverse();
}
}
Let’s look at your sum method first:
public int calSum(int sum) {
int sum = 0;
for (int value : numbers) {
sum += value;
}
return sum;
}
Why does this method accept a parameter? You just redeclare it on the next line anyway.
Looks good otherwise.
Here’s a cleaned up version:
public int calSum() {
int sum = 0;
for (int value : numbers) {
sum += value;
}
return sum;
}
Next up, mean average:
public double calMean(int[] array){
//Unsure which elements go here
}
Again, why the parameter?
Recall how we calculate the mean average: sum all elements, then divide by the number of elements.
We’ve already got a method for calculating the sum, so we can use that.
public double calMean() {
int sum = calSum();
int length = numbers.length;
return (double) sum / length;
}
Note the use of (double) here. Without it, cal / length would be integer division, and the result would be rounded to the nearest whole number.
Your method "printArray(int sum)" has the mistake. When you call the method you take a parameter sum, which is not needed. Then you try to create a second local variable with the name sum. This is impossible, because you already have a parameter called sum.
In your for loop you init antoher local variable called sum. You need a different name for that variable, since you only need it for counting the loop.
So remove your parameter sum and rename the variable used in the for loop.
This should work:
import java.util.Arrays;
public class ArrayCalculations
{
private int[] numbers;
public ArrayCalculations(int size)
{
this.numbers = new int[size];
for (int i = 0; i < size; i++)
{
int randomNumber = (int) (Math.random() * 10);
numbers[i] = randomNumber;
}
}
public int calculateSum()
{
int sum = 0;
for (int i = 0; i < numbers.length; i++)
{
sum += numbers[i];
}
return sum;
}
public float calculateAverage()
{
float sum = (float) calculateSum();
return sum / numbers.length;
}
public void printArray()
{
System.out.println(Arrays.toString(numbers));
}
public static void main(String[] args)
{
ArrayCalculations ac = new ArrayCalculations(5); // initiates an array with 5 elements
ac.printArray(); // prints the array to console
System.out.println("The sum is: " + ac.calculateSum()); // prints the sum
System.out.println("The average is: " + ac.calculateAverage()); // prints the average
}
}

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.

Selection sort Algorithm in Java

I'm having some trouble sorting an array. I'm trying to sort it in ascending order.
My task is to get a series of integers from the user and store them into an array, then display them back to the user in ascending order. I was fine getting input from the user, storing it in the array and displaying them back. I was able to run my code and get the results I wanted but as far as getting the integers in the array in ascending order using selection sort, I was having a lot of difficulty with that.
The size of the array depends on the value that the user inputs, so it is set to the variable numValues rather than a number.
I get an error with the sort method I created. I'm getting syntax errors and void is an invalid type. I think I'm missing something and I'm not sure how to go about fixing this. If someone can point me in the right direction. Any help would be appreciated.
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + "");
}
System.out.println("Here are the values you've entered, in ascending order");
/*
* Method to arrange values in ascending order
*/
private static void sort(int[] values) {
int scan;
int index;
int minIndex;
int minValue; // Variables to put values in ascending order
for(scan=0; scan < (values.length-1); scan++)
{
minIndex = scan;
minValue = values[scan];
for(index = scan+1; index < values.length; index++)
{
if(values[index] < minValue)
{
minValue = values[index];
minIndex = index;
} // End if
} //End for
values[minIndex] = values[scan];
values[scan] = minValue;
} // End for loop
/*
* For loop to display values
*/
for(int n=0; n < values.length; n++ )
{
System.out.print(values[scan] + " ");
} //End for
} // End method sort
keyboard.close(); // To close Scanner object
} //End method main
You cannot have another method inside main. Get the method sort(int[] values) out of main, and call it inside main.
You had another problem. Inside your sort method:
System.out.print(values[scan] + " ");
scan has to be replaced by n.
Here is the completed code:
import java.util.*;
public class Project {
public static void main(String[] args) {
int numValues; // The number of values user has
int [] values; // Array declaration for values
Scanner keyboard = new Scanner(System.in); // Scanner object to get input from user
System.out.println("How many values do you have?"); // To get number of values for array
numValues = keyboard.nextInt();
/*
* Array to hold number of values
*/
values = new int [numValues];
/*
* Loop to gather integer values
*/
for (int n=0; n < values.length; n++ )
{
System.out.print("Enter value " + (n+1) + ":" );
values[n] = keyboard.nextInt();
} //End for loop
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + " ");
}
System.out.println("Here are the values you've entered, in ascending order");
sort(values);
keyboard.close(); // To close Scanner object
}
/*
* Method to arrange values in ascending order
*/
private static void sort(int[] values) {
int scan;
int index;
int minIndex;
int minValue; // Variables to put values in ascending order
for(scan=0; scan < (values.length-1); scan++)
{
minIndex = scan;
minValue = values[scan];
for(index = scan+1; index < values.length; index++)
{
if(values[index] < minValue)
{
minValue = values[index];
minIndex = index;
} // End if
} //End for
values[minIndex] = values[scan];
values[scan] = minValue;
} // End for loop
/*
* For loop to display values
*/
for(int n=0; n < values.length; n++ )
{
System.out.print(values[n] + " ");
} //End for
} // End method sort
} // End class Project
Your program will not executed or will not display correct result due to some reasons.
You are using "private static void sort(int[] values)" method in main method and it's not possible because we can't define method in another method. Either you have to create a separate method outside of main method or you can use sorting functionality in your main method also.
Another mistake is in below code. You are using scan variable for displaying result in ascending order. Here is should be n.
for(int n=0; n < values.length; n++ )
{
System.out.print(values[scan] + " ");
}
Your logic is correct. But it's little bit large for selection sort. Below is small way to do this.
public class SelectionSort
{
public static void main(String[]args)
{
int [] values = {15,14,13,12,11};
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + "");
}
System.out.println("\nHere are the values you've entered, in ascending order");
sort(values);
}
private static void sort(int[] values)
{
int index = 0;
int index2 = 0;
int temp = 0;
for(index=0; index<values.length; index++)
{
for(index2 = index+1; index2< values.length; index2++)
{
if(values[index] > values[index2])
{
temp = values[index];
values[index]= values[index2];
values[index2] = temp;
}
}
}
for(int n=0; n < values.length; n++ )
{
System.out.print(values[n] + " ");
}
}
}
int[] arrayToSort=new int[]{1,7,81,2,-2,9,9,6,-6};
//the outer loop will switch the number
for(int i=0;i<arrayToSort.length;i++){
int indexSmal=i;
//the inner loop will search for the biggest number
for(int j=i+1;j<arrayToSort.length;j++){
//search for biggest number index starting from i index
if(arrayToSort[j]>arrayToSort[indexSmal]){
indexSmal=j;
}
}//end loop
//swap the number
int smallNum=arrayToSort[indexSmal];
arrayToSort[indexSmal]=arrayToSort[i];
arrayToSort[i]=smallNum;
}// end loop
for(int i=0;i<arrayToSort.length;i++){
System.out.print(arrayToSort[i]+", ");
}

Why doesn't my program return the correct number?

import java.util.Scanner;
public class AnalyzingScores
{
public static void main(String[] args)
{
int count = 0;
double scoreTotal = 0;
int index;
int tests;
double scoreAverage;
double highest;
double lowest;
//Creates a new Scanner.
Scanner keyboard = new Scanner(System.in);
//Asks the user to enter how many tests they have taken.
System.out.println("Enter the amount of tests you have taken: ");
tests = keyboard.nextInt();
//Creates an array.
int[] score = new int[tests];
//Creates a for loop that asks a user to enter their test scores.
for (index = 0; index < tests; index++)
{
System.out.println("Enter your test score: ");
score[index] = keyboard.nextInt();
scoreTotal += score[index];
}
scoreAverage = scoreTotal / score.length;
System.out.println("You entered " + tests + " scores.");
System.out.println("The test average is " + scoreAverage);
System.out.println("Number of scores above or equal to the average is " + getHighest(score));
System.out.println("Number of scores below the average is " + getLowest(score));
}
private static int scoreAverage;
public static int getHighest(int[] score)
{
int aboveAverage = 0;
for (int index = 1; index < score.length; index++)
{
if (score[index] >= scoreAverage)
{
aboveAverage++;
}
}
return aboveAverage;
}
public static int getLowest(int[] score)
{
int belowAverage = 0;
for (int index = 1; index < score.length; index++)
{
if (score[index] < scoreAverage)
{
belowAverage++;
}
}
return belowAverage;
}
}
Hi everyone! Right now I have an issue with my code and I can't figure out why. The code is supposed to send back the number of scores that are above or equal to the average and those that are below the average.
Sometimes, though, the code doesn't return the correct number. For example, if I type in 3 test scores that are 100, 90, and 80, the average is 90. It should show that 2 are above/equal to 90 and 1 that is below 90. The problem is, it shows that 0 are below 90. I've tested it out several times and it only seems to happen to belowAverage. Thanks in advance!
Others have answered that the problem is with the indexing in your for loops which should be 0-based, and that is certainly a bug in your code. However, that is not the problem.
Within functions getHighest() and getLowest(), the variable scoreAverage refers to the uninitialised class level variable declared just prior to the definition of the functions, viz:
private static int scoreAverage;
not to the scoreAverage declared within function main(). The class level variable defaults to 0, and that is why you see no values less than the average.
You can fix your code by removing the declaration of scoreAverage in main() and modifying the class level declaration to:
private static double scoreAverage;
It needs to be a double, not an int, as division returns a floating point type, not an integer.
Alternatively you could use a variable of type double declared within main() for the score average, and pass that to the two functions, rather than accessing the class level variable, and this is probably preferable.
for (int index = 1; index < score.length; index++)
Arrays in Java (and most programming languages) use 0-based numbering. Your loops should start from int index = 0, not int index = 1.
Indexing of your array should start from 0, not 1, in your getHighest(int[] score) and getLowest(int[] score) methods. This way you are missing out on your first values entered.
You are not checking the element in the 0th index in your getHeighest() and getLowest(). Hence you get one less of the value that you expected in either aboveAverage or belowAverage.
Delete the line
private static int scoreAverage;
and pass scoreAverage to both the functions.
Code:
public static int getHighest(int[] score, double scoreAverage)
{
int aboveAverage = 0;
//Index should start from 0 to avoid skipping the first element of the array.
for (int index = 0; index < score.length; index++)
{
if (score[index] >= scoreAverage)
{
aboveAverage++;
}
}
return aboveAverage;
}
public static int getLowest(int[] score, double scoreAverage)
{
int belowAverage = 0;
//Here also, index should start from 0.
for (int index = 0; index < score.length; index++)
{
if (score[index] < scoreAverage)
{
belowAverage++;
}
}
return belowAverage;
}
}
As the others have mentioned, your for-loops should start at index 0:
for (int index = 0; index < scrore.length; index++)
But there's also another problem with your code in that you declare two variables named scoreAverage: one in the main method: double scoreAverage;
and another time a little below the main method as a static field:
private static int scoreAverage;
So there's only one change that you need to do:
private static double scoreAverage;
public static void main(String[] args)
{
int count = 0;
double scoreTotal = 0;
int index;
int tests;
//double scoreAverage; <--- remove that
double highest;
double lowest; ...
And your code should work.
The methods that you are calling: getHighest() and getLowest() don't have the correct scoreAverage variable. In the code of that methods the scoreAverage variable equals 0. So you can do this:
public static int getHighest(int[] score, double scoreAverage)
{
int aboveAverage = 0;
for (int index = 0; index < score.length; index++)
{
if (score[index] >= scoreAverage)
{
aboveAverage++;
}
}
return aboveAverage;
}
public static int getLowest(int[] score, double scoreAverage)
{
int belowAverage = 0;
for (int index = 0; index < score.length; index++)
{
if (score[index] < scoreAverage)
{
belowAverage++;
}
}
return belowAverage;
}

Categories