I'm trying to write a simple program which will take a number of inputs from the user and produce the max number (Highest number) min number (Lowest Number) and the average.
So far I have written the code but found that the second and third while loops were being ignored. I tested this by outputting println's. I'm new to Java but any help is appreciated :)
public void analyseInput() {
UI.clearText();
UI.print("input (end with 'done')");
double sum = 0;
double i=0;
for( i=0; UI.hasNextDouble(); i++){ //average
double amt = UI.nextDouble();
sum = (sum + amt);
}
UI.println("test0");
int maxAge = 0;
while(UI.hasNextDouble()){ //max
int age = UI.nextInt();
while(age>maxAge){
maxAge = age;
UI.println(maxAge);
}
}
double minAge = 0;
while(UI.hasNextDouble()){ //min
double age = UI.nextDouble();
if(age<minAge){
minAge = age;
}
}
double average = sum/i;
UI.nextLine(); // to clear out the input
UI.println(average);
UI.println(minAge);
}
Take out your for loop.
using it empties ui.doubles.
furthermore instead of iterating through your stack twice you might as well do the max, min and average calculations in one loop. also your max and finder isn't right, because it would only work on a sorted list and if the list was already sorted you would just look at either end of it.
If you need the min age, max age, average for a set of data, instead of parsing over it a bunch of time, you can simply do it in one go.
public void analyseInput() {
UI.clearText();
UI.print("input (end with 'done')");
double sum = 0;
double i=0;
double maxAge = Double.MIN_VALUE, minAge = Double.MAX_VALUE;
for( i=0; UI.hasNextDouble(); i++){ //average
double amt = UI.nextDouble();
sum = (sum + amt);
maxAge = Math.max(amt, maxAge);
minAge = Math.min(amt, minAge);
}
double average = sum/i;
UI.nextLine(); // to clear out the input
UI.println(average);
UI.println(minAge);
}
You must to do all operations (max, min, avg) inside a single while-loop and initialize your variable right. To each new double value, update the min and max variable. Add to an accumulator all the values and calculate the average after the loop.
Related
Instructions;
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the max and average. A negative integer ends the input and is not included in the statistics. Assume the input contains at least one non-negative integer.
Output the average with two digits after the decimal point followed by a newline, which can be achieved as follows:
System.out.printf("%.2f\n", average);
Ex: When the input is:
15 20 0 3 -1
the output is:
20 9.50
I have tried a few different ways to convert the int avg into a string but somehow keep messing up.. What am I not doing?? Example code below
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int num = 0;
int count = 0;
int max = 0;
int total = 0;
int avg = 0;
String s=Integer.toString(avg);
do {
total += num;
num = scnr.nextInt();
count = ++count;
if (num >= max) {
max = num;
}
} while (num >= 0);
avg = total/(count-1);
System.out.printf("%.2f\n", avg);
}
}
What you are trying to do is almost correct. The only things, you would need to change for this to work are these:
int avg = 0; // The type of avg should be a float
The reason for this is that what you're printing is a float but before these changes, you are providing it with an int.
// The number you are providing avg with should be cast to a float value
avg = total/(count-1);
This is because if you didn't, you would have integer division.
// It would look like this
float avg = 0;
avg = (float)total/(count-1);
Hello i am trying to make a method to generate a random number within a range
where it can take a Bias that will make the number more likely to be higher/lower depending on the bias.
To do this currently i was using this
public int randIntWeightedLow(int max, int min, int rolls){
int rValue = 100;
for (int i = 0; i < rolls ; i++) {
int rand = randInt(min, max);
if (rand < rValue ){
rValue = rand;
}
}
return rValue;
}
This works okay by giving me a number in the range and the more rolls i add the likely the number will be low. However the problem i am running in to is that the there is a big difference between having 3 rolls and 4 rolls.
I am loking to have somthing like
public void randomIntWithBias(int min, int max, float bias){
}
Where giving a negative bias would make the number be low more often and
a positive bias make the number be higher more often but still keeping the number in the random of the min and max.
Currently to generate a random number i am using
public int randInt(final int n1, final int n2) {
if (n1 == n2) {
return n1;
}
final int min = n1 > n2 ? n2 : n1;
final int max = n1 > n2 ? n1 : n2;
return rand.nextInt(max - min + 1) + min;
}
I am new to java and coding in general so any help would be greatly appreciated.
Ok, here is quick sketch how it could be done.
First, I propose to use Apache commons java library, it has sampling for integers
with different probabilities already implemented. We need Enumerated Integer Distribution.
Second, two parameters to make distribution look linear, p0 and delta.
For kth value relative probability would be p0 + k*delta. For delta positive
larger numbers will be more probable, for delta negative smaller numbers will be
more probable, delta=0 equal to uniform sampling.
Code (my Java is rusty, please bear with me)
import org.apache.commons.math3.distribution.EnumeratedIntegerDistribution;
public int randomIntWithBias(int min, int max, double p0, double delta){
if (p0 < 0.0)
throw new Exception("Negative initial probability");
int N = max - min + 1; // total number of items to sample
double[] p = new double[N]; // probabilities
int[] items = new int[N]; // items
double sum = 0.0; // total probabilities summed
for(int k = 0; k != N; ++k) { // fill arrays
p[k] = p0 + k*delta;
sum += p[k];
items[k] = min + k;
}
if (delta < 0.0) { // when delta negative we could get negative probabilities
if (p[N-1] < 0.0) // check only last probability
throw new Exception("Negative probability");
}
for(int k = 0; k != N; ++k) { // Normalize probabilities
p[k] /= sum;
}
EnumeratedIntegerDistribution rng = new EnumeratedIntegerDistribution(items, p);
return rng.sample();
}
That's the gist of the idea, code could be (and should be) optimized and cleaned.
UPDATE
Of course, instead of linear bias function you could put in, say, quadratic one.
General quadratic function has three parameters - pass them on, fill in a similar way array of probabilities, normalize, sample
import java.util.Scanner;
class objectDetails {
double w, t, res, amt;
String ob;
void getDetails(int n) {
Scanner get = new Scanner(System.in);
int limit = n;
System.out.println("Enter Object Details\n");
for (int i = 0; i < limit; i++) {
System.out.println("Name of appliance:\n");
ob = get.next();
System.out.println("Enter the amount of watts per hour:\n");
w = get.nextDouble();
System.out.println("Enter the amount of time in hours used:\n");
t = get.nextDouble();
res = (w * t) / 1000;
amt = (res * 4.2);
System.out.println("The amount in ruppes payable=" + amt);
}
}
}
i want the sum of amt from all the iterations in the loop. Add all the amt and display the total amount payable. im new to coding trying to self learn. thank you
Before the loop,
double total = 0;
and then in the loop (after you calculate the amount)
total += amt;
and finally after the loop, something like
System.out.printf("The total is %.2f%n", total);
Assign one global variable and store the value in that variable and at last print the value of that global variable.
thats all
I am trying to calculate and return the average of an array of integer values. The problem is, the array I am calculating the average from has values I need to find the average of, and values I need to exclude.
For example, take this as being my data set in the array.
20, -999, -10, 50, -999, 40, 30
I need to find the average but exclude any -999 value from the calculation.
How can I go about removing the -999 value from my sums and then find the new value to divide by at the end? Is there a way to keep count of the values I exclude? How can I exclude a value and move on to the next?
public static double averageTemperature(int[] temperatures)
{
double sum = 0.0;
double avg = 0.0;
for (int i =0; i < temperatures.length; i++)
{
if (i == -999)
{
// what technique is there to exlude and keep counting?
}
else
{
sum += i;
}
}
avg = sum / temperatures.length;
return avg;
}
This should be pretty straightforward - just use a variable as counter for the "valid" entries. You also need to access the values in the array properly. Here's a proposal (untested), which assumes "valid" entries are those not equal t0 -999 (modify the condition as you like):
public static double averageTemperature(int[] temperatures)
{
double sum = 0.0;
double avg = 0.0;
int validEntries = 0;
for (int i =0; i < temperatures.length; i++)
{
// process only "valid" entries
if (temperatures[i] != -999)
{
sum += temperatures[i];
++validEntries;
}
}
avg = sum / validEntries;
return avg;
}
Using Java 8 you can do;
temperatures = Arrays.stream(temperatures).filter(x -> x != -999).toArray();
You can exclude any array value this way using predicate statements.
Calculating the mean is as simple as just looping the array and dividing by the length then.
float mean;
for (int i = 0; i < temperatures.length; ++i) {
mean += (float) temperatures[i];
}
mean /= (float) temperatures.length;
Note to use a float for the mean and cast your integer array values to float also to avoid integer division, as well as the length of the array.
suppose you are correct with the logic but you are not getting the sum of the temperature values.
public static double averageTemperature(int[] temperatures)
{
double sum = 0.0;
double avg = 0.0;
for (int i =0; i < temperatures.length; i++)
{
if (temperatures[i] == -999)
{
continue;
}
else
{
sum += temperatures[i];
}
}
avg = sum / temperatures.length;
return avg;
}
hope this is what you are looking for.
The easiest way to compute the average while filtering out any unwanted values would be:
double average = Arrays.stream(temperatures)
.filter(i -> i != -999)
.average();
I have a program where the user inputs marks into the array and then gets the average value
This is using Jcreator
My problem is that when I ask for the average on my program,it says that the average is 1
This is my code :
//averageEnglish
public void averageEnglish()
{
System.out.println("The Average Mark Of English Is");
int averageEnglish = english.length / 10;
System.out.println("-----------");
System.out.println(averageEnglish);
System.out.println("-----------");
}//End of averageEnglish
English is an int array
int[] english = new int [10];
averageEnglish is a variable
int averageEnglish;
10/10 equals 1. pretty normal.
what you need to do is get the sum of all elements, and divide them by the length of the array.
also: the IDE you use is not really relevant
english.length/10 is not the average value of the array, its simply the length (10) of the array divided by 10, which is 1. You need to sum up all values of the array and divide the sum by the length of the array.
Often you want to present the result not only as an integer but with a few decimals, store the sum and average result in a double.
double sum = 0;
for (int i = 0; i < english.length; i++) {
sum += english[i];
}
double average = sum / english.length;
You are dividing the array's length by the constant 10 (which just happens to be the length), so naturally you'd get 1. You should sum all values of the array and only then divide them by its length:
double englighSum = 0;
for (int i = 0; i < english.length; ++i)
englishSum += english[i];
}
double englishAverage = englishSum / english.length;
If you want user to fill the array, you need to use Scanner object.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of grades: ");
int n = scanner.nextInt();
double[] english = new double[n];
for(int i=0; i<n; i++)
{
System.out.println("Please enter the grade for grade " + (i+1) + ":");
english[i] = scanner.nextDouble();
}
scanner.close();
Than you may use Markus Johnsson's code to proceed.
You anticipated the size of the array and assumed it is always 10 which is the first mistake, then you did your division based on the number of array elements not their sum:
int[] english = new int[10];
/* Now we assume you did some stuff here to fill the array. */
//averageEnglish
public void averageEnglish()
{
System.out.println("The Average Mark Of English Is");
int noOfElements = english.length; // The divisor
int sum = 0; // The dividend
for (int i = 0; i < noOfElements; i++)
{
sum += english[i];
}
// Here is your Average (Should be of type double since there will be floating points)
double averageEnglish = sum / noOfElements;
System.out.println("-----------");
System.out.println(averageEnglish);
System.out.println("-----------");
}//End of averageEnglish
The value of english.lenght is always 10. As in this example:
int[] english = new int [10];
It doesn't matter what data the english array holds, its lenght is always 10.
In order to do the proper calculation use the data, not the lenght of the array.