As part of this problem I needed to find:
the amount of numbers (count)
the sum of the numbers (sum)
the average of the numbers (average)
which numbers are even (evens)
which numbers are odd (odds)
the last two things I need to find are the largest and smallest values.
My teacher wrote the base code already:
Scanner infile = new Scanner ( new FileReader(args[0]) );
int count=0,sum=0, largest=Integer.MIN_VALUE,smallest=Integer.MAX_VALUE, evens=0, odds=0;
double average=0.0;
while (infile.hasNext())
I've written the code for the listed variables within the while loop but I can't figure out what to do about the largest and smallest value.
I have tried doing this within the while loops:
if (count > largest)
largest = count;
if (count < smallest)
smallest = count;
The idea being that while the while loop iterates it will compare the number it passes against the largest value and it will match the largest one it finds in the count against largest and if the number it find is larger than largest, that becomes the new largest. Same idea for smallest.
It is not working though. What should I do?
I'm not sure if you guys need this but this is the code I wrote for the count within the while loop:
count += 1;
What should I do?
EDIT/ADD ON:
I figured you guys should see everything else I've actually done within the while loops:
while (infile.hasNext())
{
count += 1;
sum += infile.nextInt();
average = sum/count;
if (sum%2 != 0)
odds++;
else
evens++;
}
This code is not tested, but it should do what you request.
int count = 0, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE,
sum = 0, even = 0, odd = 0;
while (scanner.hasNextInt()) {
int number = scanner.nextInt();
if (number < min)
min = number;
if (number > max)
max = number;
if (number % 2 == 0)
even++;
else
odd++;
sum+= number;
count++;
}
double average = sum * 1.0 / count;
I believe you need to do something like,
int count = 0, sum = 0, largest = Integer.MIN_VALUE, smallest = Integer.MAX_VALUE,
evens = 0, odds = 0;
double average = 0.0;
while (infile.hasNext()) {
if (infile.hasNextInt()) {
int value = infile.nextInt();
count++;
sum += value;
if (value > largest) {
largest = value;
}
if (value < smallest) {
smallest = value;
}
if (value % 2 == 0) {
evens++;
} else {
odds++;
}
} else {
infile.next();
}
}
average = ((double) sum) / count;
System.out.printf("smallest = %d, largest = %d, average = %f, "
+ "sum = %d, count = %d, evens = %d, odds = %d%n",
smallest, largest, average, sum, count,
evens, odds);
Which I tested with a file containing
50 3 21 57 10 20
And I received the expected (formatted here) output of
smallest = 3, largest = 57, average = 26.833333, sum = 161, count = 6, evens = 3,
odds = 3
Related
Here is the entire question:
"Write a program that reads an integer value and prints the average of all odd integers between 0 and the input value, inclusive. Print an error message if the input value is less than 0. Prompt accordingly."
I can't seem to figure out how to get the math to work out in the for loop. I'm having trouble setting it up so that the loop increments in odds. I've tried a million different things and nothing has worked.
public static void main(String[] args) {
int value;
int oddAvg = 0;
int count = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: ");
value = scan.nextInt();
while (value < 0){
System.out.println("Error: Input should not be less than 0");
System.out.print("Enter an integer greater than 0: ");
value = scan.nextInt();
}
for(){
}
System.out.println("The average of odd integers between 0 and " + value + " is " + oddAvg);
}
}
A trivial approach could be to just iterate from zero to the target number and check whether each number is odd or even:
int sum = 0;
int count = 0;
for (int i = 0; i <= value; i++) {
if (i % 2 != 0) {
sum += i;
count++;
}
}
int avg = sum / count;
But this, of course, is inefficient. A slightly better approach would be to start from the first odd number, 1, and increment it by 2 in each iteration, so you'd be iterating over just the odd numbers:
double sum = 0;
int count = 0;
for (int i = 1; i <= value; i += 2) {
sum += i;
count++;
}
int avg = sum / count;
Or, if you want to really be mathematically sound, you can utilize the fact that the odd natural numbers in a given range are uniformly distributed. Since this distribution is symmetric, the average equals the mean, and you don't need a loop at all:
int start = 1;
int end = value;
if (value % 2 == 0) {
value--;
}
int avg = (end + start) / 2;
General comment:
In this specific case the average would be an int, so I used ints throughout my examples. In the general usecase, you should probably use doubles to avoid mistakes of using integer division.
Here's a solution to your problem!
public static void main(String[] args) {
int input = 25; //this is whatever value you're going up to.
int accumulator = 0; //keep track of the total sum
for (int i = 0; i < input; i++) {
if (i % 2 == 1) { //if odd
accumulator+=i; // add to the running total sum
}
}
System.out.println(accumulator/(input/2)); //print out the total/num of numbers
}
You can try this if interested in Java 8. It is naive approach implementation.
int val = 0;
final OptionalDouble average = IntStream.rangeClosed(0, val)
.filter(n -> n % 2 != 0)
.average();
System.out.println(average);
I am moving along in this program just fine, but as I have progressed I have seemingly made some logic errors that are tough to find & need some help. I have methods that sort the array from least to greatest. Whenever I print the smallest number to the screen it always shows that number as 0 even if I haven't typed any zero. I can get the correct highest number, except for when the user enters the max amount of numbers, then it prints the second highest number. Sometimes I get the correct output for the median, but never get the correct output for the average. Any help is greatly appreciated! I feel like I am close to the correct code, but these errors are giving me a tough time.
public static Scanner kbd = new Scanner(System.in);
public static void main(String[] args) {
//change to 100 when done testing
final int MAXSIZE = 10;
int[] nums = new int [MAXSIZE];
int usedSize, indexOfNextSmallest = 0;
double median, average;
System.out.println("Please enter each number starting from least to greatest(a negative number will quit input): ");
usedSize = getNums(nums);
for (int index = 0; index < nums.length -1; index++) {
indexOfNextSmallest = getIndexOfSmallest(index, nums);
interchange(index, indexOfNextSmallest, nums);
}
median = medians(nums);
average = averages(nums);
System.out.println("The smallest number entered is " + nums[0] + ".");
System.out.println("The largest number entered is " + nums[nums.length-1] + ".");
System.out.println("The median is: " + median);
System.out.println("The average is: " + average);
}
public static int getIndexOfSmallest(int startIndex, int[] nums) {
int min = nums[startIndex];
int indexOfMin = startIndex;
for (int index = startIndex +1; index < nums.length; index++) {
if (nums[index] < min) {
min = nums[index];
indexOfMin = index;
}
}
return indexOfMin;
}
private static void interchange(int index, int indexOfNextSmallest, int[] nums) {
int temp = nums[index];
nums[index] = nums [indexOfNextSmallest];
nums[indexOfNextSmallest] = temp;
}
public static int getNums(int nums[]) {
int usedSize = 0, userValue = 0;
while(userValue >= 0 && usedSize < nums.length) {
nums[usedSize] = userValue;
userValue = kbd.nextInt();
usedSize++;
}
if(!(userValue >= 0)) {
--usedSize;
System.out.println(usedSize + " numbers entered.");
}
else if(!(usedSize < nums.length)) {
System.out.println("Maximum amount of inputs (" + nums.length + ") reached.");
}
return usedSize;
}
public static double medians(int nums[]) {
double median;
if (nums.length % 2 == 0)
median = ((double)nums[nums.length / 2] + (double)nums[nums.length / 2 - 1]) / 2;
else
median = (double)nums[nums.length / 2];
return median;
}
public static double averages(int nums[]) {
double average;
int sum = 0;
for (int index = 0; index < nums.length; index++){
sum = sum + nums[index];
}
average = ((double)sum / (double)nums.length);
return average;
}
}
This is the output that I am getting if I enter 1, 2, 3, 4, 5, -7(the negative is to stop user input(could that be a problem?))
Please enter each number starting from least to greatest(a negative number will quit input):
1 2 3 4 5 -7
5 numbers entered.
The smallest number entered is 0.
The largest number entered is 5.
The median is: 0.5
The average is: 1.5
The answers I should be getting with correct code is 1, 5, 3.0, & 3.0
Thank you again for any help.
Your medians() and averages() methods look fine. I would recommend that you get rid of the getIndexOfSmallest() and interchange() methods. You only ostensibly need these methods because you are trying to sort. But I believe the sort is instead altering the array. Use the following method to find the minimum value:
public int getMin(int[] nums) {
int min = nums[0];
for (int i=1; i < nums.length; ++i) {
if (nums[i] < min) {
min = nums[i];
}
}
return min;
}
I will leave it as a homework assignment for you to code a method to find the maximum value.
The whole thing goes worng in two places:
The first one
final int MAXSIZE = 10;
int[] nums = new int [MAXSIZE];
This means that even though the program stopped accepting values after a negative value; all the rest of the array is filled with 0s.
To resolve this, you can choose to use ArrrayList instead on int array.
The second issue
The existing code for getnums is
public static int getNums(int nums[]) {
int usedSize = 0, userValue = 0;
while(userValue >= 0 && usedSize < nums.length) {
nums[usedSize] = userValue;
userValue = kbd.nextInt();
usedSize++;
}
if(!(userValue >= 0)) {
--usedSize;
System.out.println(usedSize + " numbers entered.");
}
else if(!(usedSize < nums.length)) {
System.out.println("Maximum amount of inputs (" + nums.length + ") reached.");
}
return usedSize;
}
Here in the while loop, the statements
nums[usedSize] = userValue;
userValue = kbd.nextInt();
will ensure that the value at num[0] will always be zero(as userValue is initialised to 0) and it won't be fetched from user input.
Instead it should be:
while(userValue >= 0 && usedSize < nums.length) {
userValue = kbd.nextInt();
nums[usedSize] = userValue;
usedSize++;
}
If you take care of these two issues; then the rest of the code should work out fine.
This is what I get when I run the program after updating it for the second issue:
Input
Please enter each number starting from least to greatest(a negative number will quit input):
5
8
4
32
-5
Output
The smallest number entered is -5.
The largest number entered is 32.
The median is: 0.0
The average is: 4.4
Which is correct cause the average and median are calculated for 10 numbers and the rest of the numbers (after entering negative number) are just 0
Update as per comments
If you just wish to reject the negative number the you can update the while loop in getnums method as:
while(userValue >= 0 && usedSize < nums.length) {
userValue = kbd.nextInt();
if(userValue >= 0) {
nums[usedSize] = userValue;
usedSize++;
}
}
Also, the if loop after that shouldn't decrease the value of usedSize
if(!(userValue >= 0)) {
System.out.println(usedSize + " numbers entered.");
}
Find Number Equal to the sum of factorial of each of its digits eg:145
From 1 to 200
I tried this :
public static void main(String[] args) {
int i = 0, x = 0, temp, temp1, digit = 0, factorial = 1, sum = 0;
System.out.println("Special Numbers from 1 to 10,000 -:");
for (i = 1; i <= 200; i++) {
temp = i;
temp1 = i;
while (temp > 0) {
digit = temp % 10;
factorial = 1;
for (x = 1; x <= digit; x++) {
factorial *= x;//factorial of digit
}
sum += factorial;//sum of factorial of a all the digits of the number
temp = temp / 10;
}
if (sum == temp1) {
System.out.println(temp1);
}
}
}
So if i put i=145 it works but othervise i get the wrong output.
You forgot to make sum 0, so you only get the correct result for the first number you try. The line sum = 0; should go before while(temp>0){.
Your sum variable is declared outside the for block.
Each time you calculate a factorial sum get added to the previous sum and hence 1! + 4! + 5! will never be 145 in this case.
Try initializing it inside the loop to 0.
You need to initialize sum inside the for loop.
for(i=1;i<=200;i++){
sum = 0; //<--include this
temp = i;
temp1 = i;
while(temp>0){
digit = temp%10;
factorial =1;
for(x = 1;x<=digit;x++){
factorial*=x;//factorial of digit
}
sum+=factorial; //sum of factorial
temp = temp/10;
}
if(sum == temp1){
System.out.println(temp1);
}
}
As a class exercise I have to code using methods a program that:
1) Calculates the average of even and odd numbers in an array.
I expect on using one method to find the average of even and odd numbers. However, I'm having trouble on returning the right average. For example, if I enter only odd numbers I get an error, and vice versa.
This error:
"java.lang.ArithmeticException: / zero"
Also, if it were possible I would like to get some help on coding the rest of the exercise which asks for:
2) Print the highest and lowest number in the array
3) Allow the user to modify any of the numbers of the array
So far I have this code:
public static void main (String args[]){
int x[] = new int[4];
Scanner input = new Scanner(System.in);
for(int i = 0; i < x.length ; i++){
System.out.println("Enter a number: ");
x[i] = input.nextInt();
}
System.out.println("Average of even numbers: " + getAverage(x));
System.out.println("Average of odd numbers: " + getAverage(x));
}
public static int getAverage(int a[]){
int add_even = 0;
int counter_even = 0;
int average_even = 0;
int add_odd = 0;
int counter_odd = 0;
int average_odd = 0;
for(int i = 0; i < a.length; i++){
if(a[i] % 2 == 0){
add_even += a[i];
counter_even++;
}
else if(a[i] % 2 == 1) {
add_odd += a[i];
counter_odd++;
}
}
if (add_even % 2 == 1 && add_odd % 2 == 1){
average_even = 0;
average_odd = add_odd / counter_odd;
return average_even;
}
else if (add_even % 2 == 0 && add_odd % 2 == 0){
average_even = add_even / counter_even;
average_odd = 0;
return average_even;
}
else{
average_even = 0;
average_odd = add_odd / counter_odd;
return average_odd;
}
}
Thank you!
Your get average looks more complicated then it needs to be.
First off the getAverage(x):
System.out.println("Average of even numbers: " + getAverage(x));
System.out.println("Average of odd numbers: " + getAverage(x));
will return the same value, so if you wanted to get the average for odds or evens the method should require a boolean arg to represent odd or even.
In your method you should loop through all the numbers and check if it is even. If it is even and you are averaging evens add it to a "total" and add one to a counter. At the end divide "total" by the counter and return the value. The average will most likely include a decimal value, so you should return a double or a float.
Example:
public static double getAverage(int a[], boolean even){
double total = 0;//These are doubles so dividing later does not require casting to retain a decimal (this can be an int if you only want to return integers)
double counter = 0;
for(int i = 0; i<a.length; i++){
if(a[i] % 2 == 0 && even){//even
counter++;
total += a[i];
}else{//odd
counter++;
total += a[i];
}
}
if(total == 0){//Avoid dividing by 0.
return 0; //You can also throw an exception instead of returning 0.
}
return total / counter; //Returns the average for even or odd numbers.
}
For the second part of your question you need to loop through the numbers and find the highest and lowest while looping.
Example:
int highest = 0;
int lowest = 0;
for(int i = 0; i<x.length; i++){
if(x[i] > highest){
highest = x[i];
}
if(x[i] < lowest){
lowest = x[i];
}
if(i == 0){
highest = x[i];
lowest = x[i];
}
}
You have a divide by zero error cropping up here.
else if (add_even % 2 == 0 && add_odd % 2 == 0){
average_even = add_even / counter_even;
average_odd = 0;
return average_even;
}
0 % 2 == 0 so even if add_even is 0 (and as a result, so is counter_even) you're attempting to use it to divide. You'll need to account for that in your code by checking if counter_even is 0.
else if (counter_even != 0 && add_even % 2 == 0 && add_odd % 2 == 0){
1)Using one method to get the average of the even and odd numbers isn't proper because you only return one int. It would be simpler to use two methods but if you're insistent on using one method you could add a boolean as a parameter like this to decide which to do. To handle the ArithmeticException just return 0 if there are no values.
public static int average(int[] n, boolean even) {
int total = 0;
int count = 0;
for (int i = 0; i < n.length; i++) {
if (even == (n % 2 == 0)) {
total += n;
count ++;
}
}
if (count == 0)
return 0;
return total / count;
2)To check find the max and min value simply loop through the array like this
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < x.length; i++) {
if (x[i] < min)
min = x[i];
if (x[i] > max)
max = x[i];
}
3)To allow the user to modify the array, you could print the values and prompt them as to which value they would like to change like this.
System.out.print("Array: ");
for (int i = 0; i < x.length; i++) {
System.out.print(i + ",");
}
System.out.println();
System.out.println("Which value would you like to change?");
int index = input.nextInt();
System.out.println("What do you want the new value to be?");
int value = input.nextInt();
You can then run a method that changes the value of the array
edit(x, index, value);
public static int edit(int[] n, int index, int value) {
n[index] = value;
return n;
}
I used JS for this task, you can just rewrite my code to Java language.
A number is divisible by 2 if the result of its division by 2 has no
remainder or fractional component - in other terms if the result is an
integer. Zero is an even number because when 0 is divided by
2, the resulting quotient turns out to also be 0 - an integer (as a
whole number that can be written without a remainder, 0 classifies as
an integer).
function compareEvenOddAverage(arr) {
let even = 0,
odd = 0,
evenCounter = 0,
oddCounter = 0,
str = '';
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
even += arr[i];
evenCounter++;
} else {
odd += arr[i];
oddCounter++;
}
}
if (even / evenCounter > odd / oddCounter) {
str += 'Average value of even numbers is greater';
} else if (even / evenCounter < odd / oddCounter) {
str += 'Average value of odd numbers is greater';
} else {
str += 'Average values are equal';
}
return str;
}
console.log(compareEvenOddAverage([0, 1, 2, 3, 4, 5]));
I am currently struggling to calculate the average, minimum and maximum in my coding. I am receiving a lot of errors and not sure as to what I am doing wrong. Sorry if I am not providing enough information, I will update my post if needed. Also, I would appreciate if you can explain as to why you used that code so that I can understand please. Thank you.
EDIT - What I want it to do is when the user enters a set of numbers and finished inputting numbers, I want it to display the average of the numbers the user inputted after the histogram as well as the maximum and minimum. I assumed I would have to use my count variable as well as my num variable but still struggling in implementing it.
Errors I am receiving are shown in my coding below within the lines of coding.
import java.util.Scanner;
public class Histogram1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[5000];
int num = 0;
int count = 0;
int total = 1;
int max = 0;
int min = 0;
System.out.println ("Enter students marks in the range 0 to 100\n");
loop: for (count = 0; count <= total; count++)
{
System.out.println ("Enter a number:");
num = scan.nextInt();
if (num < 0 || num > 100)
{
break loop;
}
array[count] = num;
total = count+1;
}
System.out.println ("How many times a number between 0-100 occur.");
String[] asterisk = {"0- 29 | ", "30- 39 | ","40- 69 | ", "70- 100 | "}; //4 strings
for (count = 1; count <= total; count++)
{
num=array[count];
if (num >=0 && num <=29) asterisk [0] +="*";
else if (num>29 && num <=39) asterisk[1] +="*";
else if (num>39 && num <=69) asterisk[2] +="*";
else if (num>69 && num <=100) asterisk[3] +="*";
}
for (count =0;count < 4;count++)
System.out.println(asterisk[count]);
System.out.println("The total amount of students is " + total);
**int cannot be dereferenced** for (int i = 0; i < count.length; i++) {
**array required, but int found** num += count[i];
**array required, but int found** if (min > num[i]) {
**array required, but int found** min = num[i];
}
**array required, but int found** if (max < num[i]) {
**array required, but int found** max = num[i];
}
}
**int cannot be dereferenced** double average = (double) num / count.length;
System.out.printf(" min: " + min);
System.out.printf("%n max: " + max);
System.out.printf("%naverage: %.1f", average);
}
}
If you have an array, minimum is often calculated by first setting the initial minimum value to a known maximum value "infinity" or in this case 100. Next step would be to iterate over your set of values and check whether a value is below current minimum, and if so set minimum to that value.
int min = 100;
for (int i = 0; i < total; i++) {
if (array[i] < min) {
min = array[i];
}
}
for maximum, do the other way around, setting initial maximum value to 0 or negative "infinity" and check whether a value in the array is greater than current maximum value.
for average, sum all values and divide the result on the total amount of elements in the array.
int sum = 0;
for (int i = 0; i < total; i++) {
sum += array[i];
}
double avg = (double) (sum) / total;
In java positive infinity as integer type is represented as Integer.MAX_VALUE and negative infinity: Integer.MIN_VALUE.
Let's assume we have an array of values: int[] values = { some values }
To calculate average:
loop through the array and calculate the sum
divide sum by number of elements
int sum = 0;
for(int i : values) {
sum += i;
}
double average = (double)(sum) / values.length;
To find min and max:
loop through the array and compare current element with min and max and set them appropriately
int max = -2147483648; //set to min int value, -2^31
int min = 2147483647; //set to max int value, 2^31 - 1
for (int i : values) {
if (i > max) max = i;
if (i < min) min = i;
}
I see that the other posts have already answered how to calculate average, min, and max in an array, so I will only be tackling the error with your code.
You receive an error that says that int cannot be dereferenced:
tmp.java:48: int cannot be dereferenced
for (int i = 0; i < count.length; i++) {
^
This stems from the fact that you have defined count as an int not as an array. In fact, all of the compiling errors come from here. The variable count will not have a length, nor can you access its elements (it has none). In the last part of your code (where the errors arise) you have confused count, min, and max as arrays, whereas they are actually just integers. Your code was close (had the proper idea), but I think you might have confused some of the syntax.
Because your array length is always 5000, I had to use the second for loop to calculate the minimum number. Otherwise, if I was to use the first for loop (that is now commented), the minimum number would always be 0 (if less than 5000 numbers inputted) because there would always be trailing elements that are = 0. I would suggest using an ArrayList instead, but my code for you uses the same array you created.
I commented everything I changed/added from your code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[5000];
int num = 0;
int count = 0;
int total = 0; // start this at 0, in case no inputs are valid
double sum = 0; // make this a double to get a decimal average
int max = 0; // start at the lowest possible number for max
int min = 100; // start at the highest possible number for min
double average = 0;
System.out.println ("Enter students marks in the range 0 to 100\n");
loop: for (count = 0; count <= total; count++)
{
System.out.println ("Enter a number:");
num = scan.nextInt();
if (num < 0 || num > 100 || total == 5000) // can't enter more than 5000 (array length restriction)
{
break loop;
}
array[count] = num;
sum += num; // keep track of the sum during input
total = count+1;
}
System.out.println ("How many times a number between 0-100 occur.");
String[] asterisk = {"0- 29 | ", "30- 39 | ","40- 69 | ", "70- 100 | "}; //4 strings
for (count = 1; count <= total; count++)
{
num=array[count];
if (num >=0 && num <=29) asterisk [0] +="*";
else if (num>29 && num <=39) asterisk[1] +="*";
else if (num>39 && num <=69) asterisk[2] +="*";
else if (num>69 && num <=100) asterisk[3] +="*";
}
for (count =0;count < 4;count++)
System.out.println(asterisk[count]);
System.out.println("The total amount of students is " + total);
// calculate the average
average = sum / total;
// calculate the min and max
// use this for loop if the length of the array is
// the amount of the inputs from the user
/*for (int i : array) // for every int in the array of inputted ints
{
if (i > max) max = i; // if this int in array is > the last recording max number, set the new max number to be this int
if (i < min) min = i; // if this int in array is < the last recording min number, set the new min number to be this int
}*/
for (int i = 0; i < total; i++) // for every inputted int ( < total so that you exclude the trailing elements that are = 0)
{
if (array[i] > max) max = array[i]; // if this int in array is > the last recording max number, set the new max number to be this int
if (array[i] < min) min = array[i]; // if this int in array is < the last recording min number, set the new min number to be this int
}
// my way of printing results
//System.out.println("\n Average: " + average);
//System.out.println("Max: " + max + "\n Min: " + min);
System.out.printf(" min: " + min);
System.out.printf("%n max: " + max);
System.out.printf("%naverage: %.1f", average);
}