import java.util.*;
import java.lang.*;
public class MyClass
{
String[] getdata()
{
Scanner in=new Scanner(System.in);
System.out.print("Enter numbers to calculate their average (choose 5 to 10 numbers only : ");
String[] a=in.nextLine().split(" ");
return a;
}
double average(String[] num)
{
double avg;
int tot=0;
int[] numbers = new int[num.length];
int l=num.length;
for(int j=0;j<l;j++)
{
tot=tot+numbers[j];
}
avg=tot/l;
return avg;
}
void results(String[] arr,double avg)
{
int[] numbers1=new int[arr.length];
int ll=arr.length;
System.out.print("The average of the numbers ");
for(int i=0;i<ll;i++)
{
numbers1[i]=Integer.parseInt(arr[i]);
System.out.print(numbers1[i]+" ");
}
System.out.print("is ");
System.out.printf("%.2f",avg);
}
public static void main(String args[])
{
MyClass obj=new MyClass();
String[] x=obj.getdata();
double y=obj.average(x);
obj.results(x,y);
}
}
The code is running successfully but for any given output the average is showing as 0.00.
The code takes in integers with space between them and calculates the average and displays it
Help me fix it. Thanks
You do not initialize your numbers array inside average() method.
Instead of tot=tot+numbers[j]; do the following
tot = tot + Integer.parseInt(num[j]);
And to avoid integer deletion change calculation if avg to the following
avg = 1.0 * tot / l; //this will cast intermediate result of 1.0 * tot to double.
There are several issues with your code:
The only thing int[] numbers shares with String[] num input is length. All items of the array remain zero, which in itself is sufficient to explain zero result
Even though avg is double, tot/l is an int. It could be truncated down to zero, depending on the values inside num.
You need to modify your code to parse Strings from num, and compute total as double. After that the division would return the correct result.
Further, you can avoid multiple parses of strings if you return int[] from getdata() method. Given the small number of inputs, this one is not critical for performance of your code.
You never copy the values from String[] num to your int[] numbers, so when you loop through the whole array numbers, you are going to be summing the default value 0, l times.
You need to use parseInt() on all the values in num to convert it to ints and store them in numbers, then make sure you do float(tot)/l to cast it to a float during the division. This avoids truncation due to integer division.
In the average method you create an empty array called numbers. You're calculating the average based on that array which is empty.
Hope this helps
Your numbers array is wrong in the average function. Please find the corrected code below,
double average(String[] num)
{
double avg;
int tot=0;
int l=num.length;
for(int j=0;j<l;j++)
{
tot=tot+Integer.parseInt(num[j]);
}
avg=tot/l;
return avg;
}
Change the data types as you need.
I'd recommend printing a from getdata() to ensure that your numbers are getting entered correctly. My best guess is taht something in the split command is not working right.
Your problem is your average function. You initializes the array of int[] num, but you did not write the int value in it. You can do that as in the same way as in void results(String[] arr,double avg).
Another problem is, that you get the average avg = tot/l; where tot and l are int values. When you divide 2 integer values the result is an int too and the int value will be written into 'avg'. If the average is a floiting point number (example input "1 2", then the floiting part get cutoff and your programm returns the avg = 1. Therefore the division needs at least one variable, which is double.
This one should work:
double average(String[] num)
{
double avg;
double tot=0;
int l=num.length;
for(int j=0;j<l;j++)
{
tot=tot+Integer.parseInt(num[j]);
}
avg= tot/l;
return avg;
}
In your code you are not initializing the numbers[] array .
double average(String[] num)
{
double avg;
double tot=0;
int[] numbers = new int[num.length];
for(int i=0;i<num.length;i++)
{
numbers[i]=Integer.parseInt(num[i]);
}
int l=num.length;
for(int j=0;j<l;j++)
{
tot=tot+numbers[j];
}
avg=tot/l;
return avg;
}
If you are using > Jdk8 . you can use
double average(String[] num) {
OptionalDouble tot = Arrays.stream(num).mapToInt(s -> Integer.parseInt(s)).average();
return tot.orElse(0.0);
}
}
Related
I made a simple program that calculate the Mean and Median value of given array from command-line.
import java.util.Arrays;
public class EdankJaya {
public static void main(String args[]) {
double sum = 0;
double d;
if(args.length < 1) {
System.out.println("Usage : java EdankJaya <Number1> <Number2> ..");
System.exit(1);
}
//Mean
for(String s : args) {
d = Double.parseDouble(s);
sum = sum+d;
}
double mean = sum/args.length;
System.out.println("Mean: " + mean);
//Median
Arrays.sort(args);
int med = args.length/2;
if((args.length % 2) == 0) {
double median1 = Double.parseDouble(args[med-1]);
double median2 = Double.parseDouble(args[med]);
System.out.println("Median :"+(median1+median2)/2);
} else {
double median = Double.parseDouble(args[med]);
System.out.println("Median :"+median);
}
}
}
Technique that i used for Median value is divide args.length by 2 and store it in med. If args.length value is even, it'll be args[med-1] + args[med], no problem for even number. And for odd args.length value, it'll just be args[med], which is works fine on the paper since integer will not produce fraction(11/2 gonna be 5), but here's what happened:
Everything's good until i inputted 1-10, the value turned back to the result when i inputted 1-8, and 1-11 just like 1-7, and so on.
What could be the issue here.
Thanks.
Your array has strings in it, not numbers, so they are not sortting in numerical order. They're probably sorting in ASCII order. Since you're already iterating over the array and converting them to numbers, build a second array with them and sort that one.
I was calculating a simple combination using java, when I define the result as double, the answer seems right, only lost some precision, but when I use the BigInteger class, the answer looks just wrong at all, I don't see why it's like that, here is the code.
import java.math.BigInteger;
import java.util.Scanner;
public class Test {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please input the lottery sum");
int num = in.nextInt();
System.out.println("Please input the available sum");
int avail = in.nextInt();
//double sum = 1;
BigInteger sum = BigInteger.ONE;
for (int i = avail - 1; i >= 1;i--){
//sum = sum*(num - i) / i;
sum = sum.multiply(BigInteger.valueOf(num - i)).divide(BigInteger.valueOf(i));
}
//sum = sum * num / avail;
sum = sum.multiply(BigInteger.valueOf(num)).divide(BigInteger.valueOf(avail));
System.out.println(sum);
in.close();
}
}
The main difference between double and BigInteger is that one is using float-point maths, and other is using integer maths. This means that, when you using BigInteger, the result of every division gets truncated.
I'm not sure what you're calculating, but I suspect that the integer division is what's causing the observed differences.
I suppose that you get the same result with BigInteger and a regular int for small examples.
For example:
double:
3.0/2.0 = 1.5
(Big)Integer:
3/2 = 1
If you sum over such divisions multiple times, the discrepancy gets bigger and bigger.
Take a look at BigDecimal, that may be the solution you're after to avoid this error introduced by integer divisions.
import java.util.ArrayList;
public class Variance {
// Copy here sum from exercise 63
public static int sum(ArrayList<Integer> list) {
int sum = 0;
for(int i=0; i<list.size(); i++ ){
sum = sum + list.get(i) ;
}
return sum;
}
// Copy here average from exercise 64
public static double average(ArrayList<Integer> list) {
double average = sum(list)/list.size();
return average;
}
public static double variance(ArrayList<Integer> list) {
// write code here
double sumMinusAverage = sum(list) - average(list);
return sumMinusAverage * sumMinusAverage / (list.size()-1);
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(2);
list.add(7);
list.add(2);
System.out.println("The variance is: " + variance(list));
}
}
The program is calculating variance. But when when the list contains the same numbers etc 1-s. The program says the variance is 3, but the answer should be 0.
Can someone give me some direction.
The integer division Luiggi Mendoza has already mentioned is a problem you need to fix, but additionally, your algorithm for computing the variance is not correct. It's not the square of the difference between the sum and the average in the numerator.
You must sum up the differences of the individual elements from the average. Dividing by (list.size() - 1) is correct for the sample variance.
public static double variance(ArrayList<Integer> list) {
double sumDiffsSquared = 0.0;
double avg = average(list);
for (int value : list)
{
double diff = value - avg;
diff *= diff;
sumDiffsSquared += diff;
}
return sumDiffsSquared / (list.size()-1);
}
Be careful when there is only one item in the list. The variance should be 0, but you'll need to check the size to avoid a divide-by-zero exception.
Also, if you ever want the population variance, divide by list.size() instead.
The problem is here:
double average = sum(list)/list.size();
sum(ArrayList<Integer>) returns an int, and sum(list)/list.size() is an integer division, so you'll get an int as result. The decimal part of the division will be truncated.
In order to fix this, you should cast one of the operands of the division to double:
double average = ((double)sum(list))/list.size();
Similar in variance method.
This is unrelated to the main problem, but you should code oriented to interfaces, not to direct class implementations. This means, declare your variables and parameters as List<Integer> instead of ArrayList<Integer>. Here's an example:
public static int sum(List<Integer> list) {
int sum = 0;
for(int i=0; i<list.size(); i++ ){
sum = sum + list.get(i) ;
}
return sum;
}
//...
List<Integer> list = new ArrayList<Integer>();
Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:
A method that accepts two integer parameters and returns their average.
A method that accepts three integer parameters and returns their average.
A method that accepts two integer parameters that represent a range.
Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).
Implement the class and write a program to test its methods and submit your source code (.java files).
I am stuck on part three, I don't even really understand the stipulation. Will I be using a floating point / double? Here is the program I have thus far:
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
int numb1, numb2, numb3, userInput;
System.out.println("Enter '2' if you wish to average two numbers enter '3' if you wish to average 3.");
Scanner keyboard = new Scanner(System.in);
userInput = keyboard.nextInt();
if (userInput == 2){
System.out.println("Enter two numbers you'd like to be averaged.");
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
Average ave = new Average();
System.out.println("The average is: " + ave.average(numb1, numb2));
System.exit(1);
}
if(userInput == 3){
System.out.println("Enter three numbers you'd like to be averaged.");
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
numb3 = keyboard.nextInt();
Average ave = new Average();
System.out.println("The average is: " + ave.average(numb1, numb2, numb3));
System.exit(1);
}
}
public static int average (int num1, int num2) {
return (num1 + num2) / 2;
}
public static int average (int numb1, int numb2, int numb3){
return (numb1 + numb2 + numb3) / 3;
}
}
Please don't re-ask the same question as you just asked here: http://stackoverflow.com/questions/19507108/java-averaging-program
Rather update your other post to reflect your new code / questions.
Now onto your question:
A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive). Implement the class and write a program to test its methods and submit your source code (.java files).
Lets start by declaring our method and we'll declare it as static to conform to your program (since you're not creating your own objects). Then we want to check if the parameters follow the assignment instructions and return values accordingly.
public static int getRange(int firstValue, int secondValue)
{
int range;
if (firstValue > secondValue)
range = firstValue - secondValue;
else
{
range = 0;
System.out.println("Error!");
}
return range;
}
**To promote your understanding it's up to you to find the average of the integers in the range!
Not really here to do your homework, but since I'm already here, the range is the difference between the largest and smallest number.
public int returnRange(int first, int second) {
if(first > second)
return first-second;
else
return second-first;
}
To make things easier though...
public double returnAverage(int...numbers) {
for(int i = 0; i < numbers.length(); i++) {
total += numbers;
}
return total/numbers.length();
}
public int returnRange(int...numbers) {
int holder = 0;
int highest;
int lowest;
for(int i = 0; i < numbers.length(); i++) {
if(numbers[i] > holder) {
holder = numbers[i];
}
highest = holder;
for(int i = 0; i < numbers.length(); i++) {
if(numbers[i] < holder) {
holder = numbers[i];
}
}
lowest = holder;
return highest-lowest;
}
Last 2 methods are un-tested, but from experience, should work fine. These methods have arrays for the parameters, so you can do as many numbers as you'd like.
In your main method check for -1 and return error when first value is greater than second
public double avgRange(int a, int b){
if(a>b){
return -1;
}
else{
double total=0;
for(int x=a; x<=b; x++){
total = total + x;
}
return total/(b-a+1);
}
}
the method should return the average of the integers in that range (inclusive).
You're asked to return the average of all integers in the range bounded by the two parameters.
For example, if parameters were 5 and 10, the method should return the average of 5, 6, 7, 8, 9, and 10, which is 7.5. (5 and 10 are included because the question says the range should be "inclusive".)
To find the average, use a for loop to sum each integer in the range, then divide by the number of integers.
Will I be using a floating point / double?
The return value should be a float or double, since the average isn't always a whole number.
I have this code but it doesn't work!
public class Trial
{
public static void main (String [] args)
{
int average;
int m = 0;
int [] nums = {1,6,8,9,10,60,72};
average = getAverage(int [] nums);
}
public static int getAverage(int [] a)
{
int sum = 0;
for(int i=0; i<a.length; i++)
sum = sum +a[i];
int avg = sum/a.length;
return avg;
}
}
Where is the problem ? I need to get the average of that array by calling a method that calculate the average.
Change your method call:
average = getAverage(nums);
I see two problems:
average = getAverage(int [] nums) should read average = getAverage(nums).
The function returns an int. You might want to consider using floating-point math for the result. Otherwise you're truncating the answer to the nearest int.
average = getAverage(int [] nums); //this is wrong
average = getAverage(nums); //this is right. Just sintaxis.
avg can be a floating point value, but your implementation will always return integer.
Consider using floating point value for sum and avg and change return type to double.