Adding and finding the average in an array - java

I"m trying to make a program that retrieves an endless amount of numbers that user inputs, and then it tells you how many numbers that you inputted, the sum of all the numbers, and then the average of the numbers. Here is the code I have so far. I don't know why it does not work. I get no errors, but it just does not get a valid sum or average.
import javax.swing.*;
public class SumAverage {
public static float sum;
public static float averageCalculator;
public static float average;
public static void main(String[]args) {
float numbers[] = null;
String userInput = JOptionPane.showInputDialog(null, "Ready to begin?");
if(userInput.equalsIgnoreCase("no"))
{
System.exit(0);
}
for(int i = 0; i != -2; i++)
{
numbers = new float[i + 1];
userInput = JOptionPane.showInputDialog(null, "Input any number. Input * to exit");
if(userInput.length() == 0 || userInput.equals("*") || userInput.equals(null))
{
break;
}
else
{
numbers[i] = Float.parseFloat(userInput);
}
}
for (int i = 0; i < numbers.length; i++)
{
sum += numbers[i];
}
average = sum / numbers.length;
JOptionPane.showMessageDialog(null, "The sum of all your numbers is " + sum + ". The average is " + average + ". You entered a total of " + numbers.length + " numbers.");
}
}

The problem is in this line:
numbers = new float[i + 1];
You are creating a new array, but you aren't copying the values from the previous array assigned to numbers into it.
You can fix this in two ways:
copy the values using System.arraycopy() (you'll need to use a new variable to make the call then assign it to numbers)
Don't use arrays! Use a List<Float> instead, which automatically grows in size
In general, arrays are to be avoided, especially for "application logic". Try to always use collections - they have many powerful and convenient methods.
If you wanted to store the numbers for later use, try making your code look like this:
List<Float> numbers = new ArrayList<Float>();
...
numbers.add(Float.parseFloat(userInput));
...
for (float n : numbers) {
sum += n;
}
average = sum / numbers.size(); // Note: Don't even need a count variable
And finally, if you don't need to store the numbers, just keep a running sum and count and avoid any kind of number storage.

Unrelated to the Q, but note also you can compute a running count/average without storing all the input data - or assuming you want to keep the input - without traversing over it each iteration. Pseudocode:
count = 0
sum = 0
while value = getUserInput():
count++
sum += value
print "average:" + (sum / count)

with
numbers = new float[i + 1];
you are creating a whole new array on every iteration. That means you are always creating a new array that will increase its size by 1 on each iteration but only having one field filled with the current user input and having all the other fields been empty.
Delete this line and initialize the array before.
If the size of the array should grow dynamically within the loop
do not use an array at all and use a dynamic data structure like a List or an ArrayList instead.
Further i would suggest to use
while (true) {
//...
}
to realize an infinite loop.

Related

Modification of Bubblesort program with user input

I have created a program previously using the BubbleSort method that works to sort numbers in a list that already exists, however, I am having difficulty with trying to manipulate this program in order to allow a user to input the list of numbers to be sorted instead. So far I have:
import java.util.Scanner;
public class MedianValue {
public static void main(String[] args) {
//use scanner to input list of numbers to sort
Scanner scan = new Scanner(System.in);
int[] numbers = new int[] {scan.nextInt()};
//nested for loop
//outer loop just iterating
//inner loop going through and flipping
//checking if out of order (if statement)
int counter = 0;
//outer loop: keep doing this until it's sorted
for(int i = 0; i < numbers.length - 1; i = i + 1)
//put in a inner loop number.length times minus one because we don't want to swap the last element
for(counter = 0; counter < numbers.length - 1; counter = counter + 1)
{
if (numbers [counter] > numbers [counter + 1])
{
int temporary = numbers [counter];
numbers [counter] = numbers [counter + 1];
numbers [counter + 1] = temporary;
}
}
for(int i =0; i < numbers.length; i = i + 1)
{
System.out.print(numbers[i] + " ");
}
}
}
But, in this program, instead of sorting the inputted numbers, the program simply prints the first number that is inputted by the user. I am not sure if I need to move where my scanner function is placed, or add on to it within the loop for it to sort all of the numbers as I want it to do. I am lost on where to change the program if that is the case.
That's because int[] numbers = new int[] {scan.nextInt()}; is a single assigment. scan read a single input and assign to number[0].
You actually need to modify your code for scan to read n numbers and store in n-sized numbers.
something like.
int[] numbers = new int[scan.nextInt()];
for( int i = 0; i < numbers.length; i++)
numbers[i] = scan.nextInt();
The code int[] numbers = new int[] {scan.nextInt()}; will always create an array (not a List) of size 1.
Usually in these kinds of assignments you get n + 1 numbers, for example 5 3 6 2 4 1 would mean "I'm going to give you five numbers. Oh here they are: 3 6 2 4 and 1!"
You probably want something like int[] numbers = new int[scan.nextInt()]; - then loop from 0 to numbers.length to fill the array.

Print sum of unique values of an integer array in Java

I am yet again stuck at the answer. This program prints the unique values but I am unable to get the sum of those unique values right. Any help is appreciated
public static void main(String args[]){
int sum = 0;
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for (int x : numbers) {
setUniqueNumbers.add(x);
}
for (Integer x : setUniqueNumbers) {
System.out.println(x);
for (int i=0; i<=x; i++){
sum += i;
}
}
System.out.println(sum);
}
This is a great example for making use of the Java 8 language additions:
int sum = Arrays.stream(numbers).distinct().collect(Collectors.summingInt(Integer::intValue));
This line would replace everything in your code starting at the Set declaration until the last line before the System.out.println.
There's no need for this loop
for (int i=0; i<=x; i++){
sum += i;
}
Because you're adding i rather than the actual integers in the set. What's happening here is that you're adding all the numbers from 0 to x to sum. So for 23, you're not increasing sum by 23, instead, you're adding 1+2+3+4+5+....+23 to sum. All you need to do is add x, so the above loop can be omitted and replaced with a simple line of adding x to sum,
sum += x;
This kind of error always occures if one pokes around in low level loops etc.
Best is, to get rid of low level code and use Java 8 APIs:
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sum = Arrays.stream(numbers)
.distinct()
.mapToInt(Integer::intValue)
.sum();
In this way there is barely any space for mistakes.
If you have an int array, the code is even shorter:
int[] intnumbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sumofints = Arrays.stream(intnumbers)
.distinct()
.sum();
So this is my first time commenting anywhere and I just really wanted to share my way of printing out only the unique values in an array without the need of any utilities.
//The following program seeks to process an array to remove all duplicate integers.
//The method prints the array before and after removing any duplicates
public class NoDups
{
//we use a void static void method as I wanted to print out the array without any duplicates. Doing it like this negates the need for any additional code after calling the method
static void printNoDups(int array[])
{ //Below prints out the array before any processing takes place
System.out.println("The array before any processing took place is: ");
System.out.print("{");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
if (i != array.length - 1)
System.out.print(", ");
}
System.out.print("}");
System.out.println("");
//the if and if else statements below checks if the array contains more than 1 value as there can be no duplicates if this is the case
if (array.length==0)
System.out.println("That array has a length of 0.");
else if (array.length==1)
System.out.println("That array only has one value: " + array[0]);
else //This is where the fun begins
{
System.out.println("Processed Array is: ");
System.out.print( "{" + array[0]);//we print out the first value as it will always be printed (no duplicates has occured before it)
for (int i = 1; i < array.length; i++) //This parent for loop increments once the all the checks below are run
{
int check = 0;//this variable tracks the amount of times an value has appeared
for(int h = 0; h < i; h++) //This loop checks the current value for array[i] against all values before it
{
if (array[i] == array[h])
{
++check; //if any values match during this loop, the check value increments
}
}
if (check != 1) //only duplicates can result in a check value other than 1
{
System.out.print(", " + array[i]);
}
}
}
System.out.print("}"); //formatting
System.out.println("");
}
public static void main(String[] args)
{ //I really wanted to be able to request an input from the user but so that they could just copy and paste the whole array in as an input.
//I'm sure this can be done by splitting the input on "," or " " and then using a for loop to add them to the array but I dont want to spend too much time on this as there are still many tasks to get through!
//Will come back and revisit to add this if I remember.
int inpArray[] = {20,100,10,80,70,1,0,-1,2,10,15,300,7,6,2,18,19,21,9,0}; //This is just a test array
printNoDups(inpArray);
}
}
the bug is on the line
sum += i;
it should be
sum += x;

Storing double up value in an Array using for loop?

/*IMO I have completed most of the project, but I can't wrap my mind around part with the array. I am supposed to assign the values to it then have it show on screen, as it is doing now when program get run, but it isn't going through the array. Please help its driving me insane.
Assignment:
For this project, you will create a program that asks the user to enter a positive integer value less than 20. Note that the program will only collect one number from the user. All other numbers will be generated by the program.
If the user enters a number greater than 20, the user should get an error.
If the user enters a number equal to or less than 20, display the double of each value beginning with 1 up to the selected number (multiply each number by 2), then provide the total of all doubles.
For example, if the user entered the number 5, the following should display:
Double up 1 = 2
Double up 2 = 4
Double up 3 = 6
Double up 4 = 8
Double up 5 = 10
Total = 30
Minimum Requirements:
• Create a separate class that contains the following methods. Note: This class should be separate and apart from the public class that holds the main method. 1. A method that will accept two parameters: an integer array and a integer variable. 1. The integer variable should hold the value provided by the user. The array will be used to hold the double up results.
2. This method should perform the calculations, and store the double up results in the array. Additionally, the total of all double up values should be calculated using an accumulator variable that is also a private instance variable.
3. You must make sure the calling method gets the changes to the array. Remember, arrays are passed by reference by default. This method must use a loop.
A separate method that will return (not display) the value stored in the private instance variable called total.
• Create a main method that creates an array and integer variable, as well as an instance of your class. The main method should then use the instance to call each of the methods of the class, passing the data needed and handling any return data. Display the entire contents of the array and total variable.
*/
import java.util.Scanner;
public class project2 {
public static void main(String args[]){
scores output = new scores();
output.enterNum();
output.displayScores();
}
}
class scores
{
int total;
int stats[] = new int[20];
int num1;
void enterNum()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a number between 1 and 20: ");
num1 = input.nextInt();
if(num1<=0 || num1>20)
{
System.out.println("You entered a wrong number. Try again.");
System.out.println("");
enterNum();
}
}
void displayScores()
{
int b=0;
int val2=0;
int total = 0;
val2=num1*2;
for(int i=1;b<val2;i++)
{
System.out.println(b=i*2);
total = total + b;
// this part.
// stats[i] = b;
// System.out.println(stats);
}
System.out.println(total);
}
}
Maljam is right, your for-loop is the issue here.
Your for-loop is messing around with some int b that doesn't need to be there. What you want is to add i*2 to total on each iteration of your loop. Also, you need to modify your for-loop header to check against i instead of b. I'm not really sure what you are trying to do with the array. It's not needed in this project at all.
Try changing it to something like this:
for (int i=1; i<=val1; i++){
//stats[i] = i;
System.out.println("Double up " + i + " = " + 2*i);
total = total + 2*i; //or total += 2*i;
}
System.out.println("Total: " + total);
public class scores {
int total;
int stats[];
int num1;
void enterNum() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number between 1 and 20: ");
num1 = input.nextInt();
if (num1 <= 0 || num1 > 20) {
System.out.println("You entered a wrong number. Try again.");
System.out.println("");
enterNum();
}
}
void displayScores() {
stats = new int[num1];
int total = 0;
for (int i = 0; i < num1; i++) {
stats[i] = (i+1) * 2;
total += stats[i];
}
for (int i = 0; i < num1; i++) {
System.out.println((i+1) + " * 2 = " + stats[i]);
}
System.out.println("Total: " + total);
}
}

Making a method for an array

I have an array that takes student grades from an input. I have to make a method that will find the average of the numbers within the array. Here is the code i have so far...
int mark = Integer.parseInt(input.getText());
if(mark <= 100){
marks.add(Integer.parseInt(input.getText()));
input.setText("");
warningLbl.setText("");
}
else{
warningLbl.setText("Please enter an number between 0-100");
}
I want to take the contents in the array 'marks' and get an average for them then append it in my text area
public static double getAverage(int[] marks)
{
int sum = 0;
for(int i : marks) sum += i;
return ((double) sum)/marks.length;
}
This is the method i have to find the average, but i dont know how to use this method and get it to print in a text area
If you want to find the average stored in an array , try the following function.
public static double average(int[] marks)
{
int sum = 0;
double average;
for(int element: marks)
{
sum = sum + element;
}
average = (double)sum / marks.length;
return average;
}
Hope it helps ! :)
The above method is used to find average in an array(primitive type) , but to find average in List type array(wrapper class) , we have to iterate through each element in the list by this way and do the required calculations :
public static String average(Integer[] marks)
{
int sum = 0;
double average;
for (int i = 0; i < marks.size(); i++)
{
sum = sum + marks.get(i);
}
average = (double) sum / marks.size();
String averageString = Double.toString(average);
return averageString;
}
This returns your average in string type directly.
There are several problems with your current code.
Using input.getText(); twice will mean it's going to prompt for input twice. Have a single line like int mark = Integer.parseInt(input.getText()); then use the mark variable wherever it's needed.
In order to test if the number is between 0 and 100 (I'm assuming this needs to be inclusive), that if statement would need to be (mark >= 0 && mark <= 100).
I assume you want to get multiple students' grades/marks, so it may be a good idea to enclose your code in a for or while loop, depending on how you want it to operate. However, since this will be of variable length I'd recommend using a List over an array for resizing.
Finding the average is easy. Just use a foreach loop to sum up all the numbers, then divide that by the array length.

Counting number of index in array using for loop

So I have an array from 0-4, that has 5 random integer values (ie 10,20,25,15,50). The program ask the user to enter an integer, lets say user enter 17. The program will check and with the 5 values from the array i have and print out numbers that are larger than what the user put in, in this case which is 17(I use a for loop to do this). I also want to print out the number of numbers that are larger than what the user enter, in this case 2 (numbers that are larger than 17). How do i do this? Do i write a for loop inside the first for loop?
int[] myArrays = new int[10,20,25,15,50];
int numEntered;
for (i = 0; i < myArrays.length; i++)
{
if (myArrays[i] > numEntered)
System.out.println(myArrays[i]);
}
Now how can I get the total numbers that are larger than what the user had input?
Just have a running total counter.
int counter = 0;
Then whenever you find a number that's larger than what the user had input, increment the counter using counter++;. Then after your for loop just print out the counter's value.
That should be enough information for you to solve the homework, without revealing too much.
You're on the right track; basically, the problem boils down to these items:
Looping through your array
Recording items greater than your specified value
Summing all items encountered greater than your specified value.
You can accomplish this all with a single loop of your array.
Why not just have an integer that you increment everytime you find a value greater than the user input?
int count=0;
for(int i=0; i<4; i++) {
if(myArrays[i] > numEntered) {
count++;
System.out.println(myArrays[i]);
}
}
System.out.println("found " + count + " values greater than " + numEntered);
Is a second for loop required? why? I'd do it like so..
//Take in the number to test.
public void islarger(int num){
int counter = 0;
int numbers[] = new int[5];
//loop through array
for(int x=0; x < array.length; ++x){
if(array[x] > num){
//If it meets the condition add it to the new array
numbers[y] = array[x];
++y;
}
}
//print our results.
System.out.println("There are " + counter " numbers larger than " + num + \n "They are...");
Arrays.toString(numbers);
}

Categories

Resources