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;
}
Related
I want to loop through my array list roster and for each Student item I want to return the average of an array of grades. I know there are 3 grades so this code works, but how can I implement this if I don't know how many grades are in the Student's grades array before hand?
public static void printAverageGrades(){
System.out.println("Print Average Grades");
for(Student item : roster)
{
double div = roster.size();
**double average = (item.getGrades()[0] + item.getGrades()[1] + item.getGrades()[2]) / div;**
System.out.printf("%.2f \n", average);
}
}
You can do this two ways. The more preferable Java 8 way is listed first.
Use Arrays.stream to encapsulate the array as a stream, then getting the average is just a couple of method calls away.
double avg = Arrays.stream(item.getGrades()).average().getAsDouble();
Use another for loop and keep a running total of the elements. Don't forget to manually coerce your numerator to a double or you'll run into integer division.
int sum = 0;
for(int i : item.getGrades()) {
sum += i;
}
double avg = (sum * 1.0) / item.getGrades().length;
In practice, never hard-code your index locations. You can always get the length of an array using .length.
You can just use this function, in which would iterate through the array, by dynamically iterating through for loop, we compute sum.
Then average would be divided by the length of array.
double getAverage(double[] data)
{
double sum = 0.0;
for(double a : data)
sum += a;
return sum/data.length;
}
/*IMO I have completed most of the project, but I can't wrap my mind around part with the array. I am supposed to assign the values to it then have it show on screen, as it is doing now when program get run, but it isn't going through the array. Please help its driving me insane.
Assignment:
For this project, you will create a program that asks the user to enter a positive integer value less than 20. Note that the program will only collect one number from the user. All other numbers will be generated by the program.
If the user enters a number greater than 20, the user should get an error.
If the user enters a number equal to or less than 20, display the double of each value beginning with 1 up to the selected number (multiply each number by 2), then provide the total of all doubles.
For example, if the user entered the number 5, the following should display:
Double up 1 = 2
Double up 2 = 4
Double up 3 = 6
Double up 4 = 8
Double up 5 = 10
Total = 30
Minimum Requirements:
• Create a separate class that contains the following methods. Note: This class should be separate and apart from the public class that holds the main method. 1. A method that will accept two parameters: an integer array and a integer variable. 1. The integer variable should hold the value provided by the user. The array will be used to hold the double up results.
2. This method should perform the calculations, and store the double up results in the array. Additionally, the total of all double up values should be calculated using an accumulator variable that is also a private instance variable.
3. You must make sure the calling method gets the changes to the array. Remember, arrays are passed by reference by default. This method must use a loop.
A separate method that will return (not display) the value stored in the private instance variable called total.
• Create a main method that creates an array and integer variable, as well as an instance of your class. The main method should then use the instance to call each of the methods of the class, passing the data needed and handling any return data. Display the entire contents of the array and total variable.
*/
import java.util.Scanner;
public class project2 {
public static void main(String args[]){
scores output = new scores();
output.enterNum();
output.displayScores();
}
}
class scores
{
int total;
int stats[] = new int[20];
int num1;
void enterNum()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a number between 1 and 20: ");
num1 = input.nextInt();
if(num1<=0 || num1>20)
{
System.out.println("You entered a wrong number. Try again.");
System.out.println("");
enterNum();
}
}
void displayScores()
{
int b=0;
int val2=0;
int total = 0;
val2=num1*2;
for(int i=1;b<val2;i++)
{
System.out.println(b=i*2);
total = total + b;
// this part.
// stats[i] = b;
// System.out.println(stats);
}
System.out.println(total);
}
}
Maljam is right, your for-loop is the issue here.
Your for-loop is messing around with some int b that doesn't need to be there. What you want is to add i*2 to total on each iteration of your loop. Also, you need to modify your for-loop header to check against i instead of b. I'm not really sure what you are trying to do with the array. It's not needed in this project at all.
Try changing it to something like this:
for (int i=1; i<=val1; i++){
//stats[i] = i;
System.out.println("Double up " + i + " = " + 2*i);
total = total + 2*i; //or total += 2*i;
}
System.out.println("Total: " + total);
public class scores {
int total;
int stats[];
int num1;
void enterNum() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number between 1 and 20: ");
num1 = input.nextInt();
if (num1 <= 0 || num1 > 20) {
System.out.println("You entered a wrong number. Try again.");
System.out.println("");
enterNum();
}
}
void displayScores() {
stats = new int[num1];
int total = 0;
for (int i = 0; i < num1; i++) {
stats[i] = (i+1) * 2;
total += stats[i];
}
for (int i = 0; i < num1; i++) {
System.out.println((i+1) + " * 2 = " + stats[i]);
}
System.out.println("Total: " + total);
}
}
I have an array that takes student grades from an input. I have to make a method that will find the average of the numbers within the array. Here is the code i have so far...
int mark = Integer.parseInt(input.getText());
if(mark <= 100){
marks.add(Integer.parseInt(input.getText()));
input.setText("");
warningLbl.setText("");
}
else{
warningLbl.setText("Please enter an number between 0-100");
}
I want to take the contents in the array 'marks' and get an average for them then append it in my text area
public static double getAverage(int[] marks)
{
int sum = 0;
for(int i : marks) sum += i;
return ((double) sum)/marks.length;
}
This is the method i have to find the average, but i dont know how to use this method and get it to print in a text area
If you want to find the average stored in an array , try the following function.
public static double average(int[] marks)
{
int sum = 0;
double average;
for(int element: marks)
{
sum = sum + element;
}
average = (double)sum / marks.length;
return average;
}
Hope it helps ! :)
The above method is used to find average in an array(primitive type) , but to find average in List type array(wrapper class) , we have to iterate through each element in the list by this way and do the required calculations :
public static String average(Integer[] marks)
{
int sum = 0;
double average;
for (int i = 0; i < marks.size(); i++)
{
sum = sum + marks.get(i);
}
average = (double) sum / marks.size();
String averageString = Double.toString(average);
return averageString;
}
This returns your average in string type directly.
There are several problems with your current code.
Using input.getText(); twice will mean it's going to prompt for input twice. Have a single line like int mark = Integer.parseInt(input.getText()); then use the mark variable wherever it's needed.
In order to test if the number is between 0 and 100 (I'm assuming this needs to be inclusive), that if statement would need to be (mark >= 0 && mark <= 100).
I assume you want to get multiple students' grades/marks, so it may be a good idea to enclose your code in a for or while loop, depending on how you want it to operate. However, since this will be of variable length I'd recommend using a List over an array for resizing.
Finding the average is easy. Just use a foreach loop to sum up all the numbers, then divide that by the array length.
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
}
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.