Struggling with passing array values into methods - java

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.

Related

Writing a method in java using an array and objects

I'm new to Java and I'm stuck on this problem:
"Create a second add() method which has a single parameter of an array of doubles and, inside the method, adds the values of the array, returning the result as a double. Sample test data:
double[] dblArr = {11.82,88.23,33};
I have a separate class file with the following so far:
public double add(double[] values) {
int sum = 0;
for (double i : values)
sum += i;
return sum;
}
This is the method to add the array's and return the total sum.
And this is the code I have in my "main" document to call the method
double dblArr;
utils.print("Please enter an array of 5 numbers: ");
dblArr = input.nextDouble();
double sum = calc.add(dblArr);
System.out.println(dblArr);
I know I'm quite off scope so some advice would be really appreciated, thank you
"calc" is what I'm using to call the other document
Calculate calc = new Calculate();
You are most of the way there, you just need to use a double array to gather the inputs, and you need to use a loop to save all the inpets to the array:
//use an array instead of a single double
double[] dblArr = new double[5];
int inputs = 0;
//Use a loop to gather 5 inputs
while(inputs < 5){
utils.print("Please enter the next of 5 numbers: ");
dblArr[inputs] = input.nextDouble();
inputs++;
}
//We have changed the add method to static, so you can just use `add(dblArr)` instead of making an instance of the class with the add method
double sum = add(dblArr);
//Finally print out the sum result not the dblArr array
System.out.println("The total is " + sum);
Then just change the method to static so that you can call it directly:
//Add static to this line as shown, because we don't need an instance of this method
public static double add(double[] values) {
int sum = 0;
for (double i : values)
sum += i;
return sum;
}

Java: How do I get a variable from the second method to work in the third method?

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);

Displaying Average Integer in Array using Driver Program

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.

How to pass a array to a constructor and use it in a class?

This is my main method, i am trying to get back into coding, for i failed at it repeatedly in school. I want to take an array from my main method with user input from a loop, and pass it to a constructor in my "TestScoresTwo.java" class. I want to then take that array and use it to sum the values and find the average in a method in the class, and then return the sum.
import java.math.*;
import java.text.DecimalFormat;
import java.io.*;
public class labBookFortyTwo
{
public static void main(String[] args)
{
Scanner myInput = new Scanner(System.in);
System.out.println("Please enter the amount of grades there are ");
int size = myInput.nextInt();
double grade = 0;
double[] myArray = new double[size];
for(int count = 0; count < myArray.length; count++)
{
System.out.println("enter grade ");
grade = myInput.nextDouble();
myArray[count] = grade;
System.out.println("grade is " + myArray[count] );
}
TestScoresTwo myScore = new TestScoresTwo(myArray, size);
double avg = myScore.avgGrade();
System.out.println("avg is" + avg);
}
}
This is my TestScoresTwo.java Class.
public class TestScoresTwo
{
int size = 0;
double[] tScore = new double[size];
double sum = 0;
public TestScoresTwo(double[] scores ,int sizE)
{
double[] tScore = scores;
size = sizE;
}
public double avgGrade()
{
for(int count = 0; count < tScore.length ; count++)
{
sum = tScore[count] + sum;
}
double avg = sum / size;
return avg;
}
}
When it compiles my output is:
"Please enter the amount of grades there are"
3
"enter grade"
11
"grade is 11.0"
50
"grade is 50.0"
70
"grade is 70.0"
"avg" is 0.0"
"Press any key to continue..."
So for some reason in my class TestScoresTwo.java, the for loop inst being entered, and im not sure why. They are two separate files , and i cant think of any other information to include. Thank you for any help you can give.
Your proble; is in TestScoresTwo class:
public TestScoresTwo(double[] scores ,int sizE)
{
double[] tScore = scores;
size = sizE;
}
tScore is local to the constructor. So you're assigning the passed variable to a local variable, which is lost once the end of the constructor is reached.
So when you call avgGrade() to calculate the average, the array it,s calculating the average from is empty.
Replace it by:
public class TestScoresTwo
{
int size = 0;
double[] tScore; // no need to create it here, it's already created and filled in outside
double sum = 0;
public TestScoresTwo(double[] scores ,int sizE)
{
this.tScore = scores; // "this." added for clarity
this.size = sizE; // "this." added for clarity
}
You declared your array double[] tScore = new double[size]; to be of zero size. You intended to replace it with a new array in your constructor here:
double[] tScore = scores;
However, all you did is declare a local variable of the same name, and assign the parameter to it, which immediately goes out of scope at the end of the constructor. The for loop appears not to be entered, because tScore is still empty and of zero length.
Remove double[] so that tScore resolves to your instance variable and get assigned properly.
tScore = scores;
Also, it's confusing to see a parameter named sizE and an instance variable named size. It's common to use this to refer to the instance variable, so that they can be named the same name and yet be clear. Try naming the parameter size also, and use this line in your constructor:
this.size = size;

Manipulate individual numbers inside of an array in Java

Working on some homework and I want to make my code more precise, I have a set of values inside of an array that I need to convert into a different set of numbers while still being inside the array. Since this is for my homework I don't want to actually post what I am working on, so I will post an example, wouldn't want anyone doing my work for me!
public class Example{
public Example(){
double rainfall [] = {1.07, 3.25, 4.51, 2.32, 8.28}; //in Inches
System.out.print("Enter i for Inches or c for Centimeters ");
String scale = in.next();
if(scale.equalsIgnoreCase("C")){
for (double i : rainfall){
rainSum += i;
}//End for
// Here is where I am lost on what to do in my current program I have it
// to where it adds up all the numbers as inches and then converts them into
// centimeters, however I need to display every number in centimeters, so I
// cannot do it that way.
}//End if
}
}
So I suppose you have stats of rainfall of 5 days. They are provided in Inches and you need to output 2 things(Based on if the user selects 'C') :
(1). Total rainfall in cms.
(2). Daily rainfall stats in cms.
(3). You need to do this while preserving the original array in Inches.
So I would suggest you following code :
(1).
You are pretty correct on thinking in doing this. Add all the elements and multiply them by 2.54
to get its equivalent in cms.
(2).
call a method display as following :
void display(double[] a) // This would print individual rainfall stats in cms.
{
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]*2.54);//Modify formatting as per your requirements
}
}
(3).
These remain as is.
Method-2 :
If the expectancy of program getting input as 'C' is more, then create another array
that actually converts the initial inches array to cms array.
So, now you have two arrays :
rainfallInches[] & rainfallCms[]
You can use them as follows :
for(int i=0;i<rainfallInches.length;i++)
{
rainfallCms[i] = rainfallInches[i]*2.54;
}// This creates new cms array
Hope this helps
If you need to preserve the original values you will need to create a new array and copy the converted values to the corresponding positions in the new array.
If you don't need to preserve the original values use array element assignment, for instance:
private static final double CENTIMETERS_PER_INCH = 2.54d;
...
a[1] = a[i] * CENTIMETERS_PER_INCH;
in a loop to calculate the converted values. The constant definition would appear at the class level, not in the loop.
You're adding up all of the numbers and converting that sum (inches) into centimeters by multiplying by 2.54. The values in your array are still in inches, so to print all of them out in centimeters, simply iterate through the array and print the value multiplied by 2.54. Alternatively, if you need the transformed values and the original, simply copy the array, but multiplying each entry by 2.54.
public class Example{
public interface Constants{
/**
* Centimer to inch
*/
static final double CENTIMETER_TO_INCH = 0.393701;
/**
* Centimer to inch
*/
static final double INCH_TO_CENTIMETER = 2.54;
}
public double[] convertToCentimeter(double[] rainfallInInches){
int length = rainfallInInches.length;
double[] rainfallInCentimeters = new double[length];
for( int i = 0; i < length; i++ ){
rainfallInCentimeters[i] = rainfallInInches[i] * Constants.INCH_TO_CENTIMETER;
}
return rainfallInCentimeters;
}
public double[] convertToInches(double[] rainfallInCentimeter){
int length = rainfallInCentimeter.length;
double[] rainfallInInches = new double[length];
for( int i = 0; i < length; i++ ){
rainfallInInches[i] = rainfallInCentimeter[i] * Constants.CENTIMETER_TO_INCH;
}
return rainfallInInches;
}
public static void main(String[] args){
double rainfall [] = {1.07, 3.25, 4.51, 2.32, 8.28}; //in Inches
// Test convert to centimeter
Example example = new Example();
double[] convertedArray = example.convertToCentimeter(rainfall);
System.out.print("{");
for(int i = 0; i < convertedArray.length; i++){
System.out.print(convertedArray[i] + ", ");
}
System.out.println("}");
} // end main
}

Categories

Resources