Need help storing values i get from a while loop - java

I would like to be able to store the data I get which is the sum from this while loop so I can add them together in the end.
public class Sum
{
public static void main(String[] args)
{
double second = 1;
double n = 4;
double start = 1;
double sum1= 1.0;
while(second<=n)
{
sum1 = start/second;
second++;
System.out.println(sum1);
}
}
}

You can add the value to the sum1 variable and at last, you can get the total of all the values.
public class Sum
{
public static void main(String[] args)
{
double second = 1;
double n = 4;
double start = 1;
double sum1 = 0;
while(second<=n)
{
sum1 += start/second;
second++;
}
System.out.println(sum1);
}
}

Related

java, counting Standard Deviation. stuck in my last code

public int deviasi(){
//sum
int jumlah=0;
for (int i=0; i<banyak; i++){
jumlah = jumlah+nilai[i];
}
//mean
int rata2;
rata2=jumlah/banyak;
//menghitung deviasi
double deviasi = 0;
for (int i=0;i<banyak;i++){
deviasi += Math.pow(nilai[i] - rata2,2);
}
return
Math.sqrt (deviasi/banyak);
}
i got error in my last code. it told me the problem because of different data type between deviasi and banyak. but, i've changed the data type to make them have the same data type. but the error warning still told me the problem because of different data type between deviasi and banyak. i got stuck. T_T
Like mentioned in comments you need to work with double as variable type
public class StandDev {
public double standardDevioation(int[] numbers){
int count = numbers.length;
double sum = 0.0;
for (int i = 0; i < count; i++){
sum += numbers[i];
}
double mean = sum / count;
double sumDiff = 0.0;
for (int i = 0; i< count; i++){
sumDiff += Math.pow(numbers[i] - mean,2);
}
return Math.sqrt (sumDiff/count);
}
public static void main(String[] args) {
int[] numbers = {-5, 1, 8, 7, 2};
StandDev standDev = new StandDev();
System.out.println(standDev.standardDevioation(numbers));
}
}
// Code returns 3.7549966711037173
public class Devs {
public static double deviasi(){
//sum
int jumlah= 0;
int[] nilai = {4,7,6,3,9,12,11,12,12,15};
int banyak = 10;
for (int i=0; i<banyak; i++){
jumlah += nilai[i];
}
//mean
int rata2;
rata2=jumlah/banyak;
//menghitung deviasi
double deviasi = 0;
for (int i=0;i<banyak;i++){
deviasi += Math.pow(nilai[i] - rata2,2);
}
return Math.sqrt (deviasi/banyak);
}
public static void main(String args[]) {
System.out.println(deviasi());
}
}

Incompatible types: double[][] can not be converted to double

I am trying to resolve an issue for this assignment I was given for Homework. I am currently stuck and would appreciate any help that could guide me in correcting the program.
The original assignment is as follows:
Write a program that uses a two-dimensional array to store the highest and lowest temperatures for each month of the year. Write two methods : one to calculate and return the average high and one to calculate and return the average low of the year. Your program should output all the values in the array and then output the average high and the average low.
This is the code I have assembled so far and have an error that I am not able to resolve. It is " incompatible types: converting double[][] cannot be converted to double. The lines in question are Line 8, and Line 110 ( the last return in the program).
import java.util.*;
public class Weather
{
public static void main(String[] args)
{
double[][] tempData = getData();
printTempData(tempData);
double avgHigh = averageHigh(tempData);
double avgLow = averageLow(tempData);
int indexHigh = indexHighTemp(tempData);
int indexLow= indexLowTemp(tempData);
System.out.format("The average high temperature is %4.1f%n", avgHigh);
System.out.format("The average low temperature is %4.1f%n", avgLow);
System.out.format("The index of high temperature is %2d%n", indexHigh);
System.out.format("The index of low temperature is %2d%n", indexLow);
}
private static void printTempData(double[][] tempData)
{
System.out.format("%6s:%4s%4s%4s%4s%4s%4s%4s%4s%4s%4s%4s%4s%n","Month","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
System.out.format("%6s:","Low");
for (int i = 0; i < tempData[0].length;i++)
{
System.out.format("%4.1s", tempData[0][i]);
}
System.out.format("%n");
System.out.format("%6s: ","High");
for (int i = 0; i < tempData[1].length; i++)
{
System.out.format("%4.1f", tempData[1][i]);
}
System.out.format("%n");
}
private static int indexLowTemp(double[][] tempData)
{
int index = 0;
double temp = tempData[0][0];
for (int i = 0; i < tempData[0].length; i++)
{
if (temp > tempData[0][i])
{
temp = tempData[0][i];
index = i;
}
}
return index +1;
}
private static int indexHighTemp(double[][] tempData)
{
int index = 0;
double temp = tempData[1][0];
for(int i = 0; i< tempData[1].length; i++)
{
if ( temp < tempData[1][i])
{
temp = tempData[1][i];
index = i;
}
}
return index + 1;
}
private static double averageHigh(double[][] tempData)
{
double avg = 0.0;
for(int i=0; i < tempData[0].length; i++)
{
avg += tempData[0][i];
}
avg /= tempData[0].length;
return avg;
}
private static double averageLow(double[][] tempData)
{
double avg = 0.0;
for(int i=0; i > tempData[1].length; i++)
{
avg += tempData[0][i];
}
avg /= tempData[0].length;
return avg;
}
private static double getData()
{
double[][] tempData = new double[2][12];
Random r = new Random();
for (int j = 0; j < tempData[0].length; j++)
{
tempData[0][j] = 30 + Math.sqrt(j) - r.nextDouble();
tempData[1][j] = 30 + Math.sqrt(j) + r.nextDouble();
}
return tempData;
}
}
Your method private static double getData() should be private static double[][] getData()
You already declared an array
double[][] tempData = getData();
but you are trying to call
private static double getData()
thus the error "converting double[][] cannot be converted to double."
Hence change to
private static double[][] getData()
The method should be private static double[][] getData()

Arrays, Statistics, and calculating mean, median, mode, average and sqrt

I need to implement four static methods in a class named ArrayStatistics. Each of the four methods will calculate the mean, median, mode, and population standard deviation, respectively, of the values in the array.
This is my first time working with Java, and cannot figure out what should I do next. I was given some test values for, you guessed it, test out my program.
public class ArrayStatistics {
public static void main(String[] args) {
final int[] arr;
int[] testValues = new int[] { 10, 20, 30, 40 };
meanValue = a;
meadianValue = b;
modeValue = c;
sqrtDevValue = d;
average = (sum / count);
System.out.println("Average is " );
}
static double[] mean(int[] data) {
for(int x = 1; x <=counter; x++) {
input = NumScanner.nextInt();
sum = sum + inputNum;
System.out.println();
}
return a;
}
static double[] median(int[] data) {
// ...
}
public double getMedian(double[] numberList) {
int factor = numberList.length - 1;
double[] first = new double[(double) factor / 2];
double[] last = new double[first.length];
double[] middleNumbers = new double[1];
for (int i = 0; i < first.length; i++) {
first[i] = numbersList[i];
}
for (int i = numberList.length; i > last.length; i--) {
last[i] = numbersList[i];
}
for (int i = 0; i <= numberList.length; i++) {
if (numberList[i] != first[i] || numberList[i] != last[i]) middleNumbers[i] = numberList[i];
}
if (numberList.length % 2 == 0) {
double total = middleNumbers[0] + middleNumbers[1];
return total / 2;
} else {
return b;
}
}
static double[] mode(int[] data) {
public double getMode(double[] numberList) {
HashMap<Double,Double> freqs = new HashMap<Double,Double>();
for (double d: numberList) {
Double freq = freqs.get(d);
freqs.put(d, (freq == null ? 1 : freq + 1));
}
double mode = 0;
double maxFreq = 0;
for (Map.Entry<Double,Doubler> entry : freqs.entrySet()) {
double freq = entry.getValue();
if (freq > maxFreq) {
maxFreq = freq;
mode = entry.getKey();
}
}
return c;
}
static double[] sqrt(int[] sqrtDev) {
return d;
}
}
This is pretty easy.
public double mean(ArrayList list) {
double ans=0;
for(int i=0; i<list.size(); i++) {
ans+=list.get(i); }
return ans/list.size()
}
`
Median:
public void median(ArrayList list) {
if(list.size()%==2) return (list.get(list.size()/2)+list.get(list.size()+1))/2;
else return list.get((list.size()/2)+1)
}
For Mode, just a keep a tally on the frequency of each number occurrence, extremely easy.
For standard deviation find the mean and just use the formula given here: https://www.mathsisfun.com/data/standard-deviation-formulas.html

While loop numbers sum

I need help on how to calculate sum of the numbers that while loop prints. I have to get numbers 1 to 100 using while loop and calculate all those together. Like 1+2+3...+98+99+100. I can get numbers but can't calculate them together. Here's my code:
public class Loops {
public static void main(String[] args) throws Exception {
int i = 1;
while (i < 101) {
System.out.print(i);
i = i + 1;
}
}
}
How do I make it only print the last sum? If I try to trick the equation it just hangs.
Use another variable instead of i which is the loop variable:
int i = 1;
int sum = 0;
while (i < 101) {
sum += i;
i++;
}
Now sum will contain the desired output. In the previous version, you didn't really loop on all values of i from 1 to 101.
First either change your sum variable or index variable
public class Loops {
public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i < 101) {
sum = sum + i;
++i;
}
System.out.println(sum);
}
Your sum (i) is also your index. So each time you add to it, you're skipping numbers which you want to add to it.
public class Loops {
public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i < 101) {
//System.out.print(i);
sum = sum + i;
++i;
}
System.out.println(sum);
}
Alternatively, use the Gauss sum: n(n+1)/2
So, the end sum is 100(101)/2 = 5050
Try the following. Moved the values around a bit to ensure that you add up to 100 and always show the sum.
public static void main(String[] args) throws Exception {
int i = 1;
long tot = 1;
while (i < 100) {
i += 1;
tot += i;
System.out.print("Number :" + i + " ,sum="+tot);
}
}
public class Loops {
public static void main(String[] args) throws Exception {
int i = 1;
int sum = 0;
while (i < 101) {
sum = i + 1;
}
System.out.print(sum);
}
}

Issue with Cumulative Sum

Here is an easy one that I am having trouble with. The problem requires me to write a method called fractionSum which accepts an integer parameter and returns a double of the sum of the first n terms.
for instance, if the parameter is 5, the program would add all the fractions of (1+(1/2)+(1/3)+(1/4)+(1/5)). In other words, it's a form of the Riemann sum.
For some reason, the for loop does not accumulate the sum.
Here's the code:
public class Exercise01 {
public static final int UPPER_LIMIT = 5;
public static void main(String[] args) {
System.out.print(fractionSum(UPPER_LIMIT));
}
public static double fractionSum(int n) {
if (n<1) {
throw new IllegalArgumentException("Out of range.");
}
double total = 1;
for (int i = 2; i <= n; i++) {
total += (1/i);
}
return total;
}
}
you need to type cast to double
try this way
public class Exercise01 {
public static final int UPPER_LIMIT = 5;
public static void main(String[] args) {
System.out.print(fractionSum(UPPER_LIMIT));
}
public static double fractionSum(int n) {
if (n<1) {
throw new IllegalArgumentException("Out of range.");
}
double total = 1;
for (int i = 2; i <= n; i++) {
total += (1/(double)i);
}
return total;
}
}
The operation
(1/i)
is working on integers and hence will generate the result in terms of int. Update it to:
(1.0/i)
to get the fractional result and not the int result.

Categories