I need practice with my syntax. I have an array of numbers and with that are methods to find the average, report highest number, and report the lowest number. To report the highest/lowest numbers I will be sorting the array.
But first my problem is with reporting the average. I think that if I can understand that part, then the min/max will be no problem. I have tried changing it to say Driver.randomArray[].getAverage() as well.
Are there any suggestions? Thanks in advance.
~Crystal
error code:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
randomArray cannot be resolved to a type
Class cannot be resolved to a type
Syntax error, insert ". class" to complete Expression
at IntegerArray.main(IntegerArray.java:48)
and it refers to my attempt to call the average from this line,
System.out.println(randomArray[].getAverage());
First, Driver Class
import java.util.Arrays;
public class Driver {
private static final int MAX = 0;
public Driver(){
int[] randomArray = new int [MAX];
int sum;
final int MAX;
}
public int getAverage(){
for (int index = 0; index < MAX; index++){
int sum = 0;
int[] randomArray = null;
int average;
sum = sum + randomArray[index];
average = sum/MAX;
return average;}
}
public void sortArray(){
// sort the array from smallest to biggest
int[] randomArray;
Arrays.sort(randomArray);
System.out.println("The sorted array from smallest to biggest is:");
for (int number : randomArray) {
System.out.println( + number)}
}
public int getMin(){
int[] randomArray;
// find the lowest number
return randomArray[0];
}
public int getMax(){
int[] randomArray;
// find the highest number
return randomArray[MAX];
}
}
Then my main class:
import java.util.Random;
import java.lang.reflect.Array;
import java.util.Arrays;
public class IntegerArray {
public static void main (String[] args) {
// set up the constant for the size of the array
final int MAX = 10;
int sum = 0;
int average = 0;
int[] randomArray = new int [MAX];
for (int index = 0; index < MAX; index++)
// values of the array go from 0-10
randomArray[index] = (int) (Math.random() *10);
// prints the array
for (int value : randomArray)
System.out.println (value);
System.out.println("The length of the array is: " + randomArray.length);
System.out.println(randomArray[].getAverage());
}
}
The way you're creating your methods eg. getAverage() you can't call it on the array you created. On the other hand you can call them on the a Driver object you create. for example: Driver driver = new Driver(); System.out.println(driver.getAverage()); If you want to call them on the Array Object you should add them on the Array class (but that is something more advanced Java than this).
In Java Code you need to add a ; after a statement don't forget them ;). Your IDE should warn you about them.
When you create your getMax() method you should add the array as a parameter. So that the method knows for what Array object it should get the highest number. For example:
public int getMax(int[] randomArray) {
// find the highest number
return randomArray[MAX];
}
This counts for all your methods.
I hope this solves some of your answers if not please add a comment or something.
So here is your code after that:
Driver class:
import java.util.Arrays;
public class Driver {
private static final int MAX = 0;
public Driver() {
int[] randomArray = new int[MAX];
int sum;
final int MAX;
}
public int getAverage() {
int average = 0;
for (int index = 0; index < MAX; index++) {
int sum = 0;
int[] randomArray = null;
sum = sum + randomArray[index];
average = sum / MAX;
}
return average;
}
public void sortArray(int[] randomArray) {
// sort the array from smallest to biggest
Arrays.sort(randomArray);
System.out.println("The sorted array from smallest to biggest is:");
for (int number : randomArray) {
System.out.println(+number);
}
}
public int getMin(int[] randomArray) {
// find the lowest number
return randomArray[0];
}
public int getMax(int[] randomArray) {
// find the highest number
return randomArray[MAX];
}
}
IntegerArray class:
public class IntegerArray {
public static void main(String[] args) {
// set up the constant for the size of the array
final int MAX = 10;
int sum = 0;
int average = 0;
int[] randomArray = new int[MAX];
for (int index = 0; index < MAX; index++)
// values of the array go from 0-10
randomArray[index] = (int) (Math.random() * 10);
// prints the array
for (int value : randomArray)
System.out.println(value);
System.out.println("The length of the array is: " + randomArray.length);
Driver driver = new Driver();
System.out.println(driver.getAverage());
}
}
Reply to the question in the comments:
You should give the randomArray as the parameter with your getAverage method so that method knows on which array it should operate, example: driver.getAverage(randomArray);
Your getAverage method also has some flaws:
1. Your sum variable should be outside the loop because else you would set your sum to 0 every time you iterate inside the loop.
2. int[] randomArray = null; You shouldn't really do this line at all, this line will create a NEW int array and set its value to null while you should you use the int array you give as a parameter.
So your getAverage method becomes:
public int getAverage(int[] randomArray) {
int sum = 0;
for (int index = 0; index < randomArray.length; index++) {
sum = sum + randomArray[index];
}
int average = sum / randomArray.length;
return average;
}
Currently your main class doesn't reference Driver at all, so your code cannot be called.
System.out.println(randomArray[].getAverage());
On this line randomArray is still just an array of integers (int[] randomArray = ...).
You will need to create an instance of Driver, pass in whatever array you're wanting to use, and then do .getAverage() on that.
randomArray is null and you are trying to read from a null array.
you need to define randomArray as a class member, not a local variable in all functions.
Local variables inside functions cannot be used as soon as function ends, and using the same name in other functions cannot help that.
Also:
define sum and average before loop. calculate and return average after loop.
Among other things your main issue seems to be a fundamental misunderstanding of scope rules. For example:
void method () {
int someVariable;
}
void method2 () {
someVariable = 2; // <-- Error.
}
In that code someVariable is local to method and is not available outside of it. You could not access it in method2.
I suggest you have a read not only of the above scope rules link, but of the official tutorial on member variables as well, which also describes scope. The information there will help you come up with a final strategy.
In your specific case your two most reasonable options are:
You could make randomArray a member field of your class (see above links).
You could pass randomArray as a parameter to your various methods (e.g. as a parameter to getAverage, see also the official tutorial on passing information to a method).
You have a few other issues, some mentioned in the other answers here, but my take is that is your primary confusion here. Read through the official tutorials (the docs.oracle.com links above), they're concise and well-written, and will fill in the blanks of some of your missing concepts. After you do that, give it another shot.
By the way, as for your compiler error on:
System.out.println(randomArray[].getAverage());
Unfortunately randomArray[].getAverage() simply does not make enough sense to justify a full explanation of how the compiler is interpreting it, so suffice it to say: No, that's wrong. :)
You'll want to check out that "passing information to a method" tutorial mentioned above, because it looks like you're trying to express something like this (option 2 above):
int getAverage (int randomArray[]) {
...
}
System.out.println(getAverage(randomArray));
As an aside: Note that the average of a bunch of integers isn't necessarily an integer itself (the average of 1 and 2 is 1.5). You might consider computing and returning a float or a double instead.
Related
HOMEWORK BACKGROUND
I'm writing a java program for my class in which:
An array of 10 random numbers between 1 and 100 are generated
The application will pass the array to a calculated average method and then return the calculated average method to the main method
The array and the average value in the array will be passed to a count below method in which all numbers less than the average will be counted and the number of integers that are < average will be returned and displayed in the main method.
This is my beginner java class, so I'm not the best with java yet. I've been programming for about a month and a half.
TL;DR: My problem is I can't get the average variable in the second method to work in the third method in order to do the computation.
In the third method, I've tried calling the other method like:
calcAverage(int [] array))
and
public static double countBelow (int[] array, calcAverage(array))
EDITED:
// main method
public static void main (String[] args)
{
final int ARRAY_LENGTH = 10;
//array object is created
int array[] = new int [ARRAY_LENGTH];
//for loop that loops through the array
for (int rand = 0; rand < array.length; rand++)
{
// random number generator from 1-100
array[rand] = (int)(Math.random()*100);
}//end of loop
//for loop that loops through the array
for (int rand = 0; rand < array.length; rand++)
{
// prints random numbers to the screen
System.out.printf("Numbers: %d \n", array[rand]);
} //end of for loop
//passing the array to the second method
calcAverage(array);
//prints out average
System.out.print("Average is:");
System.out.println (calcAverage(array));
//passing array to the third method
countBelow(calcAverage(array));
} // end of main method
//declaring second method for calculating average
public static double calcAverage(int[] array)
{
//declaring variables for the sum and average
double sum = 0;
double average = 0;
//for loop that loops through the array
for (int rand = 0; rand < array.length; rand++)
{
//computes the sum of the random numbers from first method
sum += array[rand];
}
//computes average
average = (sum / array.length);
//returns average to main method
return average;
} //end of second method
//start of third method
public static int countBelow (int[] array, double average)
{
int scoresBelow = 0;
//for loop that loops through the array
for (int rand = 0; rand < array.length; rand++)
{
if (array[rand] < average)
{
scoresBelow ++;
}
else {}
}
return scoresBelow;
}
}//end of class ArrayTest
I get the error message:
error: method countBelow in class ArrayTest cannot be applied to given types;
countBelow(calcAverage(array));
^
required: int[],double
found: double
reason: actual and formal argument lists differ in length
1 error
Your countBelow method seems to have two parameter:
int[] array and the result of calcAverage(array),
so the signature should be:
public static int countBelow(int[] array, double average) {
// ...
}
I assume you want to pass the result of calcAverage(array) to this method.
public static void main(String[] args) {
int[] array = ...
int count = countBelow(array, calcAverage(array));
}
Edit:
As others mentioned, your countBelow method should return a natural number.
Edit2:
error: method countBelow in class ArrayTest cannot be applied to given types; countBelow(calcAverage(array)); ^ required: int[],double found: double reason: actual and formal argument lists differ in length 1 error
Seems like you mismatched the number of parameters now. If you define 2 (array & average), you need to call it with 2.
//passing array to the third method
countBelow(array, calcAverage(array));
Note that the array needs to be passed to each method individually. Passing the array to calcAverage does not pass it automatically to the countBelow method.
You either needs to compute the average in the main method, and pass it to countBelow, or compute it in countBelow:
First version — Compute before and pass to countBelow
// You pass the average already computed as a double argument:
public static double countBelow (int[] array, double average) {
// Do what you must do...
}
// In the main method:
final int[] array = ...;
final double average = calcAverage(array);
countBelow(array, average);
Second version — Compute the average directly in countBelow
// You only pass the array:
public static double countBelow(int[] array) {
// You compute the average here:
final double average = calcAverage(array);
// Do what you must do...
}
// In the main method:
final int[] array = ...;
countBelow(array);
So this is a coding question from school I have, I don't want to say "hey guys do my homework for me!", I actually want to understand what's going on here. We just started on arrays and they kind of confuse me so I'm looking for some help.
Here's the complete question:
Write a program in which the main method creates an array with
10 slots of type int. Assign to each slot a randomly-generated
integer. Call a function, passing it the array. The called
function should RETURN the largest integer in the array to
your main method. Your main method should display the number
returned. Use a Random object to generate integers. Create it
with
Random r = new Random(7);
Generate a random integer with
x = r.nextInt();
So, here's what I have so far:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
int x = r.nextInt();
for (int i = 0; i < count.length; i++)
{
count[i] = x;
}
}
I created that array with 10 ints, then used a for loop to assign each slot that randomly generated integer.
I'm having a hard time for what to do next, though. I'm not sure what kind of method / function to create and then how to go from there to get the largest int and return it.
Any help is really appreciated because I really want to understand what's going on here. Thank you!
Here is how to generate Random ints
public static void main(String[] args) {
int []count = new int[10];
Random r = new Random(7);
int x=0;
for (int i = 0; i < count.length; i++)
{
x = r.nextInt();
count[i] = x;
}
System.out.println("Max Number :"+maxNumber(count));}//Getting Max Number
Here is how to make method and get max number from list.
static int maxNumber(int[] mArray){//Passing int array as parameter
int max=mArray[0];
for(int i=0;i<mArray.length;i++){
if(max<mArray[i]){//Calculating max Number
max=mArray[i];
}
}
return max;//Return Max Number.
}
Ask if anything is not clear.
This is how we make method which return int.
You can do it by using a simple for loop for the Array.
First you have to create a seperate int variable (eg: int a) and assign value zero (0) and at each of the iterations of your loop you have to compare the array item with the variable a. Just like this
a < count[i]
and if it's true you have to assign the count[i] value to the variable a . And this loop will continue until the Array's last index and you will have your largest number in the a variabe. so simply SYSOUT the a variable
Important: I didn't post the code here because I want you to understand the concept because If you understand it then you can solve any of these problems in future by your self .
Hope this helps
What you have got so far is almost correct, but you currently are using the same random number in each iteration of your for-loop. Even though you need to get a new random number for each iteration of your for-loop. This is due to how the Random object is defined. You can achieve this by changing your code the following way:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
for (int i = 0; i < count.length; i++)
{
int x = r.nextInt(); // You need to generate a new random variable each time
count[i] = x;
}
}
Note that this code is not optimal but it is the smallest change from the code you already have.
To get the largest number from the array, you will need to write another for-loop and then compare each value in the array to the largest value so far. You could do this the following way:
int largest = 0; // Assuming all values in the array are positive.
for (int i = 0; i < count.length; i++)
{
if(largest < count[i]) { // Compare whether the current value is larger than the largest value so far
largest = count[i]; // The current value is larger than any value we have seen so far,
// we therefore set our largest variable to the largest value in the array (that we currently know of)
}
}
Of course this is also not optimal and both things could be done in the same for-loop. But this should be easier to understand.
Your code should be something like this. read the comments to understand it
public class Assignment {
public static int findMax(int[] arr) { // Defiine a function to find the largest integer in the array
int max = arr[0]; // Assume first element is the largest element in the array
for (int counter = 1; counter < arr.length; counter++) // Iterate through the array
{
if (arr[counter] > max) // if element is larger than my previous found max
{
max = arr[counter]; // then save the element as max
}
}
return max; // return the maximum value at the end of the array
}
public static void main(String[] args) {
int numberofslots =10;
int[] myIntArray = new int[numberofslots]; // creates an array with 10 slots of type int
Random r = new Random(7);
for (int i = 0; i < myIntArray.length; i++) // Iterate through the array 10 times
{
int x = r.nextInt();
myIntArray[i] = x; // Generate random number and add it as the i th element of the array.
}
int result = findMax(myIntArray); // calling the function for finding the largest value
System.out.println(result); // display the largest value
}
}
Hope you could understand the code by reading comments..
This can be done in one simple for loop no need to have 2 loops
public static void main(String[] args) {
Integer[] randomArray = new Integer[10];
randomArray[0] = (int)(Math.random()*100);
int largestNum = randomArray[0];
for(int i=1; i<10 ;i++){
randomArray[i] = (int)(Math.random()*100);
if(randomArray[i]>largestNum){
largestNum = randomArray[i];
}
}
System.out.println(Arrays.asList(randomArray));
System.out.println("Largest Number :: "+largestNum);
}
Initialize max value as array's first value. Then iterate array using a for loop and check array current value with max value.
OR you can sort the array and return. Good luck!
Here's a basic method that does the same task you wish to accomplish. Left it out of the main method so there was still some challenge left :)
public int largestValue(){
int largestNum;
int[] nums = new int[10];
for (int n = 0; n < nums.length; n++){
int x = (int) (Math.random() * 7);
nums[n] = x;
largestNum = nums[0];
if (largestNum < nums[n]){
largestNum = nums[n];
}
}
return largestNum;
}
I am trying to find the minimum value in an array by way of creating a new Java class. I am having trouble passing in the array and using it to find the minimum value of an array.
I have a total of two separate arrays that I am trying to find the value of.
Here is the first class I created:
import java.util.*;
public class mooseWeight
{
public int main(String[] args)
{
int[] length1;
int[] length2;
length1 = new int[20];
length2 = new int[50];
//Length 1
System.out.println("Array 1:");
Random rnd = new Random();
for(int i = 0; i<length1.length; i++)
{
length1[i] = rnd.nextInt(400) + 250;
System.out.println(length1[i]);
return length1[i];
}
System.out.println("-----------------------------------");
//Length2
System.out.println("Array 2:");
Random rnd2 = new Random();
for(int j = 0; j < length2.length; j++)
{
length2[j] = rnd2.nextInt(400) + 250;
System.out.println(length2[j]);
return length2[j];
}
}
}
This is currently set up to find the minimum value of length1[] (aka the first array).
This is the class I am trying to pass the arrays into:
public class minWeight
{
public static int getArrayMin(int[] arr)
{
mooseWeight array1[] = new mooseWeight[];
int minValue = array1[0];
for (int i = 0; i < array1.length; i++)
{
if (array1[i] < minValue)
{
minValue = array1[i];
}
//return minValue;
}
return minValue;
System.out.println(minValue);
}
}
My current error:
1 error found:
File: D:\2016-2017\Fall2016\201_CSCE_Programming\Lab 7\minWeight.java [line: 5]
Error: array dimension missing
The error in minWeight not fom the array parameter, it is from this line:
mooseWeight array1[] = new mooseWeight[];
You cannot allocate an array of unknown dimension in java.
Also, your attempt to do so makes no sense.
Just delete the line above from your java method and change the name of the parameter to array1.
Get an IDE like netbeans or eclipse.
Your mooseWeight class contains your main, so when you're creating array1, you're trying to create an array containing your actual program.
mooseWeight array1[] = new mooseWeight[]; is creating an array of mooseWeight objects.
As you don't define a size, this will fail, but even if it didn't, it wouldn't work.
I assume that you meant to create an array of int, then loop over it.
If you created an array of int, then tried to loop over it without adding anything, the loop won't do anything as there's nothing to iterate over.
In your method, you pass in an array of int called arr, so you need to use that to loop over.
If you're trying to pass 2 arrays into the method, creating an array as part of your method still won't work.
You need to modify your method declaration to accept a second array.
Assuming you want to find the smallest value from both of these arrays, I've modified my code snippet to do just that.
If you need to process your second array differently, modify the loop which deals with secondArr.
As mentioned in comments, your mooseWeight class should be named MooseWeight to keep with correct Java naming conventions.
A class name is in PascalCase, with instances in camelCase.
To call the method, use the following snippet.
int[] ar1 = new int[20];
int[] ar2 = new int[50];
//Populate your arrays with values....
int minValue = MinWeight.getArrayMin(ar1, ar2);
Class:
public class MinWeight {
public static int getArrayMin(int[] arr, int[] secondArr) {
int minValue = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] < minValue)
{
minValue = arr[i];
}
}
for (int i = 0; i < secondArr.length; i++) {
if (secondArr[i] < minValue)
{
minValue = secondArr[i];
}
}
System.out.println(minValue);
return minValue;
}
}
As a final concern, in your code, you return minValue before you try to print the result, so the print instruction is always unreachable.
I am having difficulty in making the logic for my scenario which i m considering an array of arrays more specifically said as 2D array.i want to find the maximum value in 2D arrays i do not want to call it in main method.i am making the array as annonymous and calling the function of max from it via static data members.the code is as follows.do let me know the logic to find the greatest no in 2D array as i m finding it difficult to which value to compare with the array.the code is as follows:-
class Max2DArray
{
static int i;
static int j;
static int large;//largest number
int max(int x[][])
{
for(int i=0;i<x.length;i++)
{
for(j=0;j<x[i].length;i++)
{
if(x[i][j]<=???)//what should be the comparison here.
{
??//what should be done here??
}
}
}
return large
}
public static void main(String... s)
{
Max2DArray m1 = new Max2DArray();
int t = m1.max(new int[][]{{20,10,5},
{5,7,6},
{23,31,16}});
System.out.println("the largest number is = "+t);
}
}
I am not going to solve it to you but here is an algorithm
Have a local variable max
assign max to the first value of the array
iterate through the array and change the value of max whenever you find a value greater that the current value of max.
return max
Try this:
int max(int x[][]){
// Initialize the value to the lowest value
int large = Integer.MIN_VALUE;
for(int i = 0; i < x.length; i++) {
for(j = 0; j < x[i].length; j++) {
// Check if the current value is greater than large
if(x[i][j] > large) {
// It is greater so we keep the new value
large = x[i][j];
}
}
}
return large;
}
Using java 8, it could simply be:
int max(int x[][]){
return Arrays.stream(x).flatMapToInt(IntStream::of).max().getAsInt();
}
A Java 8 one-liner, instead of your for loop:
Arrays.stream(x).flatMapToInt(arr2 -> Arrays.stream(arr2)).max().getAsInt();
i'm struggling a bit with getting array values from one method into another without repeating the method over again (the method obtains judges scores using getScannerInput (we have to use it at my uni instead of other options :-/ ).
My program is the following;
public class mark4
{
static int SIZE = 10; // Define array size
static int classMarks[] = new int [SIZE]; // Initialise array classMarks[]
static double max = 0;
static double min = 0;
static double total = 0;
static double averagescore = 0;
static int pass = 0;
public static int[] getMarks()
{
int[] classMarks = new int [SIZE];
for(int i = 0; i< classMarks.length; i++) // Start input loop to obtain marks
{
classMarks[i] = getScannerInput.anInt("Please enter students mark: ");
}
System.out.print("\nThe marks for this class are; "); // Output initial line to be completed with students marks
for(int i=0; i<classMarks.length; i++) // Start output loop to output students marks
{
System.out.print(classMarks[i] + ", "); // Output marks separated by a comma and a space
}
return classMarks;
}
public static double averagescore(){
for(int i=0; i<classMarks.length; i++) // Start loop to calculate total of all marks.
{
total = classMarks[i] + total; // Calculate total of array by traversing and adding to 'total' variable each time
averagescore = total / classMarks.length; // Divide array total by array length to find average
} // end average loop
return averagescore;
}
public static double min(){
min = classMarks[0]; // Set min to first value of array to compare to rest
for(int i=0; i<classMarks.length; i++) // Start loop to calculate minimum and maximum scores
{
if(classMarks[i] < min) // Compare values on each iteration, if value is less than current 'min' value, replace min with new value
min = classMarks[i];
} // end minloop
return min;
}
public static double max(){
max = classMarks[0]; // Set max to first value of array to compare to rest
for(int i=0; i<classMarks.length; i++) // Start loop to calculate minimum and maximum scores
{
if(classMarks[i]>max) // Compare values on each iteration, if value is greater than current 'max' value, repalce max with new value
max = classMarks[i];
} // end max loop
return max;
}
public static int pass(){
for(int i=0; i<classMarks.length; i++) // Start loop to calculate how many students passed with a mark of 8 or higher
{
if( classMarks[i] >= 8 ) // Compare the current score in each iteration to 8 to see if it is more than or equal to the pass mark
pass++; // If current value is greater than or equal to pass mark, add one to pass counter.
} // end pass loop
return pass;
}
public static void main (String args[])
{
int[] classMarks = getMarks();
double averagescore = averagescore();
double min = min();
double max = max();
int pass = pass();
System.out.print("\nThe number of students who passed the exam is " + pass);
System.out.printf("\nThe class average correct to 1 decimal place is: %4.1f", averagescore); // Output average score to 1 decimal place
System.out.printf("\nThe lowest mark obtained in this class was: %3.1f", min); // Output lowest score to one decimal place (in case of half marks...)
System.out.printf("\nThe highest mark obtained in this class was: %3.1f", max); // Output highest score to one decimal place (in case of half marks...)
} // end main
} // end class
The program compiles correctly, but the results I get are all 0 or 0.0, suggesting that the methods aren't taking the figures input during the getScores() method.
If I try to define the results for classMarks[] inside the methods using;
int[] classMarks = getMarks();
it repeats the whole getScores() method and asks for the results again every time it encounters a method in the main.
I'm aware this is probably a fairly simple answer, but we had to do this as a question in an assessment, but i missed the lectures on methods and arrays and i'm struggling a bit with some minor elements.
Any help would be much appreciated!
You declare this, which I beleive is what you intend to use,
static int classMarks[] = new int [SIZE];
but, within getMarks(), you declare a new one:
int[] classMarks = new int [SIZE];
which is what will be used within the scope of that method.
Either, you should use the class scope variable, and not declare others which will override it (that is, remove the second declaration shown above), or your min, max, etc. methods should take the an int[] argument, and you could pass the array returned from getMarks() to them.
In your main method you are declaring classMarks, which is hiding the static classMarks you have at the class level. You are also declaring another classMarks array within your getMarks method, so your scanner is never reading into the shared classMarks array, only into the local array in getMarks, which is then returned and placed in the local classMarks variable in main, but never getting into your static variable that is referenced by every other method in the class.