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);
Related
I am aiming to create a method which prints the total cost of all employees that are added to an array.
Salary is added to the array using:
**Scanner sal = new Scanner(System.in);
System.out.println("Enter annual employee salary $");
int salary = sal.nextInt();
salaryArray[index] = salary;
index++;**
I then use the following to get the sum:
public static void cost()
{
int sum = 0;
for (int i = 0; i < salaryArray.length; ++i)
{
System.out.println(sum += salaryArray[i]);
}
}
The problem is it prints out the result multiple times, I would like it to print only once, giving only one result. Further changes seem to break my code when I try to fix it.
For each salary added you print the current sum.
You want to print the sum after the loop. So do that
As improvement, you could use a more meaningful name for the method as method names should generally start by an infinitive verb.
You could also use an enhanced for as the index variable is only used to iterate every element. The enhanced for provides it in a cleaner way.
public static void displayCost() {
int sum = 0;
for (int salary : salaryArray){
sum += salary;
}
System.out.println(sum);
}
public static void cost()
{
int sum = 0;
for (int i = 0; i < salaryArray.length; ++i)
{
sum += salaryArray[i];
}
System.out.println(sum);
}
Just show sum variable once .
You are printing the result in a for loop, of course it would print multiple times. why not try this;
for(int i = 0; i < salaryArray.length; i++){
sum += salaryArray[i];//getting the value of the sum first
}
System.out.println(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);
}
}
This is the original prompt:
Write program that declares a 2-dimensional array of doubles called scores with three rows and three columns. Use a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Finally, use a nested for loop to compute the average of the doubles in each row and output these three averages to the command line.
Here is my code:
import java.util.Scanner;
public class Scorer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int i = 0;
int j;
while (i < 3) {
j = 0;
while (j < 3) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[i][j] = value;
j++;
}
i++;
}
int average = 0;
for (i = 0; i < scores.length; i++) {
for (j = 0; j < scores[i].length; j++) {
average += value;
value = value / scores[i][j];
System.out.println(value);
}
}
}
}
The part that I need help on is the nested for loop at the bottom of the code. This code is supposed to compute the average of the numbers that are entered; however, I am confused on how to do that with the nested for loop.
you're almost there!
Here are the things you need to do:
1)you've to initialize the variable 'average' after the first for loop.
because average needs to be 0 i.e., reset after second for loop ends each time.
2)you've defined "value = value / scores[i][j]" . I don't know why you did that, but "value = scores[i][j]" must solve your problem.
3) you should print the average only thrice i.e., after calculating average of each row. so, print average at the end of second for loop.
Hope this makes it clear.
here's the code for your reference:
for (i = 0; i < 3; i++) {
int average = 0;
for (j = 0; j < 3; j++) {
value = scores[i][j];
average += value;
}
System.out.println(average/3);
}
Ever i represents a row, every j represents a column.
You need the average of every row, meaning that for every same i and every different j for that i you need to store the values and calculate the average.
Looks like homework code. We can give you hints but not write it for you :(
I have declared an array that i would like to multiply the value of the first column by value of the second column of each row and create a grand sum of these products. I have tried the code listing below, what am i missing
public class Arrays {
public static void(String[] args) {
int array_x[][]={{9,8},{2,17},{49,4},{13,119},{2,19},{11,47},{3,73}};
int sum = 0;
for (int i = 0; i < array_x.length; i++) {
for (int j = 0; j < array_x.length; j++) {
array_x[i][j] = i * j;
System.out.println("\n" + array_x[i][j])
}
}
}
}
The output should be something like
9*8=72
2*17=34 etc then sum the whole results as 72+34+....
The code you wrote had several issues, including the fact that it would not compile because you had a different number of open and closed brackets, you didn't specify the function name (which I assumed to be main) and there was a ; missing. However the biggest issue was a logical one: you only need a single for to do what you want to do. You know that the indices of the second dimension of the array are going to be 0 and 1, because as you said the array has only two columns. Also, you need to accumulate the products into sum, instead you initialized sum to 0 and never updated it. Finally, the instruction array_x[i][j] = i * j multiplies the indices instead of the values, so the result is not what you expect, and this result is put into array_x, which is the wrong place because you really don't need to alter the input array.
class Arrays{
public static void main(String[] args){
int array_x[][]={{9,8},{2,17},{49,4},{13,119},{2,19},{11,47},{3,73}};
int sum=0;
for(int i=0;i<array_x.length;i++) {
int prod = array_x[i][0] * array_x[i][1];
System.out.println("\n"+prod);
sum += prod;
}
System.out.println("Final: " + sum);
}
}
The code you originally wrote is actually what you need to build a multiplication table, but in that case you need an array with an equal number of rows and columns.
public class Arrays {
public static void main (String[] args) {
int array_x[][]={{9,8},{2,17},{49,4},{13,119},{2,19},{11,47},{3,73}};
int multiply[] = new int[7];
for (int i = 0; i < array_x.length; i++) {
multiply[i] = array_x[i][0] * array_x[i][1];
}
int sum = 0;
for(int i = 0; i < multiply.length; i++)
{
System.out.println(array_x[i][0] + "*" + array_x[i][1] + "=" + multiply[i]);
sum += multiply[i];
}
System.out.println("Sum:" + sum);
}
}
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);
}
}
}