This is the question that I need to figure out:
Write a method called percentEven that accepts an array of integers as a parameter and returns the percentage of even numbers in the array as a real number. For example, if the array stores the elements [6, 2, 9, 11, 3] then your method should return 40.0. If the array contains no even elements or no elements at all, return 0.0.
Here is what I have so far:
import java.util.*;
public class Change {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Let's find the range.");
System.out.println("Enter five numbers to find the range.");
int num = console.nextInt();
int[] list = new int[num];
System.out.println("The numbers you entered are: " + list.length);
System.out.println();
percentEven(list);
}
public static void percentEven(int[] num){
int percent = 0;
int even = 0;
for(int i = 0; i < num.length; i++){
if(num[i] % 2 == 0){
even++;
}
}
percent = (even / num.length) *100;
System.out.println("The percent of even numbers is: " + percent);
}
}
When I run it, I get 100 as the percent.
Two issues here:
Cast one of them to a double or float.
percent = (even / (double) num.length) *100;
The other issue is that you never assign the numbers any value, so they are all 0. 0 % 2 is equal to 0, so the list is, by definition, 100% even.
You should also have a base case in the method when nums == {}, which would return 0.0 as the assignment states.
There are three major problems in your code:
You are reading only ONE integer, not five
You use this single integer to define the LENGTH of the array, not the content (so you don't put the integer into the array. So the array contains only zeroes, which means that all of them are even.
You are doing wrong integer arithmetic (as Obicere already stated in his answer). But this doesn't have any effect, as all elements of the array are even, so the result will be 100 in any case.
You are almost there. But you are initializing and storing the array wrong way. Do this
int num = console.nextInt();
int[] list = new int[num];
System.out.println("Enter " + num + " numbers");
for(int i = 0; i < num; i++) {
list[i] = console.nextInt();
}
System.out.println("The numbers you entered are: " + java.util.Arrays.toString(list));
System.out.println();
and also do as other suggested.
Write
percent = even * 100 / num.length;
Changing the order of the operations will make the integer division business work in your favour - you'll get a value rounded down to the next lowest percentage, rather than rounded down to zero.
Also fix the problem with all the numbers being zero by reading them from the keyboard, as in tintinmj's answer.
import java.util.*;
public class percentEvenClass
{
public static void main(String[] args){
int[] list = {6, 2, 9, 11, 3};
int percentEven_Result = percentEven(list);
System.out.println(percentEven_Result);
}
public static int percentEven(int[] list){
int count = 0;
int percent = 0;
for (int i=0; i<list.length; i++){
if (list[i] % 2 == 0){
count++;
}
percent = (count * 100)/ list.length;
}
return percent;
}
}
Related
public static void main(String[] args) {
int avg=0,sum=0,percentage=0;
Scanner input = new Scanner(System.in);
int[]arr=new int [6];
System.out.println("Enter all the elements: ");
for(int i=0; i<6; i++)
{
arr[i]=input.nextInt();
sum+=arr[i];
avg=sum/6;
}
System.out.println("Average is: "+avg);
for(int i=0;i<arr.length;i++)
{
if(arr[i]>avg)
{
percentage=(arr[i]*100/6);
}
}
System.out.println("Percentage is: "+percentage+"%");
}
For example, if 3 of the elements of the array are greater than average, percentage is 3*100/6=50%
Your calculations are wrong at the bottom part.
for(int i=0;i<arr.length;i++){
if(arr[i]>avg)
{
percentage=(arr[i]*100/6);
}
}
here, the correct calculation would be
for(int i=0;i<arr.length;i++){
if(arr[i]>avg)
{
percentage += (100/6);
}
}
you have to add the count the number of times arr[i] is greater than average and multiply the count with 100/6. The above code does exactly that.
NB: The percentage variable should be a floating point number not an integer
First, to compute the global average, do it at the end, using the array length tobe more generic
double sum=0;
for(int i=0; i<6; i++){
arr[i] = input.nextInt();
sum += arr[i];
}
avg = sum/input.length;
System.out.println("Average is: "+avg);
Then to compute the part that are the greater than the average, find how many values are greater then divide by the total number :
double greaterAvg = 0;
for(int i=0;i<arr.length;i++){
if(arr[i]>avg){
greaterAvg++;
}
}
double percentage = 100 * greaterAvg / input.length
System.out.println("Percentage is: "+percentage+"%");
I used double type to remove int division problem : Int division: Why is the result of 1/3 == 0?
To calculate the percentage of elements having a value greater than
average. first, you have to find the count of those elements and then divide it
with the total number of elements
Try this:
public static void main(String[] args) {
int avg=0,sum=0,percentage=0;
Scanner input = new Scanner(System.in);
int[]arr=new int [6];
System.out.println("Enter all the elements: ");
for(int i=0; i<6; i++)
{
arr[i]=input.nextInt();
sum+=arr[i];
avg=sum/6;
}
System.out.println("Average is: "+avg);
int count = 0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]>avg)
{
count=count+1;
}
}
System.out.println(count);
percentage = (count*100)/6;
System.out.println("Percentage is: "+percentage+"%");
}
Output:
Enter all the elements:
1 2 3 4 5 6
Average is: 3
3
Percentage is: 50%
You need to find the total number of values that are greater than the average. Then you take that total number and divide it by the max, then multiple by 100 to return the percentage. For example, if we use 6, 5, 4, 3, 2, 1; The average is 3. The total number greater than 3 is 3 (6, 5, 4). We then take 3 (total) and divide it by max (6) to get .5 then multiply by 100 to get 50 (50%).
array = 6, 5, 4, 3, 2, 1
average = 3
max = 6
percentage = average / max * 100
public static void main(String[] args) {
int avg=0,sum=0,percentage=0;
Scanner input = new Scanner(System.in);
int[]arr=new int [6];
System.out.println("Enter all the elements: ");
for(int i=0; i<6; i++)
{
arr[i]=input.nextInt();
sum+=arr[i];
avg=sum/6;
}
System.out.println("Average is: "+avg);
int greaterThan = 0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]>avg) {
greaterThan++;
}
}
percentage = (int) (((double) greaterThan / (double) arr.length) * 100D);
System.out.println("Percentage is: "+percentage+"%");
}
You can use a counter variable initialized to zero to count the elements first, then you can simply count the percentage using COUNTER * 100 / (number of elements)
You're calculating the avg in the loop, that's not efficient as the value get crushed at each iteration. It's better to keep only the sum in the loop and calculated the avg after the first loop.
This being said, there are only two main (functional) issues in your code:
The first one is the percentage processing in the loop - you're missing the "+=" and should not use arr[i] value.
The second one is the accuracy of the percentage, should be double (e.g) instead of int (same for the average - if really needed).
To sum up :
Declare percentage as double : double percentage = 0;
Replace percentage=(arr[i]*100/6); => percentage += (100.0/6);
[Optional] Truncate/round the percentage for display: e.g. System.out.printf("Percentage is: (%.2f) %%", percentage);
Cheers!
The full assignment was to create a number of methods, e.g. getMode and getAverage, to compute stats for an array with randomly-generated numbers and user-inputted ceiling max, floor min, and sample size. All of my other methods seem to work, but every time I try returning the populated set's min value, I get 0--even if the inputted min was something higher.
Here's my code:
import java.util.Random;
public class Stats extends Main
{
int sampleSize;
double count;
double ave;
double sum;
int mode;
int evenCount;
int oddCount;
int countMatching;
int counter;
int target;
int match;
//Method: return the sample set's max value
public int getMax(int sampleSize, int[] data)
{
int max = Integer.MAX_VALUE;
max = data[0];
for(int i = 0; i < sampleSize; i++)
{
if (data[i] > max)
max = data[i];
}
return max;
}
//Method: return the min value
public int getMin(int sampleSize, int[] data)
{
int min = Integer.MIN_VALUE;
min = data[0];
for(int i = 0; i < sampleSize; i++)
{
if (data[i] < min)
min = data[i];
}
return min;
...
And the main program:
import java.util.Random;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int stats;
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the Stats Program!");
System.out.println();
System.out.println("Enter sample size: ");
int sampleSize = keyboard.nextInt();
System.out.println();
System.out.println("What is the sample set's minimum? ");
int min = keyboard.nextInt();
System.out.println();
System.out.println("What is the sample set's maximum? ");
int max = keyboard.nextInt();
System.out.println();
Stats g = new Stats();
System.out.println("Main Menu");
System.out.println();
System.out.println("1) Get max value");
System.out.println("2) Get min value");
System.out.println("3) Get the mean");
System.out.println("4) Get the mode");
System.out.println("5) Get the count of even numbers");
System.out.println("6) Get the count of odd numbers");
System.out.println("7) Display the sample set");
System.out.println("8) Return the count of numbers in the sample set that match the input parameter");
System.out.println("9) Exit");
System.out.println();
stats = keyboard.nextInt();
//Constructor: use an RNG to generate sampleSize integers between minValue and maxValue. Store the numbers in an array named 'data'.
int[] data = new int[sampleSize];
for (int i = 0; i < sampleSize; i++)
{
Random rand = new Random();
data[i] = rand.nextInt((max - min + 1) + min);
}
while (stats != 9)
{
if (stats == 1)
{
g.getMax(sampleSize, data);
System.out.println("Max is: " + g.getMax(sampleSize, data));
System.out.println();
}
else if (stats == 2)
{
g.getMin(sampleSize, data);
System.out.println("Min is: " + g.getMin(sampleSize, data));
System.out.println();
}
...
Any idea why my program isn't returning appropriate min values (equal to or above what the user inputs)? The max seems to come out fine--sometimes it's below the user's inputted max, and most often it's equal. I've looked at other questions re. min/max and arrays with random numbers, but haven't been able to apply their solutions to my own problem.
Thanks in advance!
Look at this part of your code:
for (int i = 0; i < sampleSize; i++)
{
Random rand = new Random();
data[i] = rand.nextInt((max - min + 1) + min);
}
First wrong thing is that you create a new random number generator in each iteration. You should create it before the loop and just use it in the loop.
But that's the less important issue. The more important one is the way you run rand.nextInt(). Suppose your min is 3 and your max is 7. Then (max - min + 1) + min gives you 8. And this means you are calling rand.nextInt(8), which will give you a number such that 0 ≤ number < 8.
The method Random.nextInt(int n) gives you back a number such that 0 ≤ number < n. So if you want a number such that 3 ≤ number < 8, you'll need it to give you something between 0 and 5, and add that to 3. This means:
rand.nextInt(max - min + 1) + min;
It looks almost like what you wrote, but the extra pair of parentheses made all the difference. You can't just stick parentheses anywhere. The first parenthesis after the name of a method defines that method's parameters, and in your case, it caused the + min to become part of the parameter to nextInt.
One more thing: your class should not extend Main. They are not related in any way, your Stats is not a kind of Main, right?
Your min method seems to work well, maybe there is no number in your array that is less than 0.
This answer is not exactly to make your actual method work but is just a suggestion for a much easier way to do this.
You could use Collections and Commons Lang to find the min/max of an array and to convert a primitive array to a List.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
public class tst {
public static void main(String[] args) {
int[] arr = {1, 23, 43, 2, 4, 5, 5, 1, 2, 3};
List lst = Arrays.asList(ArrayUtils.toObject(arr));
System.out.println(Collections.min(lst));
System.out.println(Collections.max(lst));
}
}
This will output min:1 and max:43.
This is a good solution to consider if you are not forced to use primitive arrays and do everything by yourself.
Hope it helps :)
Please change you random nextInt function on how you get the random value.
it should be
data[i] = rand.nextInt(max - min + 1) + min;
not data[i] = rand.nextInt((max - min + 1) + min);
i'm having some trouble recursively adding integers in java from 1^2 to n^2.
I want to be able to recursively do this in the recurvMath method but all i'm getting is an infinite loop.
import java.util.Scanner;
public class Lab9Math {
int count = 0;
static double squareSum = 0;
public static void main(String[] args){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the value you want n to be: ");
n = scan.nextInt();
Lab9Math est = new Lab9Math();
squareSum = est.recurvMath(n);
System.out.println("Sum is: "+squareSum);
}
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 0){
return 0;
}//end if
if (n == 1){
return 1;
}//end if
if (n > 1){
return (recurvMath((int) ((int) n+Math.pow(n, 2))));
}//end if
return 0;
}//end method
}//end class
I'm not fully grasping the nature of defining this recursively, as i know that i can get to here:
return (int) (Math.pow(n, 2));
but i can't incorporate the calling of the recurvMath method correctly in order for it to work.
Any help would be appreciated. Thanks!
In general, when trying to solve recursive problems, it helps to try to work them out in your head before programming them.
You want to sum all integers from 12 to n2. The first thing we need to do is express this in a way that lends itself to recursion. Well, another way of stating this sum is:
The sum of all integers from 12 to (n-1)2, plus n2
That first step is usually the hardest because it's the most "obvious". For example, we know that "a + b + c" is the same as "a + b", plus "c", but we have to take a leap of faith of sorts and state it that way to get it into a recursive form.
So, now we have to take care of the special base case, 0:
When n is 0, the sum is 0.
So let's let recurvMath(n) be the sum of all integers from 12 to n2. Then, the above directly translates to:
recurvMath(n) = recurvMath(n-1) + n2
recurvMath(0) = 0
And this is pretty easy to implement:
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 0){
return 0;
} else {
return recurvMath(n-1) + (n * n);
}
}
Note I've chosen to go with n * n instead of Math.pow(). This is because Math.pow() operates on double, not on int.
By the way, you may also want to protect yourself against a user entering negative numbers as input, which could get you stuck. You could use if (n <= 0) instead of if (n == 0), or check for a negative input and throw e.g. IllegalArgumentException, or even use Math.abs() appropriately and give it the ability to work with negative numbers.
Also, for completeness, let's take a look at the problem in your original code. Your problem line is:
recurvMath((int) ((int) n+Math.pow(n, 2)))
Let's trace through this in our head. One of your int casts is unnecessary but ignoring that, when n == 3 this is recurvMath(3 + Math.pow(3, 2)) which is recurvMath(12). Your number gets larger each time. You never hit your base cases of 1 or 0, and so you never terminate. Eventually you either get an integer overflow with incorrect results, or a stack overflow.
instead of saying:
return (recurvMath((int) ((int) n+Math.pow(n, 2))));
i instead said:
return (int) ((Math.pow(n, 2)+recurvMath(n-1)));
Try this
import java.util.Scanner;
public class Lab9Math {
int count = 0;
static double squareSum = 0;
public static void main(String[] args){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the value you want n to be: ");
n = scan.nextInt();
Lab9Math est = new Lab9Math();
squareSum = est.recurvMath(n);
System.out.println("Sum is: "+squareSum);
}
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 1){
return 1;
}//end if
// More simplified solution
return recurvMath(n-1) + (int) Math.pow(n, 2); // Here is made changes
}//end method
}//end class
I have a program where the user inputs marks into the array and then gets the average value
This is using Jcreator
My problem is that when I ask for the average on my program,it says that the average is 1
This is my code :
//averageEnglish
public void averageEnglish()
{
System.out.println("The Average Mark Of English Is");
int averageEnglish = english.length / 10;
System.out.println("-----------");
System.out.println(averageEnglish);
System.out.println("-----------");
}//End of averageEnglish
English is an int array
int[] english = new int [10];
averageEnglish is a variable
int averageEnglish;
10/10 equals 1. pretty normal.
what you need to do is get the sum of all elements, and divide them by the length of the array.
also: the IDE you use is not really relevant
english.length/10 is not the average value of the array, its simply the length (10) of the array divided by 10, which is 1. You need to sum up all values of the array and divide the sum by the length of the array.
Often you want to present the result not only as an integer but with a few decimals, store the sum and average result in a double.
double sum = 0;
for (int i = 0; i < english.length; i++) {
sum += english[i];
}
double average = sum / english.length;
You are dividing the array's length by the constant 10 (which just happens to be the length), so naturally you'd get 1. You should sum all values of the array and only then divide them by its length:
double englighSum = 0;
for (int i = 0; i < english.length; ++i)
englishSum += english[i];
}
double englishAverage = englishSum / english.length;
If you want user to fill the array, you need to use Scanner object.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of grades: ");
int n = scanner.nextInt();
double[] english = new double[n];
for(int i=0; i<n; i++)
{
System.out.println("Please enter the grade for grade " + (i+1) + ":");
english[i] = scanner.nextDouble();
}
scanner.close();
Than you may use Markus Johnsson's code to proceed.
You anticipated the size of the array and assumed it is always 10 which is the first mistake, then you did your division based on the number of array elements not their sum:
int[] english = new int[10];
/* Now we assume you did some stuff here to fill the array. */
//averageEnglish
public void averageEnglish()
{
System.out.println("The Average Mark Of English Is");
int noOfElements = english.length; // The divisor
int sum = 0; // The dividend
for (int i = 0; i < noOfElements; i++)
{
sum += english[i];
}
// Here is your Average (Should be of type double since there will be floating points)
double averageEnglish = sum / noOfElements;
System.out.println("-----------");
System.out.println(averageEnglish);
System.out.println("-----------");
}//End of averageEnglish
The value of english.lenght is always 10. As in this example:
int[] english = new int [10];
It doesn't matter what data the english array holds, its lenght is always 10.
In order to do the proper calculation use the data, not the lenght of the array.
Write a method that computes the sum of the digits in an integer. Use
the following method header: public static int sumDigits(long n)
Programming problem 5.2. Page 212.
Please forgive my newness to programming. I'm having a hard time understanding and answering this question. Here's what I have so far. Please assist and if you dont mind, explain what I'm doing wrong.
import java.util.Scanner;
public class PP52v2 {
public static void main(String [] args) {
int sum = sumDigits(n);
System.out.println("The sum is: " + sum);
}//main
public static int sumDigits(long n) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
n = input.nextLong();
int num = (int)(n);
int sum;
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new num
}//loop
return sum;
}//sumDigits
}//class
Basically, you should not be handling the user input inside of the method. You should be passing the user input into your method. Other than that, everything looks good. I've made that slight change below:
import java.util.Scanner;
public class PP52v2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
long n = input.nextLong();
int sum = sumDigits(n);
System.out.println("The sum is: " + sum);
}// main
public static int sumDigits(long n) {
int num = (int) (n);
int sum = 0;
while (num > 0) {
sum += num % 10; // must mod - gives individual numbers
num = num / 10; // must divide - gives new num
}// loop
return sum;
}// sumDigits
}// class
Do the prompt
System.out.println("Enter your digits");
n = input.nextLong();
in your main(String[] args) method because n is not currently declared in the scope of the main method.
public static int sumDigits(int num) {
int sum = 0;
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new number
} //End loop
return sum;
}
For one, you should not read in the number within this method, as it accepts the number as a parameter. The method should be invoked after calling long inputNum = input.nextLong(); by using int digitSum = sumDigits((int)inputNum).
When writing a method, you have input, output, and side effects. The goal is to choose the right combination of the three so that the method, and program as a whole, words as expected.
It seems like your method is supposed to take a number as input and return each digit added together into one final sum.
Write A Test
Usually when you program, you come up with some code that uses your imaginary function. This is called a test. For a test, this could work:
System.out.println("123 should be 6: " + sumDigits(123));
Choose A Signature
You've already managed to right the correct signature. Nice!
Implement Method
Here's where you're a bit confused. Read through what every line of code does, and see if it is accomplishing your goal.
// set up a scanner for reading from the command line
// and print a message that you expect digits
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
// read the next long number from the input stream
n = input.nextLong();
Why is this part of your method? You already have the number passed in as the argument n.
// cast the number to an integer
int num = (int)(n);
Again, not sure what this is accomplishing, besides the possibility of a bug for large numbers.
// initialize the sum variable to 0.
int sum;
Would be clearer to explicitly set the sum to 0. int sum = 0;
// add the last digit and truncate the number in a loop
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new num
}
// actually return the calculated sum
return sum;
This seems like the only part of the method you need. Hopefully this helps!
Since the input number can be either positive or negative, you need to convert it to its absolute value to get the sum of digits. Then for each iteration, you add the remainder to the total sum until the quotient is 0.
public static int sumDigits(long n) {
int sum = 0;
long quotient = Math.abs(n);
while(quotient > 0) {
sum += quotient % 10;
quotient = (long) quotient / 10;
}
return sum;
}
Your code works fine for me.
i just changed int sum = sumDigits(n) to int sum = sumDigits(0) since n wasn't declared.
To have it done correctly, you just would have to put your scanner into the main method and pass the result of it (the long value) to your method sumDigits(long n).