Taking the average of an Array - java

I'm trying to put together a java program to do the following:
Prompt for and read in a number of integers to read
Create an array that can hold that many integers
Use a loop to read in integer values to fill the array
Calculate the average value in the array (as an integer)
This is what I have so far (although I'm pretty sure this is wrong):
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
//I don't know if I should use a while loop here or what the arguments should be
}
What should the conditions be, in order to set up the loop?

Let's look at what you need to calculate an average and what you have right now.
What you need
The total number of values
The values
Somewhere to keep the sum of values
What you have
The total number of values
A source from which to get new values
Now, from your code, you don't seem to have a place to add all your numbers. That's easy to fix; you know how to declare a new variable.
You also don't have the values, but you do have somewhere you can get them from. Since you also know how many numbers you need to sum up, you can use a loop to get that many numbers from your source.
All in all, you'll want your loop to run f times. In that loop, you'll want to get new a new number and add it to the rest. At the end, you should be able to derive the average from all that.

The better idea would be to prompt the user to enter all of the values at once, separated by spaces. IE
2 4 1 1 6 4 2 1
You can then call the split() function for Strings to split this into an array of Strings, then use the Integer.parseInt() function to turn this array of Strings into an array of ints.
Once you have your array of ints, it's a simple for loop to add all of the values together and divide by that array's length.

You can put a while loop or a for loop to input the numbers. Along with the input, keep taking the sum of the numbers. Since you have total number of values:
Average= (sum of numbers)/ total numbers.
I will write pseudo code so that it will force you to search more:
//Pseudo code starts after your array declaration
for loop from 0 to f
store it in values Array
save sum of numbers: sum= sum+values[i]
loop ends
calculate Average

public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
double avg = 0;
for (int i = 0; i < f; i++)
{
value[i] = keyboard.nextInt();
avg += value[i];
}
avg /= f;
System.out.println("Average is " + avg);
}
I dont see a point of having array value. Or do you want some other kind of average ?

I wrote(with a friend) a code that calculates the average number:
package dingen;
import java.util.Scanner;
public class Gemiddelde {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
float maxCount = 0;
float avgCount = 0;
System.out.println("How many numbers do you want");
int n = sc.nextInt();
for(int i = 0; i < n; i++) {
System.out.println("Number: ");
float number = sc.nextInt();
maxCount = maxCount + number;
}
avgCount = maxCount / n;
System.out.println("maxCount = " + maxCount);
System.out.println("avgCount = " + avgCount);
}
}
the only thing you have to do is replace your class and package.
you wil get the message: How many numbers do you want?:
and then it wil ask you the amount of numbers you inserted.
example:
How many numbers do you want?:6
Number:6
Number:7
Number:8
Number:9
Number:93
Number:94
maxCount = 217.0
avgCount = 36.166668
I have hoped I helped you with your problem :)

Related

how to define a array's length when we do not know the actural size in Java

Question: an unknown number of quiz scores from the stdin and print out the total number of quiz scores, its average, and population standard deviation with 2 decimal places.
My code is :
import java.util.Scanner;
public class Ex4_2 {
public static void main(String args[]) {
int n = 0;
Scanner input = new Scanner(System.in);
double sum = 0;
int[] scores = new int [n];
for(int i = 0; i<scores.length; i++)
{
scores[i] =input.nextInt();
sum = sum + scores[i];
}
int num = scores.length;
System.out.printf("Total number of quiz scores = %1.2f \n ", num);
System.out.printf("Average = %1.2f \n", sum/num);
double total = 0;
for(int i=0;i<scores.length;i++)
{
total += (scores[i]-(sum/num))*(scores[i]-(sum/num));
}
double SD = Math.sqrt(total/num);
System.out.printf("Standard deviation = %1.2f \n ",SD);
}
}
But when I input 10 20 30, it cannot calculate the right output and there is an error.
I cannot understand the meaning of this error and do not what is mistake.
Please help me... Thank you very much!
Following are the output and errors.
Total number of quiz scores =
Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.Integer
at java.base/java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4426)
at java.base/java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2951)
at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:2898)
at java.base/java.util.Formatter.format(Formatter.java:2673)
at java.base/java.io.PrintStream.format(PrintStream.java:1053)
at java.base/java.io.PrintStream.printf(PrintStream.java:949)
at Ex4_2.main(Ex4_2.java:16)
I assume your real question is 'how do I fix my error?'.
The problem is this line (line 16), as the error message tells you.
System.out.printf("Total number of quiz scores = %1.2f \n ", num);
Your error is nothing to do with array sizes.
You are using a format specifier for a floating-point value %f with an integer value num. Use %d for an integer. That's all.
You can't calculate the size of the array if you don't know how many items it will hold. So you need to:
Initialized it to some arbitrary length, say 10 and set the count to 0.
Every time you add a value, increment count and compare it to the size of the array.
if the array is full, copy the contents with a new length using the Arrays.copyOf method in the Arrays class.
when you are done entering in values, you can either leave the array alone or trim it to the number of items using the method mentioned above.
Or better
You can use an ArrayList which does all of the above (and much more) for you.
In such case you must try using List. Array list must work in your case.
Please refer :
https://www.javatpoint.com/java-list
Here is how you do it.
https://replit.com/#TheCodingBros/Java#main.java
First Input no of quiz candidates, then give each candidate marks.
Then it will show u sum total, mean and standard deviation.
All the above answers are correct. Please read and understand.
Additionally,
int n = 0;
int[] scores = new int [n];
Your loop will always fail because you are instantiating your scores array with 0.
In case if you want a fixed size then for eg. int[] scores = new int [10];
Or as per other answer use arraylist for dynamic sizing.

How do you count the amount of numbers when the input is given separated by spaces, ended with a letter?

I'm quite new to java.
I'm trying out some things for a project but I don't get why this does not work.
The goal here is to let the user input numbers separated by spaces and end with a letter. The program then needs to count the even and odd indexed numbers and output which sum is larger.
I already made this successfully when the amount of numbers given was a constant, but now I want to make it adapt to the user input.
Because I want to put the numbers in an array I need to know the length of this array. To get this I want to count the amount of numbers the user puts in so I can create the appropriate length array.
For some reason the while loop does not end and keeps running. How do I count the amount of numbers put in?
EDIT
I've added in.next(); in the first while loop so it is not stuck at the first input element. This brings me to a further problem however of having two while loops trying to loop through the same input. I have tried to create a second scanner and resetting the first one, but it does not get the second loop to start at the first element. Previous answers show that this is not possible, is there a way to put this in one while loop while still using arrays to store the values?
P.S. The input values should be able to be any positive or negative integer.
Here is my complete code:
import java.util.Scanner;
public class LargerArraySum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int length = 0;
System.out.println("Enter your numbers seperated by spaces, end with a letter");
while(in.hasNextInt()) {
length++;
in.next();
}
System.out.println(length);
int arra[] = new int[length];
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
int evenSum = EvenArraySum(arra);
int oddSum = OddArraySum(arra);
if(evenSum<oddSum) {
System.out.println("The sum of the odd indexed elements is bigger");
} else if(oddSum<evenSum) {
System.out.println("The sum of the even indexed elements is bigger");
} else {
System.out.println("The sum of the odd and even indexed elements is equal");
}
}
public static int EvenArraySum(int[] a) {
int sum = 0;
for(int i=1;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the even indexed elements is: " + sum);
return sum;
}
public static int OddArraySum(int[] a) {
int sum = 0;
for(int i=0;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the odd indexed elements is: " + sum);
return sum;
}
}
add in.next(); in the loop. Actually you don't need array. You can sum even and odd indexed numbers while reading without saving them.
1) Your first while-loop does not work because the iterator is always checking for further numbers in from the same position.
Example:
Position 0 1 2 3 4 5
Value 1 3 5 7 9 0
At start the iterator points to position 0. If you call hasNextInt() it will check if position 1 is available, in this case it will be true. At this moment the interator still points to position 0. So you increase your length and do the same thing again, so you have an infinite loop.
To move the iterator to the next position you need to call nextInt().
2) You can't iterate over the same Scanner with a second while-loop in that way. If you would correct you first while-loop the iterator would point to position 5 (it reached the end of the scanner). So the check for hasNextInt() will be false and the second while-loop will not be entered.
3) The comments already mentioned it, you could use an ArrayList for this use case like so:
final ArrayList<Integer> input = new ArrayList<>();
while ( in.hasNextInt() ) {
input.add( in.nextInt() );
}
System.out.println( input.size() );
( or like kitxuli mentioned in his answer, dont even store the values, just count them in the first while-loop)
Your code has 2 major problems . The first and the second while loops lets take a look at your first loop .
while(in.hasNextInt()) {
length++;
}
your condition in.hasNextInt() made you insert input because no variable was initialized with in.nextInt but also returns either [true] or [false] so as long as its true it will add to the length variable without prompting you to insert a [new input] .so the code should look like.
Int length = 0;
int k ;
while(in.hasNextInt()) {
length++ ;
k = in.nextInt();
}
you insert the input into an initialized variable k for ex then prompt the user to further input into k after adding to [length] then the loop will check your condition without prompting user for input.
Lets look at your second while loop.
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
In in.NextInt() you are prompting the user to enter new input once again so you don't need int x.Not even the while loop .However you MUST declare a new scanner in this ex: I call it c .The code should look like this.
int [] a = new int [length];
Scanner c = new Scanner (System.in);
for(int i=0;i<length;i++) {
if (c.hasNextInt()){
a[i] = c.nextInt();
} else
break;
}
You must add the if statement because if you get an alphabet in the int array you will get an exception error .The array a[i] will not prompt the user.
Of course it isn't practical to make the user enter the values twice so a better code to implement without using ArrayList class which I think you may not know very well is by using an empty String .
NEW CODE :-
String g = "";
String j ="";
int y ;
int q=0;
int w = 0;
while (in.hasNextInt())
{
y = in.nextInt();
g =g+y+",";
q++;
}
int arra [] = new int [q];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(',')){
arra[w]=Integer.parseInt(j);
System.out.println(arra[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
Another even better code :-You just insert your numbers separated by spaces without a letter ,hit enter and the array is filled.
Scanner in = new Scanner (System.in);
String g = "";
String j ="";
int y ;
int q=0;
int i=0;
int w = 0;
System.out.println("inset your input separated by spaces");
g = in.nextLine();
while(i<g.length()){
if((g.charAt(i))==(' ')){
q++;
}
i++;
}
int a [] = new int [q+1];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(' ')){
a[w]=Integer.parseInt(j);
System.out.println(a[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
a[w]=Integer.parseInt(j);
System.out.println(a[w]);

Printing random number values to an Array

Im a bit confused on how to do this particular process in Java.
I have to use a RNG to print a specific amount of values to an array, but the part I can't figure out is how to give each array element a value that is to be incremented if the RNG gives that value. Example:
Array
0
1
2
If the RNG returns a 2, then increment the 2 in the array, and then display it like this
0
1
2 1 (as in, it rolled a 2 once so its now 1)
I have no problems doing the user input and RNG part, but I don't know how to display it like that
Any help would be appreciated, thanks.
Code so far
public static void main(String[] args) {
Scanner input = new Scanner( System.in); //Declares the scanner
Random randomNumbers = new Random(); // Declares the random property you will need later
//Variables
int randomrequest = 0; //Declares randomnum as a integer with a value of 0, this is what the user inputs as the number they want.
int randomrange = 0; //Declares the number for the number range for the random number generator
int randomcounter = 0;//Declares the counter you will need later as 0
int result = 0; //This variable is for the random number generation result
System.out.printf( "How many random numbers do you want to generate?" ); //asks for the number to generate
randomrequest = input.nextInt(); //Makes the user enter a value to and then stores it in this variable.
System.out.printf( "What is the number of values for each random draw?" ); //asks for the number range
randomrange = input.nextInt(); //See above
//Ok now we have to use the inputed information to do the rest of the processing before we can display it
//First, create the array and give it the size equal to the number range entered
int[] array = new int[ randomrange ]; // Declares the array with the amount of slots for each outcome
//We need to use a loop here to make sure it rolls the RNG enough times
while (randomcounter != randomrequest) { //This tells it generate a random number until the counter equals the entered amount.
result = randomNumbers.nextInt( randomrange ); //Generates a random number within the range given
randomcounter += 1; //increments the counter, so that it will eventually equal the entered number, and stop.
}//End of do while
}//end of Public static void
}//End of entire class
The following code should work for your solution:
while (randomcounter != randomrequest) {
result = randomNumbers.nextInt(randomrange);
array[result] += 1;
randomcounter +=1;
for (int i = 0; i < array.length; i++)
{
system.out.print(array[i] + " ");
}
system.out.println();
}
If I'm interpreting your question correctly, one thing you can try is to have each element in the array be a counter for its index. So if your random number generator produces a 2, you increment the value in array[2].
A concise way to put it might be:
while (randomCounter++ != randomRequest) {
array[randomNumbers.nextInt(randomRange)]++;
}

Fill an array with doubles from scanner in Java

Im looking to fill an array with doubles from the user using Scanner. However, I am having difficulties because of Java's inability to alter array size. I need to get around this somehow. My idea for getting around this was to first have the user enter how many doubles he will be putting into the array.
System.out.print("How many numbers would you like to put in the array?: ");
int num = in.nextInt();
while(num >= 0) {
double[] array[] = new double[num][];
System.out.println("Enter the " + num + " numbers now.");
}
This is what I have so far but it is clear that it will not function as intended.
You need to:
Decrement num or option (3)
Initialize your array outside the loop
Start saving numbers from array position 0
Here is how that would be done:
System.out.print("How many numbers would you like to put in the array?: ");
int num = in.nextInt();
int position = 0;
double[] array = new double[num];
while(position < num) {
System.out.println("Enter the " + num + " numbers now.");
array[position++] = in.nextDouble();
}
As you already know how many numbers the user will provide, Consider Using an ArrayList
ArrayList<Double> list = new ArrayList<Double>();
for(int i = 0;i< num;i++){
//Ask for a value
//add that value to the list
}
Using a simple for loop, you can ask each value, an add it to the list.

Counting the least occurring in an array of 10 user input integers

LeastFrequent - Output the integer which occurs least frequently along with its occurrence count from a list of 10 integers input from System.in. If multiple integers in the list occur least frequently, output any integer that occurs least frequently. Name your class LeastFrequent. You can assume that all 10 integers are in the range -100 to 100 inclusive.
import java.util.*;
public class LeastFrequent
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arr = new int[10];
int[] hold = new int[300];
int x = 0;
int count = 0;
int a = 1;
int least = 0;
System.out.print("numbers: ");
//adds 10 numbers to an array and counts occurrence
for(int i=0;i<arr.length;i++)
{
arr[i] = scan.nextInt();
hold[arr[i]]++;
}
for(int i=0;i<hold.length;i++)
{
if(hold[i] > 0)
{
}
}
System.out.println("least frequent: " + count + " occurs " + arr[count] + " times");
}
}
I have it asking the user for 10 integers and putting it into the array.
I also have it counting the occurrence of the input numbers and storing it in another array.
I am stuck on finding the least frequent one.
I know i need to scan through the second array again bu i dont know how.
Any thoughts on how to compare the element's values of the second array while skipping the values that equal 0?
Firstly, the following isn't quite correct:
hold[arr[i]]++
What would happen if I input -1?
As to finding the least occurring element, you need to find the smallest value in hold that's greater than zero. As you iterate over hold, you could keep track of the smallest such value seen so far as well as its index.
Finally, an alternative approach to the problem is to sort the array. Once you do this, equal values are brought next to each other. This simplifies counting the repetitions.

Categories