output blank--Java program to calculate average of array - java

I am writing a program that takes 10 floating point numbers as inputs, and displays the average of the numbers followed by all of the numbers that are greater than the average. I am using a method that takes an array of doubles as a parameter and returns the average of the data in the array. However, my problem is that when I run my program the output window is completely blank. I assume this is because I did not call in my method to the main method. However, I am not sure how to write that code. Thank you.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
}
public double average(double[] number) {
Scanner scanner = new Scanner(System.in);
int x = 0;
double sum = 0;
double[] numberList = new double[10]; //array to hold all numbers
double[] largerList = new double[10]; //array to hold numbers greater than the average
int numberIndex = 0;
int largerIndex = 0;
System.out.printf("Please enter 10 floating-point numberes.\nIf more than 10 values are entered, the numbers following 10 are ignored.\nIf less than 10 numbers are entered, the program will wait for you to enter 10.\n");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
sum += numberList[x]; //add up all inputs to find sum
} catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
scanner = new Scanner(System.in);
i = -1;
numberIndex = 0;
largerIndex = 0;
numberList = new double[10];
largerList = new double[10];
continue;
}
}
for (int i = 0; i < number.length; i++) {
sum = sum + number[i];
double average = sum / number.length;
System.out.println("Average value of your input is: " + average);
System.out.println();
//return average;
if (x > average) {
largerList[largerIndex] = x; //add negative input to negativeList array
largerIndex = largerIndex + 1;
}
}
for (int i = 0; i < largerIndex; i++) {
System.out.println(largerList[i]);
}
return 0;
}
}

to answer the main question...
However, my problem is that when I run my program the output window is completely blank. I assume this is because I did not call in my method to the main method. However, I am not sure how to write that code.
public static void main(String[] args) {
new Average().average(new double[10]);
}
Or maybe you are thinking something like this...
public static void main(String[] args) {
double[] numbers = {2,3,4,5,6,4,3,2,1,3};
new Average().average(numbers);
}
A output run from above (with the doubles given):
Please enter 10 floating-point numberes.
If more than 10 values are entered, the numbers following 10 are ignored.
If less than 10 numbers are entered, the program will wait for you to enter 10.
2
3
3
4
1
2
3
4
5
1
Average value of your input is: 0.2
Average value of your input is: 0.5
Average value of your input is: 0.9
Average value of your input is: 1.4
Average value of your input is: 2.0
Average value of your input is: 2.4
Average value of your input is: 2.7
Average value of your input is: 2.9
Average value of your input is: 3.0
Average value of your input is: 3.3
1.0
1.0
1.0
Press any key to continue . . .
If you have question about the code itself, then it would be better to create a new question or edit it to make it more clear.
Good luck with your coding.

Your method average() takes an array of doubles, but then retrieves an other array from standard input. That doesn't make sense.
Either get the doubles and pass them to the method, or don't pass them to the method and get them from standard input.

What you need to do is create an instance of Average class in your main method and call the average() method.
Why parse double array in your average() method when you take the input from user?

well,you are using a non static method "average()" for your task which needs an instances of the class to run which are not creating anywhere.so there are only two options:-
#1.create an instances of your class then call it.
public static void main(String... s)
{
Average obj=new Average();
obj.average();
}
#2.make "average()" a static method by adding static keyword.
public static double average()
{
//your code.....
}
public sttatic void main(String... s)
{
average();
}
your dont need to keep an argument in your method.

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

Exception in thread "main" java.lang.IndexOutOfBoundsException: [duplicate]

This question already has answers here:
sublist index out of bound exception
(3 answers)
Closed 4 years ago.
The program uses methods to:
get the numbers used to calculate the average,
get the number of lowest numbers to drop before calculating the
get the weight, a double greater than 0 and less than or equal to 1,
calculate the weighted average of the numbers (except the lowest n numbers) entered by the user, and
print the results.
The first method should take no arguments and return an array list of doubles.
The second method should take no arguments and return a single integer, the number of the lowest numbers to drop before calculating the average.
The third method should take no arguments and return a double (the weight)
The fourth method should take three arguments: an array list of numbers (the return value of the first method above); an integer (the number of smallest items to drop before calculating the average); and a double (the weight). This method should return a double (the weighted average of all the numbers except the lowest n values).
The fifth method should take four arguments: an array list of numbers (the return value of the first method above); an integer (the number of smallest numbers to drop before calculating the average); a double (the weight); and a double (the weighted average returned from the fourth method above). This method should have no return value.
For example:
If the user gives these numbers for calculating the average:
40 60 80 100 20
and the user gives the number 2 to indicate how many of the lowest values should be dropped before calculating the average, and gives a weight of 0.5, then the program should give as output:
The weighted average of the numbers is 40.0, when using the data 40.0, 60.0, 80.0, 100.0, 20.0, where 0.5 is the weight used, and the average is computed after dropping the lowest 2 values.
import java.util.*;
import java.lang.*;
import java.util.ArrayList;
import java.util.Collections;
public class MyClass
{
public static ArrayList<Double> getALInfo()
{
Scanner in=new Scanner(System.in);
ArrayList<Double> inputs = new ArrayList<>();
System.out.println("Please enter 5 - 10 integers, Q to quit: ");
String [] tokens = in.nextLine().split("\\s");
for (int i = 0; i < tokens.length; i++)
inputs.add(Double.parseDouble(tokens[i]));
return inputs;
}
public static int getLowestnum()
{
int lowNum = 0;
System.out.println("How many of the lowest values should be dropped? ");
Scanner in = new Scanner(System.in);
lowNum = in.nextInt();
return lowNum;
}
public static double weight()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the weight: ");
double weight = in.nextDouble();
return weight;
}
public static double calculateAvg(ArrayList<Double> inputs,double weight, int lowNum)
{
double sum = 0;
double average = 0;
Collections.sort(inputs);
ArrayList<Double> inputs1 = new ArrayList<Double>(inputs.subList(lowNum, inputs.size()+1));
for (int i = 0; i < inputs1.size(); i++)
{
if (inputs1.get(i) > lowNum)
{
sum = sum + inputs.get(i);
}
}
sum=weight*sum;
average = (sum / inputs1.size());
return average;
}
public static void getAvg(ArrayList<Double> inputs,int n,double weight, double average)
{
System.out.println("The weighted average of the numbers is " + average + ", when using the data " + inputs + " where " +weight+ " is the weight used, and the average is computed after dropping the lowest " +n+" values");
}
public static void main(String args[])
{
int lowNum = 0;
double average;
double weight=0;
ArrayList<Double> inputs= getALInfo();
lowNum = getLowestnum();
weight=weight();
average = calculateAvg(inputs,weight, lowNum);
getAvg(inputs, lowNum,weight, average);
}
}
The program is running fine util you enter the weight after that it shows an array out of bounds exception error. Can you point out where im going wrong .
The error comes from new ArrayList<Double>(inputs.subList(lowNum, inputs.size()+1))
Because you try to reach, as end index, the last element +1 so it does not exists
Solve :
new ArrayList<Double>(inputs.subList(lowNum, inputs.size()))
!! Also, your for loop is wrong
don't need to check with this strange if
you don't pick up from the correct list : use better names
for (int i = 0; i < inputs1.size(); i++) {
if (inputs1.get(i) > lowNum) {
sum = sum + inputs.get(i);
}
}
Solve
ArrayList<Double> subList = new ArrayList<>(inputs.subList(lowNum, inputs.size()));
for (int i = 0; i < subList.size(); i++) {
sum = sum + inputs.get(i);
}

Logical error in loop program

import java.util.Scanner;
public class Unit2Err2{
public static void main( String[] args ){
Scanner scan = new Scanner(System.in);
double sum = 0;
double count = 0;
double in = scan.nextDouble();
while (scan.nextDouble()!= 0){
sum = sum + in;
count++;
}
double avg= sum/count;
System.out.println("The average is " +avg);
}
}
Input: 5 4 3 0 6 4 3
In particular I don't have any errors, I did have a error which said:
incomparable types: boolean and int.
But I fixed it, my issue now is that the average should be 4 instead of 5. I'm wondering where the error is in this, I have tried rearranging it so my average comes out to 4 , but then I often end up with the same error as above.
import java.util.Scanner;
public class Unit2Err2{
public static void main( String[] args ){
Scanner scan = new Scanner(System.in);
double sum = 0;
double count = 0;
double in ;
while ( (in = scan.nextDouble())!= 0){
sum = sum + in;
count++;
}
double avg= sum/count;
System.out.println("The average is " +avg);
}
}
when you first use nextDouble here double in = scan.nextDouble(); it has read a value from the terminal.
You need to re-assign in at each iteration:
while ((in = scan.nextDouble()) != 0){
sum += in;
count++;
}
The program stops and waits for input when it sees the "scan.nextDouble()" statement. Having two in a row is going to read both 5 and 4 without doing anything with the values.
The current code assigns the first input of 5 to the variable in. After that, in is never assigned the value. So 5 is being added each loop iteration.

Storing double up value in an Array using for loop?

/*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);
}
}

wrong results from simple java method [duplicate]

This question already has answers here:
Simple division in Java - is this a bug or a feature?
(5 answers)
Closed 7 years ago.
I'm trying to write a program that asks for the size of an array of integers, the values of the array, and then finds the average of the positive integers and prints it. When I run it, I sometimes get wrong results. I haven't identified on what the wrong results depends but for example if I enter the following input: "array size: 4, array values: 1, 2, -5, 5" I get an average of "2.0"
Here's my code:
import java.util.Scanner;
public class Mitra {
private static Scanner user_input;
double avg (int[] arr, int size)
{
int sum = 0;
int numbers = 0;
for (int i=0; i<size;i++)
{
if (arr[i]>0)
{
sum = sum+arr[i];
numbers++;
}
else{
continue;
}
}
double average = sum/numbers;
return average;
}
public static void main(String[] args) {
user_input = new Scanner (System.in);
System.out.println("enter array length");
int alength = user_input.nextInt();
int[] array_1 = new int[alength];
for (int i=0; i<alength;i++)
{
System.out.println("Enter array value "+i);
array_1[i] = user_input.nextInt();
}
Mitra obj = new Mitra();
double result = obj.avg(array_1, alength);
System.out.println("The average of the positive numbers of the array is "+result);
}
}
Change
double average = sum/numbers;
to
double average = (double)sum/numbers;
to force floating point division.
Otherwise, int division (which is the operation that takes place when dividing two variables of int type) will give you 2 when dividing 8/3 (as you do in your example).
When you evaluate sum/numbers it stores the result in a temporary variable(and the decimal part is already truncated) and then assigns it on the left side.You need to typecase it with (Double) like this:
double average = (double)sum/numbers;

Categories

Resources