EDIT: I've written code for the average but I don't know how to make it so that it also uses ints from my args.length rather than the array.
I need to write a java program that can calculate:
the number of integers read in
the average value – which need not be an integer!
NOTE: I don't want to calculate the average from the array but the integers in the args.
Currently I have written this:
int count = 0;
for (int i = 0; i<args.length -1; ++i)
count++;
System.out.println(count);
}
int nums[] = new int[] { 23, 1, 5, 78, 22, 4};
double result = 0; //average will have decimal point
for(int i=0; i < nums.length; i++){
result += nums[i];
}
System.out.println(result/count)
Can anyone guide me in the right direction? Or give an example that guides me in the right way to shape this code?
Thanks in advance.
Just some minor modification to your code will do (with some var renaming for clarity) :
double sum = 0; //average will have decimal point
for(int i=0; i < args.length; i++){
//parse string to double, note that this might fail if you encounter a non-numeric string
//Note that we could also do Integer.valueOf( args[i] ) but this is more flexible
sum += Double.valueOf( args[i] );
}
double average = sum/args.length;
System.out.println(average );
Note that the loop can also be simplified:
for(String arg : args){
sum += Double.valueOf( arg );
}
Edit: the OP seems to want to use the args array. This seems to be a String array, thus updated the answer accordingly.
Update:
As zoxqoj correctly pointed out, integer/double overflow is not taken care of in the code above. Although I assume the input values will be small enough to not have that problem, here's a snippet to use for really large input values:
BigDecimal sum = BigDecimal.ZERO;
for(String arg : args){
sum = sum.add( new BigDecimal( arg ) );
}
This approach has several advantages (despite being somewhat slower, so don't use it for time critical operations):
Precision is kept, with double you will gradually loose precision with the number of math operations (or not get exact precision at all, depending on the numbers)
The probability of overflow is practically eliminated. Note however, that a BigDecimal might be bigger than what fits into a double or long.
int values[] = { 23, 1, 5, 78, 22, 4};
int sum = 0;
for (int i = 0; i < values.length; i++)
sum += values[i];
double average = ((double) sum) / values.length;
This
for (int i = 0; i<args.length -1; ++i)
count++;
basically computes args.length again, just incorrectly (loop condition should be i<args.length). Why not just use args.length (or nums.length) directly instead?
Otherwise your code seems OK. Although it looks as though you wanted to read the input from the command line, but don't know how to convert that into an array of numbers - is this your real problem?
It seems old thread, but Java has evolved since then & introduced Streams & Lambdas in Java 8. So might help everyone who want to do it using Java 8 features.
In your case, you want to convert args which is String[] into double
or int. You can do this using Arrays.stream(<arr>). Once you have stream of String array elements, you can use mapToDouble(s -> Double.parseDouble(s)) which will convert stream of Strings into stream of doubles.
Then you can use Stream.collect(supplier, accumulator, combiner) to calculate average if you want to control incremental calculation yourselves. Here is some good example.
If you don't want to incrementally do average, you can directly use Java's Collectors.averagingDouble() which directly calculates and returns average. some examples here.
System.out.println(result/count)
you can't do this because result/count is not a String type, and System.out.println() only takes a String parameter. perhaps try:
double avg = (double)result / (double)args.length
for 1. the number of integers read in, you can just use length property of array like :
int count = args.length
which gives you no of elements in an array.
And 2. to calculate average value :
you are doing in correct way.
Instead of:
int count = 0;
for (int i = 0; i<args.length -1; ++i)
count++;
System.out.println(count);
}
you can just
int count = args.length;
The average is the sum of your args divided by the number of your args.
int res = 0;
int count = args.lenght;
for (int a : args)
{
res += a;
}
res /= count;
you can make this code shorter too, i'll let you try and ask if you need help!
This is my first answerso tell me if something wrong!
If you're trying to get the integers from the command line args, you'll need something like this:
public static void main(String[] args) {
int[] nums = new int[args.length];
for(int i = 0; i < args.length; i++) {
try {
nums[i] = Integer.parseInt(args[i]);
}
catch(NumberFormatException nfe) {
System.err.println("Invalid argument");
}
}
// averaging code here
}
As for the actual averaging code, others have suggested how you can tweak that (so I won't repeat what they've said).
Edit: actually it's probably better to just put it inside the above loop and not use the nums array at all
I'm going to show you 2 ways. If you don't need a lot of stats in your project simply implement following.
public double average(ArrayList<Double> x) {
double sum = 0;
for (double aX : x) sum += aX;
return (sum / x.size());
}
If you plan on doing a lot of stats might as well not reinvent the wheel. So why not check out http://commons.apache.org/proper/commons-math/userguide/stat.html
You'll fall into true luv!
public class MainTwo{
public static void main(String[] arguments) {
double[] Average = new double[5];
Average[0] = 4;
Average[1] = 5;
Average[2] = 2;
Average[3] = 4;
Average[4] = 5;
double sum = 0;
if (Average.length > 0) {
for (int x = 0; x < Average.length; x++) {
sum+=Average[x];
System.out.println(Average[x]);
}
System.out.println("Sum is " + sum);
System.out.println("Average is " + sum/Average.length);
}
}
}
// question: let, Take 10 integers from keyboard using loop and print their average value on the screen.
// here they ask user to input 10 integars using loop and average those numbers.so the correct answer in my perspective with java is below:-
import java.util.Scanner;
public class averageValueLoop {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
int sum = 0;
for (int i = 0; i < 10; i++){
System.out.print("Enter a number: ");
sum = sum + sc.nextInt();
}
double average = sum / 10;
System.out.println("Average is " + average);
}
}
}
Related
I wanted to find the missing number in series so i thought a simple idea why not add all the numbers in array which are in series and hold it in one variable and then calculate the sum of series by formula Sn=n/2(a+l) but while calculating the series sum i am getting some error.
public class Missing {
public static void main(String[] args) {
int ar [] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int sum = 0; int total=0;
for(int num: ar)
{
sum = sum+num;
}
int n = ar.length;
int a = ar[0];
int l =ar[ar.length-1];
total = [n/2*(a+l)];
System.out.print("The missing number is "+(sum-total));
}}
total = [n/2*(a+l)]; ............................(1)
This is where i am getting error.
enter image description here
You can use the below logic which is much simpler to use and understand
for(int i=0;i<ar.length-1;i++)
{
if(ar[i]!=ar[i+1]-1)
{
System.out.print("The missing number is "+(ar[i]+1)+"\n");
break;
}
}
The first thing is in total = [n/2*(a+l)]; [] is not valid syntax in this context. The second thing I noticed, is that your formula to calculate the sum seems odd, maybe you meant Sn = (n * (a + l)) / 2?. After making those two changes the code should look as follows:
public class Missing {
public static void main(String[] args) {
int ar [] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int sum = 0;
for(int num: ar)
{
sum = sum+num;
}
int n = ar.length;
int a = ar[0];
int l =ar[ar.length - 1];
int total = (n * (a + l)) / 2;
System.out.print("The missing number is "+(sum - total));
// outputs 0 which is correct nothing is missing
// Now if you remove say 12 from the array
// by changing the array to int ar [] = {1,2,3,4,5,6,7,8,9,10,11,0,13};
// you should get back -12 which means 12 is missing
}
}
If you don't want to use my above logic. You have to make changes to your code:
Edit this:
int n = ar.length+1;
n has been assigned ar.length + 1 because that +1 is needed to compensate for the missing element in the array list
Also, the formula has not been correctly written into the code:
total = (n* (a + l))/2;
If you first divide n by 2 then, it will truncate the places after decimal point because n is an integer not a floating number. So, your logic would fail when n is not even.
And lastly, the missing number would be (sum-total) not the other way around because 'total' contains the missing number and 'sum' does not.
System.out.print("The missing number is "+(total-sum));
I want to ask how to add the values and find average of values in an array. I have tried searching multiple times, but I could find something that explains how to do all that in simple code that a new programmer such as myself could understand. If someone could tell me how to do it and explain the codes used, that will be great. Thanks in advance :>
I leave the normal answers for others to do. For java people,Here we go!
public static void main(String[] args) {
int myarr[]={1,2,3,4,4,5,6,5,7,8,4};
IntSummaryStatistics statisticalData=Arrays.stream(myarr).summaryStatistics();
System.out.println("Average is " + statisticalData.getAverage());
System.out.println("Sum is " + statisticalData.getSum());
}
Other data like count,minimum element,maximum element can also be obtained from the IntSummaryStatistics object
public static void main(String args[]) {
Scanner s = new Scanner(System.in); //Define Scanner class object which will aid in taking user input from standard input stream.
int a[] = new int[10]; //Define an array
int i,sum = 0;
for(i = 0; i < 10; i++) {
a[i] = s.nextInt(); //Take the arrays elements as input from the user
}
for(i = 0; i < 10; i++) { //Iterate over the array using for loop. Array starts at index 0 and goes till index array_size - 1
sum = sum + a[i]; //add the current value in variable sum with the element at ith position in array. Store the result in sum itself.
}
double avg = (double) sum / 10; //Compute the average using the formula for average and store the result in a variable of type double (to retain numbers after decimal point). The RHS of the result is type casted to double to avoid precision errors
System.out.print(sum + " " + avg); //print the result
}
At first you have to take an array of numbers. Iterate all the numbers in the array and add the numbers to a variable. Thus after iteration you will get the sum of the numbers. Now divide the sum by count of numbers (which means the size of array). Thus you will get the average.
int[] numbers = {10, 20, 15, 56, 22};
double average;
int sum = 0;
for (int number : numbers) {
sum += number;
}
average = sum / (1.0 * numbers.length);
System.out.println("Average = " + average);
You can also iterate in this way:
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
void sumAndAverage(int a[]){
if(a!=null&&a.length>0{
int sum=0;
//traverse array and add it to sum variable
for(int i=0;i<a.length;i++){
sum=sum+a[i];
}
double avg=(1.0*sum)/a.length;
System.out.println("sum= "+sum);
System.out.println("average= "+avg);
}
}
I want to find all possible binary permutations with a given number of ones in Java:
x is the desired number of ones in each sequence
n is the desired length of each sequence
For an example:
x=2, n=4
Output: 1100, 0011, 1010, 1001, 0101, 0110
I'm searching for an elegant and fast way to do this. Can you help me?
I've tested eboix solution in Print list of binary permutations but it is unfortunately too slow because the algorithm in this example is searching for all 2^n binary permutations.
I want to find sequences with a length of 50 or 100.
First of all, you're missing 0110 as an output case.
It's fairly intuitive that there are n choose x possibilities. You're finding all valid arrangements of x identical items among n total slots. So you can find the total number of sequences in O(1).
As a hint, try simply finding all permutations of the bitstring consisting of x ones followed n - x zeros.
To specifically address the problem, try creating a recursive algorithm that decides at every ith iteration to either include 1 or 0. If 1 is included, you need to decrement the count of 1's available for the rest of the string.
Actually, there may be an elegant way, but no fast way to do this. The number of string permutations is given by the binomial coefficient (see https://en.wikipedia.org/wiki/Binomial_coefficient). For example, x=10, n= 50 gives over 10 million different strings.
Here is just a basic version that will generate your desired output. Please work on it to make it more accurate/efficient -
This will not generate all the combinations, but you will get the idea of how to do it. Off course, for all the possible combinations generated by this, you will have to generate all the other possible combinations.
public class Test {
static int iter = 0;
public static void main(String args[]){
int n = 50;
int x = 5;
byte[] perms = new byte[n];
for(int i=0; i<x; i++){
perms[i] = 1;
}
print(perms);
for(int j=x-1; j>=0; j--){
for(int i=1; i<(n/2-j); i++){
iter++;
swap(perms, j, i);
}
}
}
public static void swap(byte[] perms, int pos, int by){
byte val = perms[pos+by];
perms[pos+by] = perms[pos];
perms[pos] = val;
print(perms);
val = perms[pos+by];
perms[pos+by] = perms[pos];
perms[pos] = val;
}
public static void print(byte[] perms){
System.out.println("iter = "+iter);
for(int i=0; i<perms.length; i++){
System.out.print(perms[i]);
}
System.out.println();
for(int i=perms.length-1; i>=0; i--){
System.out.print(perms[i]);
}
System.out.println();
}
}
Another inspiration for you. A dirty version which works. It allocates extra array space (you should adjust size) and uses String Set at the end to remove duplicates.
public static void main(String[] args) {
int x = 2;
int n = 4;
Set<BigInteger> result = new LinkedHashSet<>();
for (int j = x; j > 0; j--) {
Set<BigInteger> a = new LinkedHashSet<>();
for (int i = 0; i < n - j + 1; i++) {
if (j == x) {
a.add(BigInteger.ZERO.flipBit(i));
} else {
for (BigInteger num : result) {
if (num != null && !num.testBit(i) && (i >= (n - j) || num.getLowestSetBit() >= i-1))
a.add(num.setBit(i));
}
}
}
result = a;
}
String zeros = new String(new char[n]).replace("\0", "0");
for (BigInteger i : result) {
String binary = i.toString(2);
System.out.println(zeros.substring(0, n - binary.length()) + binary);
}
}
EDIT: changed the primitives version to use BigInteger instead to support larger n,x values.
I'm having trouble figuring this out:
Write a fragment that uses a for statement to set the double variable sum to the value of:
Here's what I tried:
class thing
{
public static void main (String [] args)
{
double sum = 1;
for (int i = 1; i<=25; i++)
{
sum += Math.pow(i,1.0/i) ;
System.out.println(sum);
}
}
}
I know this is wrong because it does not end with the proper calculation of 1.137411462.
Any help is appreciated! :)
To add to the other replies above, that sum must start with 0, the calculation as you described isn't accurate.
The value of 25√25 is 1.137411462, not the sum from 1 to 25, in which case if you start with
int sum = 0;
You end up with the total: 30.85410561309813 which is the correct total that you want.
change sum to zero at start .you are adding additiona 1 to sum.
double sum = 0;
for (int i = 1; i<=25; i++)
{
sum += Math.pow(i,1.0/i) ;
}
System.out.println(sum);
I am trying to catch the lowest double from user input. I am only catching the value of the initialized min variable - what am I missing? Thanks!
public static void main(String[] args) {
double[] lowNum = new double[10];
Scanner input = new Scanner(System.in);
for (int i=0; i<=9; i++) {
System.out.println("Enter a double: ");
lowNum[i] = input.nextDouble();
}
input.close();
double min = calcLowNum(lowNum);
System.out.println(min);
}
public static double calcLowNum(double[] a) {
double min=0;
for (int i=0; i>=9; i++){
for (int j=0; j>=9; j++){
if (a[i]<=a[j] && j==9){
min=a[i];
}
else {
continue;
}
}
}
return min;
You could just use Collections#min to find the minimum value. You will need Apache Commons-Lang for this though.
// This would be the array 'a'
double[] array = {15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Convert the primitive array into a Class array
Double[] dArray = ArrayUtils.toObject(array);
List<Double> dList = Arrays.asList(dArray);
// Find the minimum value
Double returnvalue = Collections.min(dList);
return returnvalue; // or you can do returnvalue.doubleValue() if you really want
First of all, change the i>=9 and j>=9 to i<=9 and j<=9 in:
for (int i=0; i>=9; i++){
for (int j=0; j>=9; j++){
Otherwise, your loops are effectively no-ops.
A far more robust approach is to write the loops like so:
for (int i = 0; i < a.length; i++) {
or like so:
for (double val : a) {
Finally, finding the minimum can be done by iterating over the array just once, comparing each element with the current minimum (but make sure to initialize min appropriately!)
If You really need to store all inputs and than find minimal, easiest way to do it to use library function for sorting array:
...
//sorting array, so first element will be the lowest
Arrays.sort(lownum);
double min = lownum[0];
I agree with Peter Lawree You don't actually need all the array; You need to save first input and all the followings compare with it and store if lower:
double lastInput=0, min=0;
for (int i=0; i<=9; i++) {
System.out.println("Enter a double: ");
lastInput = input.nextDouble();
if (0==i) {
//if this is first iteration, save first input as min
min=lastInput;
} else {
if (lastInput<min) min=lastInput;
}
}
return min;
P.S. Actually, You should use Double.compare to compare doubles. So example with Arrays.sort() better if number of inputs not huge, in this case first example will take much more memory and time to execute.
Update: Java8 solution
double findMin(double[] input) {
return Arrays.stream(input).min().getAsDouble();
}
OMG, iterate over array - this is the worst workaround (but my bad english is more worse than it). Look at http://code.google.com/p/guava-libraries/ This lib contains robust code for your need (de-facto must have library in your project). You can see and analyze sources - it's free , but you experience in best practice will be grown as my english skills.
Below is excample of guava code:
public static double min(double... array) {
checkArgument(array.length > 0);
double min = array[0];
for (int i = 1; i < array.length; i++) {
min = Math.min(min, array[i]);
}
return min;
}
P.S: learn libraries with standart code and do not reinvent the wheel. Be happy!