I am trying to find the average of an array of numbers, whose value is taken from a JTextfield. My problem is that zero is counted in with the average. How is it possible to find the average but not include zero.
int[] numbers = new int[]{Integer.parseInt(math1.getText()),0 };
int sum =0;
if(numbers != 0){
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
//calculate average value
int average = sum / numbers.length;
totdata2.setText(Integer.toString(average));
}
Don't count the numbers whose values are zero in the denominator when calculating the average:
int tally = 0;
for ( int i = 0; i < numbers.length; i++ ){
if (numbers[i] != 0 ){
sum = sum + numbers[i];
tally++;
}
}
int average = sum / tally;
I am not sure what you are trying to accomplish with the following syntax:
if(numbers != 0)
int[] numbers // numbers is an array.
You cannot do if(numbers != 0).
Inside the for loop you should check that the actual integer number is not zero.
int counter=0; // counts not zero elements
for(int i=0; i < numbers.length ; i++)
if(numbers[i]!=0){
sum = sum + numbers[i]; // numbers[i] is an int (a number)
counter ++;
}
Second: You should not do this:
int average = sum / numbers.length;
In the above code you are counting the zeros you are dividing for the arrays original length.
You should keep a counter of elements not zero and divide by that counter.
Check the updated code above.
It should be:
int average = sum / counter;
I think it will work
int countOfZero = 0 ;
for(int i=0; i < numbers.length ; i++)
{
sum = sum + numbers[i];
if(numbers[i]==0)
{
countOfZero++;
}
}
int average = sum / (numbers.length-countOfZero);
Related
So a jist of what the program needs to do is to count how many integers are greater than the average of the sum of all elements in an array. It does this as the last number it counts is the total number of integers greater than average. However, it also shows the number of times it has looped. For example, if the number of integers is supposed to be 3, it will show, 1,2,3. That's fine but the 1,2, the part is not necessary, just the 3. This is the only way I have found possible but is there a better way?
import java.util.Scanner;
public class Sparky
{
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
int sum =0;
int n;
do
{
System.out.print("Enter integer n, greater than 0: ");
n = kbd.nextInt();
}while(n < 1);
System.out.println();
int[] arr = new int[n];
System.out.println("Array on one line: ");
for(int i = 0; i < arr.length; i++)
{
arr[i] = (int) (Math.random() * 500) + 1;
System.out.print(arr[i] + " ");
}
int max = arr[0];
for(int i = 1; i < arr.length; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
System.out.println();
{
double x = 0;
double y;
for(int i = 0; i < arr.length; i ++){
x = arr[i] + x;
}
y = x / arr.length;
System.out.println("Average: " + y);
System.out.println("Number of integers greater than average: ");
int count = 1;
for(int i = 0; i < arr.length; i ++)
{
if(arr[i] > y)
{
System.out.print(count + ",");
count ++;
}
}
}
}
}
Change the last section of your code from this :
for(int i = 0; i < arr.length; i ++)
{
if(arr[i] > y)
{
System.out.print(count + ",");
count ++;
}
}
To this :
for(int i = 0; i < arr.length; i ++)
{
if(arr[i] > y)
{
count ++;
}
}
System.out.print(count);
It should print the number of integers greater than average.
Xerox's answer was good, but I noticed a bug in your code. If you start count at 1, your count will be off. Also, I thought I'd show you how to use a foreach loop. So I made some updates to your code, ran it, and added comments for you. Remember, short variable names were used in the 80s because they took up disk space and slowed down processing time when they were larger. That's no longer an issue, and if your variable names are cryptic, your code is difficult to read, even when it's simple. You'll notice that your code is much easier to read with descriptive variable names and a foreach loop. I left the rest of the file for you to do if you are interested.
import java.util.Scanner;
public class Sparky {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int n;
do {
System.out.print("Enter integer n, greater than 0: ");
n = kbd.nextInt();
} while (n < 1);
System.out.println();
int[] arr = new int[n];
System.out.println("Array on one line: ");
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 500) + 1;
System.out.print(arr[i] + " ");
}
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
System.out.println();
{
double x = 0;
double average; //Better to have readable variables. "y" means nothing, "average" is clear, especially in the next section.
for (int i = 0; i < arr.length; i++) {
x = arr[i] + x;
}
average = x / arr.length;
System.out.println("Average: " + average);
int numberGreaterThanAverage = 0; //This needs to start at 0 or your count will be off. Also, name the variable what it does. Short variable names help no one.
for (int number: arr) { //This is called a foreach loop. It does the same thing as your loop, but is much each to read, also I renamed "i", short for "iterator" to "number" which is what it actually is, a number in the array.
if (number > average) {
numberGreaterThanAverage++;
}
}
System.out.println("Number of integers greater than average: " + numberGreaterThanAverage); //This needed to be moved out of the loop, and it also could be concatenated with the rest of the text to put it all on one line.
}
kbd.close(); //You need to close this or you can get a memory leak
}
}
Always consider printing statements after you are done with modifying the values, best is to print outside the loop.
In this case, Count is being printed before it is incremented, on the last iteration of the loop, it increments and quits the loop.
for(int i = 0; i < arr.length; i ++)
{
if(arr[i] > y)
{
// System.out.print(count + ","); count is being printed before it is incremented
count ++;
}
}
System.out.print(count + ","); //Should be printed **after** the loop ends.
The project description is to create an array of 1000 randomized numbers from 1-50 and to display the 10 highest numbers by frequency. I cut down the numbers in my code for easier testing.
I have created the array with randomized numbers and displayed how many times each number occurred.
I am having trouble figuring out how to sort the numbers from highest highest to lowest.
Any help would be appreciated.
import java.util.*; //import random class and arrays
class MaxArray{
public static void main(String[]args){
Random rand = new Random(1); //create random object and sets seed to one
int[] randArray = new int [51];
int[] newArray = new int[51];
for(int i = 0; i < randArray.length; i++){
randArray[i] = rand.nextInt(50) + 1; // returns a single random integer between 1 and 50
}
Arrays.sort(randArray);
System.out.println(Arrays.toString(randArray));
for(int j = 0; j < randArray.length; j++){
newArray[randArray[j]] += 1;
}
System.out.println(Arrays.toString(newArray));
for(int k = 0; k < newArray.length; k++){
System.out.println("Number " + k + " occurred " + newArray[k] + " times");
}
}// end main
}//end class
This is how you get from highest to lowest
for (int i = randArray.length-1; i >=0 ; i--) {
System.out.print(randArray[i]+" ");
}
and this is how you find 10 highest numbers:
int CheckingDublicate = 0, count = 1;
for(int i = 1; i <= randArray.length; i++){
if(count<=10{
if(CheckingDublicate!=randArray[randArray.length-i])
{
//Ignoring if dublicate
System.out.print(randArray[randArray.length-i]+" ");
CheckingDublicate = randArray[randArray.length-i];
count++;
}
}
else
break;
}
I'm trying to make a program that asks a user for two numbers. I want to determine how many times a certain value appear in the sequence of numbers. For instance, if user entered 10 and 20 the number "1" would appear 9 times. What I am wondering is what condition would I have to set to see how many times the number "1" would appear.
This is what I got so far...
System.out.println("Enter a number: ");
int no1 = scan.nextInt();
System.out.println("Enter a number: ");
int no2 = scan.nextInt();
int i;
int j = 0;
for(i = no1; i <= no2; i++){
if(){ // Some condition here
j++;
}
}
System.out.println(j);
}
Any other tips and tricks on how to make my code efficient would also be greatly appreciated.
for (int i = no1; i <= no2; i++) {
if(String.valueOf(i).contains("1"))
int occurances = StringUtils.countOccurrencesOf(String.valueOf(i), "1");
j+=occurances
}
Assuming that you want to count the occurrences of a digit within a list of numbers you could e.g. use modulo:
int[] occurrences = new int[10];
for (int i = n1; i <= n2; i++) {
int currentNumber = Math.abs(i);
while (currentNumber > 0) {
occurrences[currentNumber % 10]++;
currentNumber /= 10;
}
}
or parse the string representation of the number
int[] occurrences = new int[10];
for (int i = n1; i <= n2; i++) {
String cur = String.valueOf(Math.abs(i));
for (int j = 0; j < cur.length(); j++) {
char currentChar = cur.charAt(j);
if (currentChar != '-')
occurrences[Character.getNumericValue(currentChar)]++;
}
}
occurrences will contain the counts for digits from 0 to 9;
Edit: Added handling for negative integers.
I'm practicing finding max and min values, but I want to keep track of how many instances of those values I have. The program does find the min and max values, but it doesn't give the number of times the value appears in the array, so my counter is not working. Can someone give me a hand please? Thanks!
int[] values = {222,34,56,222,45,1,3,222,56,10,15,56,1,222,12,23,1,222};
int minValue = values[0];
int maxValue = values[0];
int counterMinValue = 0;
int counterMaxValue = 0;
int i;
for(i = 0; i < values.length; i++){
if (values[i] < minValue){
minValue = values[i];
counterMinValue++;
}
}
for(i = 0; i < values.length; i++){
if(values[i] > maxValue){
maxValue = values[i];
counterMaxValue++;
}
}
System.out.printf("The min value of this array is%2d and is repeated%2d times(s)", minValue, counterMinValue);
System.out.printf("\nThe max value of this array is %2d and is repeated %2d time(s)", maxValue, counterMaxValue);
Here is the output:
The min value of this array is 1 and is repeated 2 times(s)
The max value of this array is 222 and is repeated 0 time(s)
I would do something like:
for (i = 1; i < values.length; i++) {
if (values[i] == minValue) {
counterMinValue++;
}
else if (values[i] < minValue) {
minValue = values[i];
counterMinValue = 1;
}
if (values[i] == maxValue) {
counterMaxValue++;
}
else if (values[i] > maxValue) {
maxValue = values[i];
counterMaxValue = 1;
}
}
Basically the same for loop that you have, except it checks to see if the current value is equal to the minValue, if it is, add to the counter, otherwise if the value is lower then set minValue to the current value and reset the counter, then do the same for the max value. I placed this in one for-loop since there is no point in iterating through the same list twice (with bigger sets of data that would greatly impact performance). I'm defaulting the counter to 1 so that you count the current element in the array and not just every element equal to it after.
Likewise, you'll probably want:
int counterMinValue = 1;
int counterMaxValue = 1;
EDIT:
In the case of your example where the largest (could also be smallest) value is the first in the array it gets counted twice due to this section:
if (values[i] == maxValue) {
counterMaxValue++;
}
To correct this you can change the for loop to start at 1 (since you already set the min and max value to the first item in the array you don't need to compare it to itself: for (i = 1; ...) which I have corrected in my above code.
int[] values = {222,34,56,222,45,1,3,222,56,10,15,56,1,222,12,23,1,222};
int minValue = values[0];
int maxValue = values[0];
int counterMinValue = 0;
int counterMaxValue = 0;
int i;
for(i = 0; i < values.length; i++){
if (values[i] == minValue) {
counterMinValue++;
}
else if (values[i] < minValue){
minValue = values[i];
}
}
for(i = 0; i < values.length; i++) {
if (values[i] > maxValue) {
maxValue = values[i];
} else if (values[i] == maxValue) {
counterMaxValue++;
}
}
System.out.printf("The min value of this array is%2d and is repeated%2d times(s)", minValue, counterMinValue);
System.out.printf("\nThe max value of this array is %2d and is repeated %2d time(s)", maxValue, counterMaxValue);
}
I got these results:
The min value of this array is 1 and is repeated 3 times(s)
The max value of this array is 222 and is repeated 5 time(s)
I have an array of 100 numbers and I only gave the array even values. How can I print out how many elements of the array I have to add to obtain a sum < than 1768 using a WHILE LOOP? The following is what I have so far and I am stuck... thanks in advance for the help
void setup() {
int[] x = new int[100];
int i=0;
int sum=0;
for(i=0; i<100; i++) {
if (i%2==0) {
x[i]=i;
sum+=x[i];
}
}
}
void setup() {
int i = 0;
int sum = 0;
int counter = 0;
while (sum < 1768) {
sum += i;
i += 2;
counter++;
}
System.out.println(counter);
}
You start with the even index of 0. Then just skip odd numbers by using i += 2.
If the number of elements is limited with 100, add i < 200 to the while condition:
while (sum < 1768 && i < 200)
The array of 100 even numbers will contain numbers from 0 to 200.
The variable counter will contain the number of additions performed. Its value will be equal to i / 2, so you can remove that additional variable.
You can use this loop and element number would be i+1.
for(int i=0,k=0; k<1768; i++,k+=x[i]) {
System.out.println(x[i]+" - "+k);
}
While loop -
int i=0,k=0;
while(k<1768; ) {
System.out.println(x[i]+" - "+k);
i++,k+=x[i];
}
You are skipping indexes in your array.You are only filling every other 'slot'
Also, it would probably be easier to use a while loop to check against your max value (1728)
int[] x = new int[100];
int i = 0;
int sum = 0;
int max = 1728;
while (sum < max && i < 100)
{
x[i] = i*2;
if ((x[i] + sum) < max)
{
sum += x[i];
}
i++;
}
void setup() {
int[] x = new int[100];
int maxValue = 1768;
int i;
int sum=0;
while(sum<maxValue) {
if (i%2==0) {
x[i]=i;
sum+=x[i];
i++;
}
}
System.out.println(i+" Elements needed")
}
following is code:
void setup() {
int[] x = new int[100];
int i=0;
int sum=0;
for(i=0; i<100; i++) {
if (i%2==0) {
sum += i;
if(sum<1768){
num +=1;
}
}
}
}