Is there perhaps a way of finding the above and below average - java

I'm creating a program to find the average of all the numbers entered by the user and storing those numbers to check whether the number entered falls below or above the average that was calculated.
My program outputs all numbers entered as below average. i have check on stack overflow for similar problems i have tried all that but my output still displays below the average only
This is what i have tried
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
//The loop for calculating the average
for (int i = 1; i <= 5; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
double aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <=5; j++)
{
if(aboveAvg > avg)
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
}

This is a possible solution for your problem:
Note that you need to store the user inputs, calculate the average once (not inside the for loop), and finally compare the numbers stored with the average calculated before.
public void newspaper() {
Scanner in = new Scanner(System.in);
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int[] youths = new int[5];
// The loop for calculating the average
for (int i = 0; i < youths.length; i++) {
System.out.println("Youth " + (i + 1) + " How many was delivered?");
youths[i] = in.nextInt();
sum = sum + youths[i];
}
// Note that the average can be calculated once, not every iteration
avg = sum / youths.length;
System.out.println("Average is: " + avg + "\n");
// The loop for checking below of above average
for (int i = 0; i < youths.length; i++) {
if (youths[i] > avg) {
System.out.println("Youth " + (i + 1) + " is above average");
} else {
System.out.println("Youth " + (i + 1) + " below average");
}
}
}

Try to use array instead of variable
see below code
import java.util.Scanner;
public class Stackoverflow {
public void newspaper() {
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int numYouth = 5;
int youth[] = new int[numYouth];
Scanner sc = new Scanner(System.in);
// The loop for calculating the average
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + i + " How many was delivered?");
youth[i] = sc.nextInt();
sum = sum + youth[i];
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
double aboveAvg = 0;
// The loop for checking below of above average
for (int j = 0; j < 5; j++) {
if (youth[j] > avg) {
System.out.println("Youth " + j + " is above average");
} else {
System.out.println("Youth " + j + " below average");
}
}
}
public static void main(String[] args) {
new Stackoverflow().newspaper();
}
}

You need to store the numbers in a temporary list and use counter 'ctr' for incrementing the values of the matched case. I have used for each loop for simplicity.
public void newspaper() {
System.out.println("Question 4 \n");
int youth;
double avg = 0;
int sum = 0;
int numYouth = 5;
List<Integer> number = new ArrayList<>();
// The loop for calculating the average
int ctr = 0;
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + ++ctr + " How many was delivered?");
youth = in.nextInt();
number.add(youth);
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
ctr = 0;
// The loop for checking below of above average
for (int j : number) {
if (j > avg) {
System.out.println("Youth " + ++ctr + " is above average");
} else {
System.out.println("Youth " + ++ctr + " below average");
}
}
}

Assuming that you're trying to 'find the average of all the numbers entered by the user, storing those numbers to check whether each of the numbers entered falls below or above the average that was calculated', below are the things you need to fix:
The "storing those numbers" part
Compare the calculated average against the stored number.
A possible solution:
Use a list or an array to store the numbers entered by the user.
You can use an array as long as you know the number of elements to store before starting to read the numbers.
Read values from the list/array when you want to compare the entered value with the calculated average.
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
// Create a list to store the entered values
// List<Integer> enteredNumbers = new ArrayList<Integer>();
// Using an array of '5' elements - this 5 comes from numYouth
int[] enteredNumbers = new int[numYouth]; // better not to 'hardcode'
//The loop for calculating the average
for (int i = 1; i <= numYouth; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
enteredNumbers[i-1] = youth; // array is 0-indexed
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
// an int is enough to track the number of values above the average
int aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <= numYouth; j++)
{
// compare stored value against the average calculated above
if(enteredNumbers[j-1] > avg) // array is 0-indexed
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
System.out.println(aboveAvg + " Youths are above average");
}

Related

Finding best subarray sum and returning it and the subarray

I am relatively new to Java and to coding as well and am currently trying to solve a subset problem.
The goal is to have the user input the amount of numbers and then input every number up to the amount specified, with the computer asking for every n-th number accordingly.
Afterwards the computer should calculate the sum of all subsets, and return the one closest to pi, as well as the subset in this form [x,y,z] within the same line.
I managed the first part just fine, although it might have been improved with a switch-case for convenience. It adds the input numbers into the array
But I struggle with the second part of this problem, and I have no idea how to progress/arrange the code so that it outputs the desired result. The suggestion I got was that, a for-loop for a set with n elements :
for a from 0 to 2^n
for i from 0 to n
when the binary representation of x on has a 1 at the i-th position
add data[i] to solution.
This should supposedly find all subsets of an array. After that I should add each element, check if the distance from pi decreases and add the element to the solution set. Or at least that is the goal, but my code is not functional as I don't know where to start arranging it. I also don't know what to initialize bestsum with, or how the binary representation algorithm works, or how to add elements to the solution array in order.
Edit : I have made progress, the code below outputs all the subarrays, and it properly calculates the closest sum, but I have no idea how to 'save' the best subarray (subarray with the closest sum) so that I can output it at the end with the sum. I am quite new so I haven't learned about lists or even methods, but this problem in this book at this chapter and I would like to solve it with the suggested method and possibly only simple loops.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers should be read? ");
int count = input.nextInt();
double[] data = new double[count];
double [] solution = new double[count];
double bestsum = 0.0;
for (int i = 0; i < count; i++) {
if ((i + 1) % 10 == 1) {
System.out.println("Enter " + (i + 1) + "st number: ");
data[i] = input.nextDouble();
} else if ((i + 1) % 10 == 2) {
System.out.println("Enter " + (i + 1) + "nd number: ");
data[i] = input.nextDouble();
} else if ((i + 1) % 10 == 3) {
System.out.println("Enter " + (i + 1) + "rd number: ");
data[i] = input.nextDouble();
} else {
System.out.println("Enter " + (i + 1) + "th number: ");
data[i] = input.nextDouble();
}
}
for (int j = 0; j <(1 << count); j++) {
System.out.print("{ ");
double sum = 0.0;
for (int x = 0; x < count; x++) {
if ((j & (1 << x)) > 0) {
System.out.print(data[x] + " ");
sum = sum + data[x];
}
solution[x] = data[x];
}
System.out.println("}");
if (Math.abs(sum - Math.PI) < Math.abs(bestsum - Math.PI)) {
bestsum = sum;
}
}
System.out.println(bestsum);
System.out.println(Arrays.toString(solution));
}
}
Here's my solution to this problem.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers should be read? ");
int count = input.nextInt();
Double data[] = new Double[count];
Double bestsum = 0.0;
List<Double> bestArray= Collections.emptyList();
Set<List<Double>> possibleArrays = new LinkedHashSet<>();
for (int i = 0; i < count; i++) {
if (i == 0) {
System.out.println("Enter " + (i+1) + "st number: ");
data[i] = input.nextDouble();
} else if (i == 1) {
System.out.println("Enter " + (i+1) + "nd number: ");
data[i] = input.nextDouble();
} else if (i == 2) {
System.out.println("Enter " + (i+1) + "rd number: ");
data[i] = input.nextDouble();
} else {
System.out.println("Enter " + (i+1) + "th number: ");
data[i] = input.nextDouble();
}
}
input.close();
for (int i = 0; i < (1<<count); i++)
{
int m = 1; // m is used to check set bit in binary representation.
List<Double> currentArray = new ArrayList<>();
for (int j = 0; j < count; j++)
{
if ((i & m) > 0)
{
currentArray.add(data[j]);
}
m = m << 1;
}
possibleArrays.add(currentArray);
}
Iterator<List<Double>> iterator = possibleArrays.iterator();
iterator.next();
for (int i = 1; i < possibleArrays.size(); i++) {
Double sum=0.0;
List<Double> currentArray = iterator.next();
sum = currentArray.stream().collect(Collectors.summingDouble(Double::doubleValue));
if(Math.abs(sum-Math.PI)<Math.abs(bestsum-Math.PI)) {
bestArray = currentArray;
bestsum = sum;
}
}
System.out.println("possibleArrays: " + possibleArrays);
System.out.println("solution: " + bestArray);
System.out.println("bestsum: " + bestsum);
}

How can I improve this code to object oriented programming?

I would like improve this code to OOP in Java. How can I for example return value from variable avg or Can I put ArrayList in method parameters?
Thank you in advance
class ArrayTester {
private double sum;
public void getAverageNotes() {
List < Integer > theBigList = new ArrayList < Integer > ();
Random theGenerator = new Random();
for (int n = 0; n < 4; n++) {
theBigList.add(theGenerator.nextInt(6) + 1);
}
if (theBigList.size() > 2) {
int max = Collections.max(theBigList);
int min = Collections.min(theBigList);
theBigList.remove(Integer.valueOf(max));
theBigList.remove(Integer.valueOf(min));
System.out.println(theBigList);
for (int n = 0; n < theBigList.size(); n++) {
System.out.println("New note " + n + " of the Informatics is: " + theBigList.get(n));
sum = sum + theBigList.get(n);
}
System.out.println("Collection size is: " + theBigList.size() + "\nExtreme values are: " + min + " and " + max);
double avg = Math.round(sum) / (double) theBigList.size();
System.out.println("Average: " + String.format("%.2f", avg));
} else {
System.out.println("to small");
}
You can return the average by returning the avg once it has been calculated. If there are less than 2 items, it will return -1 as a result.
public double getAverageNotes() {
List<Integer> theBigList = new ArrayList<Integer>();
Random theGenerator = new Random();
for (int n = 0; n < 4; n++) {
theBigList.add(theGenerator.nextInt(6) + 1);
}
if (theBigList.size() > 2) {
double avg = 0;
int max = Collections.max(theBigList);
int min = Collections.min(theBigList);
theBigList.remove(Integer.valueOf(max));
theBigList.remove(Integer.valueOf(min));
System.out.println(theBigList);
int sum = 0;
for (int n = 0; n < theBigList.size(); n++) {
System.out.println("New note " + n + " of the Informatics is: " + theBigList.get(n));
sum = sum + theBigList.get(n);
}
System.out.println("Collection size is: " + theBigList.size() + "\nExtreme values are: " + min + " and " + max);
avg = Math.round(sum) / (double) theBigList.size();
System.out.println("Average: " + String.format("%.2f", avg));
return avg;
} else {
System.out.println("to small");
return -1;
}
}
Alternatively, if you wanted to put the ArrayList as a parameter, you can change the method signature:
public double getAverageNotes(List<Integer> list){
List<Integer> theBigList = list;
...
and define the array list to be passed in:
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Random theGenerator = new Random();
for (int n = 0; n < 4; n++) {
list.add(theGenerator.nextInt(6) + 1);
}
System.out.println(getAverageNotes(list));
}

This program should ask user for the max num to print out to and then calculate each number starting from 1 to the maximum along with it squared

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[]arr1 = new int[max+1];
int[]arr2 = new int[max+1];
int[]arr3 = new int[max+1];
int i = 1;
// For-loop to calculate
for (i = 1;i <= max;i++)
arr1[i] = arr1[i-1] + i;
i = 1;
// While-loop to calculate
while (i <= max) {
arr2[i] = arr2[i-1] + i;
i++;
}
i = 1;
// Do-While-loop to calculate
do
arr3[i] = arr3[i-1] + i;
while (++i <= max);
for (i = 0; i <= max; i++)
System.out.println("Arr1 " + arr1[i] + " Arr2 " + arr2[i] + " Arr3 " + arr3[i]);
System.out.println("Sum of All is " + arr1[max]);
}
I have this for doing sums but I am stuck when it comes to getting it to square
You seem to have 3 identical array objects?
Anyway, it's pretty straightforward to print the square of all numbers from 1 to max:
for (int i = 1; i <= max; i++) {
System.out.println(i + ": " + i * i);
}
There are also some fun ways to sum up the numbers from 1 to max, such as:
System.out.println(IntStream.range(1, max + 1).sum());

Generate Random Number - Put into List - Print List

I have a program that generates a list of numbers and computes all into a total and separates them into three different list. One being all of the numbers, and the other two are even and odd and then prints the even and odd array-list.
or some reason when I try to print out the two list, it only prints the first couple of numbers in the ArrayList giving my no error messages.
My Code:
import java.util.Random;
import java.util.ArrayList;
public class Projects {
public static void main(String [] args) {
Random Generate = new Random ();
ArrayList<Double> List = new ArrayList<>();
ArrayList<Double> Even = new ArrayList<>();
ArrayList<Double> Odd = new ArrayList<>();
double number;
double total = 0;
double totalEven = 0;
double totalOdd = 0;
double averageWhole;
double averageEven;
double averageOdd;
System.out.println("Generating Numbers:");
for (int Repeater = 0; Repeater < 10; Repeater++) {
number = Generate.nextInt(100);
List.add(number);
}
System.out.println("Loaded... " + "Putting Numbers Into List");
System.out.println();
for(int Insert = 0; Insert < 3; Insert++) {
System.out.println("Adding To List...");
}
System.out.println("List Completed!");
System.out.println();
System.out.println();
for (int x = 0; x < List.size(); x++) {
total += List.get(x);
//Complicated Code --- really big for loop try to simplify later.
if (List.get(x) % 2 == 0) {
Even.add(List.get(x));
}
else {
Odd.add(List.get(x));
}
}
System.out.println("Your Total Is: " + total);
System.out.println();
System.out.println();
System.out.println("Even Numbers:" + "\t" + "Odd Numbers");
for (int Output = 0; Output < Even.size() && Output < Odd.size(); Output++)
{
System.out.println(Even.get(Output) + "\t" + "\t" + Odd.get(Output));
}
averageWhole = total / List.size();
System.out.println("Average of All Numbers: " + "Average of All Even Numbers: "+ "Average of all Odd Numbers: " );
for (int averageE = 0; averageE < Even.size(); averageE++) {
totalEven = totalEven + Even.get(averageE);
}
averageEven = totalEven / Even.size();
for (int averageO = 0; averageO < Odd.size(); averageO++) {
totalOdd = totalOdd + Odd.get(averageO);
}
averageOdd = totalOdd / Odd.size();
System.out.print(averageWhole + "\t" + "\t" + "\t" + " " + averageEven + "\t" + "\t" + "\t" + "\t" + " " + averageOdd);
System.out.println();
System.out.println();
System.out.println("Command Complete...");
Sorry for it being so compacted - learning java - 2/3 weeks in -- Thanks!
When you are printing the odd and even numbers the condition in the loop will be met when the shorter list will be done, so the printing stops before printing all the numbers. You separate the printing to two separate loops.
for (int i = 0; i < Even.size(); i++) {
System.out.println(Even.get(i));
}
for (int i = 0; i < Odd.size(); i++) {
System.out.println(Odd.get(i));
}
As a side note, variables in Java should start with lowercase. Even, Odd, Output etc should be even, odd, output.
Another alternative to Guy's code that keeps the same format:
for (int Output = 0; Output < Even.size() || Output < Odd.size(); Output++) {
String even = "-";
if(Output < Even.size()){
even = Even.get(Output).toString();
}//end of if
String odd = "-";
if(Output < Odd.size()){
odd = Odd.get(Output).toString();
}
System.out.println(even + "\t" + "\t" + odd);
}

Combine for and while loop (Java)

I'm new to Java and I'm trying to make a program that allows the user to input 100 numbers and if the user writes '0', then the program is suppose to print the smallest, largest, sum and all the numbers. I got all that to work but not to exit and print it all. My teacher said something about using a while loop, but how is that possible when you have a for loop?
Regards
public static void main(String[] args) {
int[] list = new int[100];
int min = 0;
int max = 0;
int sum = 0;
boolean first = true;
Scanner scan = new Scanner(System.in);
while(list[i] != 0) {
for (int i = 0; i < list.length; i++) {
System.out.print("Enter number (0 to exit) " + (1 + i) + ":");
list[i] = scan.nextInt();
}
for (int i = 0; i < list.length; i++) {
if (first == true) {
min = list[i];
first = false;
}
if (list[i] < min) {
min = list[i];
}
else if (list[i] > max) {
max = list[i];
}
sum = list[i] + sum;
}
if (list[i] == 0) {
System.out.print("Numbers are: " + list[0] + ", ");
for (int i = 1; i < list.length; i++)
System.out.print(list[i] + ", ");
System.out.println();
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + min);
System.out.println("Sum is: " + sum);
}
}
}
}
You only need one while loop to do this and additionally a for loop just to print the array if you want:
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int maxValue = Integer.MIN_VALUE;
int[] history = new int[100];
System.out.println("INPUT:");
int option = scan.nextInt();
while (option != 0 && i <= 100)
{
if (option > maxValue)
maxValue=option;
sum += option;
history[i] = option;
option = scan.nextInt();
i++;
}
System.out.println("OUTPUT: \n" + "SUM: " + sum + "\n MAX VALUE: " + maxValue);
for (int x : history)
System.out.print(x + "");
Here's the body of the method which will do what you've been asked. I have not used a while loop (but in fact, a for-loop is a kind of a while-loop internally).
int size = 100; // Set the number of numbers to input.
int[] list = new int[size]; // Create an array with 'size' elements.
int min = Integer.MAX_VALUE; // Set the highest possible integer as start value.
int max = 0; // Set the minimum to zero, assuming that the user won't input negative numbers.
int sum = 0; // Initialize the sum of the numbers in the list.
Scanner scan = new Scanner(System.in);
for (int i = 0; i < size; i++) { // Run 'size' times the process of inputting a number.
System.out.print("Enter number (0 to exit) " + (i + 1) + ": ");
int number = scan.nextInt();
if (number == 0) { // Quit program if input equals '0'
System.out.println("Exiting...");
break;
}
list[i] = number; // Add the current number to the list
sum += number; // Add the number to the total
if (number < min) { // If the number is smaller than the previous one, set this number as the smallest
min = number;
}
if (number > max) { // If the number is greater than the previous smallest number, set this number as the greatest
max = number;
}
}
// Output all numbers in the list
for (int i = 0; i < list.length; i++) {
if (list[i] != 0) {
System.out.print((i == 0 ? "" : ", ") + list[i]);
}
}
// You see the snippet (i == 0 ? "" : ", ")
// That is a shorthand if-else statement:
// If i equals 0, then "" (empty string), else ", " (comma and space).
// The statement
// System.out.print((i == 0 ? "" : ", ") + list[i])
// is the same as
// if (i == 0) {
// System.out.println("") + list[i];
// }
// else {
// System.out.println(", ") + list[i];
// }
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + max);
System.out.println("Sum is: " + sum);
You have muddled code. Better to use a pattern like this:
while (true) {
// read next
if (input == 0)
break;
}

Categories

Resources