Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:
A method that accepts two integer parameters and returns their average.
A method that accepts three integer parameters and returns their average.
A method that accepts two integer parameters that represent a range.
Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).
Implement the class and write a program to test its methods and submit your source code (.java files).
I am stuck on part three, I don't even really understand the stipulation. Will I be using a floating point / double? Here is the program I have thus far:
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
int numb1, numb2, numb3, userInput;
System.out.println("Enter '2' if you wish to average two numbers enter '3' if you wish to average 3.");
Scanner keyboard = new Scanner(System.in);
userInput = keyboard.nextInt();
if (userInput == 2){
System.out.println("Enter two numbers you'd like to be averaged.");
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
Average ave = new Average();
System.out.println("The average is: " + ave.average(numb1, numb2));
System.exit(1);
}
if(userInput == 3){
System.out.println("Enter three numbers you'd like to be averaged.");
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
numb3 = keyboard.nextInt();
Average ave = new Average();
System.out.println("The average is: " + ave.average(numb1, numb2, numb3));
System.exit(1);
}
}
public static int average (int num1, int num2) {
return (num1 + num2) / 2;
}
public static int average (int numb1, int numb2, int numb3){
return (numb1 + numb2 + numb3) / 3;
}
}
Please don't re-ask the same question as you just asked here: http://stackoverflow.com/questions/19507108/java-averaging-program
Rather update your other post to reflect your new code / questions.
Now onto your question:
A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive). Implement the class and write a program to test its methods and submit your source code (.java files).
Lets start by declaring our method and we'll declare it as static to conform to your program (since you're not creating your own objects). Then we want to check if the parameters follow the assignment instructions and return values accordingly.
public static int getRange(int firstValue, int secondValue)
{
int range;
if (firstValue > secondValue)
range = firstValue - secondValue;
else
{
range = 0;
System.out.println("Error!");
}
return range;
}
**To promote your understanding it's up to you to find the average of the integers in the range!
Not really here to do your homework, but since I'm already here, the range is the difference between the largest and smallest number.
public int returnRange(int first, int second) {
if(first > second)
return first-second;
else
return second-first;
}
To make things easier though...
public double returnAverage(int...numbers) {
for(int i = 0; i < numbers.length(); i++) {
total += numbers;
}
return total/numbers.length();
}
public int returnRange(int...numbers) {
int holder = 0;
int highest;
int lowest;
for(int i = 0; i < numbers.length(); i++) {
if(numbers[i] > holder) {
holder = numbers[i];
}
highest = holder;
for(int i = 0; i < numbers.length(); i++) {
if(numbers[i] < holder) {
holder = numbers[i];
}
}
lowest = holder;
return highest-lowest;
}
Last 2 methods are un-tested, but from experience, should work fine. These methods have arrays for the parameters, so you can do as many numbers as you'd like.
In your main method check for -1 and return error when first value is greater than second
public double avgRange(int a, int b){
if(a>b){
return -1;
}
else{
double total=0;
for(int x=a; x<=b; x++){
total = total + x;
}
return total/(b-a+1);
}
}
the method should return the average of the integers in that range (inclusive).
You're asked to return the average of all integers in the range bounded by the two parameters.
For example, if parameters were 5 and 10, the method should return the average of 5, 6, 7, 8, 9, and 10, which is 7.5. (5 and 10 are included because the question says the range should be "inclusive".)
To find the average, use a for loop to sum each integer in the range, then divide by the number of integers.
Will I be using a floating point / double?
The return value should be a float or double, since the average isn't always a whole number.
Related
I want to round down an int in Java, what i mean is, if I have an int 45678, i want to convert that int into 40000
this is how im calling it
int den = placeValue(startCode,length);
and this is the code
static int placeValue(int N, int num)
{
int total = 1, value = 0, rem = 0;
while (true) {
rem = N % 10;
N = N / 10;
if (rem == num) {
value = total * rem;
break;
}
total = total * 10;
}
return value;
}
so if i have 89765, i would want 80000,
but instead it return the place value of whatever length is.
So,
for 89765, the length would be 5, so the return value is 5 i.e. the value in the ones place.
but if the number was 85760
then it would return 5000.
I hope that makes sense.
Any suggestions would be much appreicated.
In my opinions, if I can avoid 'calculating' I will compute the answer from other concept since I am not confidence on my math (haha).
Here is my answer. (only work in positive numbers)
I think the length of the inputted number is not necessary.
static int placeValue2(int N) {
String tar = N+"";
String rtn = tar.substring(0,1); // take first digital
for (int i=0;i<tar.length()-1;i++) // pad following digitals
rtn+="0";
return Integer.parseInt(rtn);
}
I appreciate you asked the question here.
Here is my solution. I don't know why you are taking two parameters, but I tried it from one param.
class PlaceValue{
int placeValue(int num){
int length = 0; int temp2=1;
boolean result=false;
long temp1=1;
if (num<0){
result=true;
num=num*(-1);
}
if (num==0){
System.out.println("Value 0 not allowed");
return 0;
}
while (temp1 <= num){ //This loop checks for the length, multiplying temp1 with 10
//untill its <= number. length++ counts the length.
length++;
temp1*=10;
}
for (int i=1; i<length; i++){//this loop multiplies temp2 with 10 length number times.
// like if length 2 then 100. if 5 then 10000
temp2=temp2*10;
}
temp2=(num/temp2)*temp2;
/* Let's say number is 2345. This would divide it over 1000, giving us 2;
in the same line multiplying it with the temp2 which is same 1000 resulting 2000.
now 2345 became 2000;
*/
if (result==true){
temp2=temp2*(-1);
}
return temp2;
}
}
Here is the code above. You can try this. If you are dealing with the long numbers, go for long in function type as well as the variable being returned and in the main function. I hope you understand. otherwise, ask me.
Do you want something like this?
public static int roundDown(int number, int magnitude) {
int mag = (int) Math.pow(10, magnitude);
return (number / mag) * mag;
}
roundDown(53278,4) -> 50000
roundDown(46287,3) -> 46000
roundDown(65478,2) -> 65400
roundDown(43298,1) -> 43290
roundDown(43278,0) -> 43278
So the equivalent that will only use the most significant digit is:
public static int roundDown(int number) {
int zeros = (int) Math.log10(number);
int mag = (int) Math.pow(10, zeros);
return (number / mag) * mag;
}
I have problem in calculate the average of
all the non-negative numbers in the array, zero inclusive, and return zero otherwise. Below is my coding, please help me to check which parts is incorrect. Thanks.
public class AverageOfNonNegativeNumbers {
public static double averageOfNumbers(double[] x) throws Exception {
double avg = 0.1;
if (x != null) {
for (double i = 0.1; i < x.length; i++) {
if ( x[i]%2 == 0 ) { //Anyone know how to set avoid calculate for negative numbers?
avg = avg / x[i]; //This code is calculate total average number.
}
}
}
return avg;
}
public static void main(String args[]) {
double x[] = {1.663, -2.1312, 3.13231, 4.124, -5.551, -6.1312, 7.111, 8.222, -9.01};
try {
System.out.println(AverageOfNonNegativeNumbers.averageOfNumbers(x));
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
Define 2 variables to store the sum of non-negative numbers and the count of non-negative numbers.
Then iterate through the array and check each element for non-negativity. If non-negative, add that value to the sum and increment the count by 1.
Finally, divide the sum by count to get the average.
public static double averageOfNumbers(double[] x) {
double sum = 0; // Variable to store the sum
int count = 0; // Variable to keep the count
if (x != null) {
for (int i = 0; i < x.length; i++) {
double value = x[i];
if (value >= 0) { // Check if the number is non-negative
sum += value; // Add the value to the current sum
count++; // Increment the count by 1
}
}
}
return (count > 0) ? (sum /count) : 0; // Calculate the average if there were any non-negative numbers
}
Following are the issues:
a.you are trying to access the x[i], but i needs to be integer type, while you have it as double
b. x[i]%2 == 0 checks if number is even or not. need to change that to x[i] >= 0
c. Logic to calculate average is not correct.
public class AverageOfNonNegativeNumbers {
public static double averageOfNumbers(double[] x) {
int elements = 0;
double sum = 0;
if (x != null) {
for (int i = 1; i < x.length; i++) {
if ( x[i] >= 0 ) { // changed this check if number is negative or not
sum += x[i]; //This code calculates total sum of all non-negative numbers
elements++; // and also how many of such no exists
}
}
}
return sum/elements;
}
public static void main(String args[]) {
double x[] = {1.663, -2.1312, 3.13231, 4.124, -5.551, -6.1312, 7.111, 8.222, -9.01};
try {
System.out.println(AverageOfNonNegativeNumbers.averageOfNumbers(x));
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
You're trying to use a double as an index to an array; this doesn't really make sense. An array must be indexed by an integer. That is, an array consists of an element in position 0, position 1, 2, etc.; it doesn't really make much sense to say 'the array element at position 0.1'.
To make your code compile, you will need to declare variable 'i' in your for loop in function 'averageOfNumbers' as an 'int' and not a 'double'.
Modifications in you code:
According to your question you want to calculate the average of all negative numbers including 0.
Errors:
The method to check if a number is less than 0. %2 checks if the number is even or not.
The way to calculate average is calculate the sum and count and then divide them to minimize the floating point errors.
public static double averageOfNumbers(double[] x){
double avg = 0.0;
double sum = 0.0;
int count=0;
if (x != null){
for (int i = 0; i < x.length; i++){
if ( x[i]>=0 ){
sum = sum + x[i];
count=count+1;
}
}
}
if(count!=0){
avg=sum/count;
}
return avg;
}
A simle one-Liner using Java 8 Strems:
double avg=Stream.of(x).mapToDouble(d->d).map(num->num<=0).average().orElse(0.0);
It creates a DoubleStream (mapToDouble) and removes all numbers greater than 0 and calculates the average.
If there is no result(because x is empty) it will return 0.
See this for reference.
This is regarding some homework and I tried to make a range which is 10 to 40.
The code would accept two inputs within the range. The method will then check if both numbers are within the range and then if they are it would give me the product of both numbers, if not it is suppose to show me a message.
I have been working on this for quite a long time and I cant get it to work I am a complete beginner.
public class testing
{
public static int computeProduct(int first , int second)
{ int max = 40;
int min = 10;
int total = first * second;
if (min <= first) {
if (first <= max) {
if (min <= second) {
if (second <= max) {
total = first * second;
} else {
System.out.println("Number is not in range, please try again");
}
}
}
}
return total;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number between 10 to 40:");
int x = scanner.nextInt();
System.out.println("Enter another number between 10 to 40:");
int y = scanner.nextInt();
int total = computeProduct(x, y);
System.out.print("Product of x and y = " + total);
}
}
Expected result is to show me if the numbers are not in range but it is not doing so currently.
It gives me the product of both numbers regardless whether it is in the range.
Here:
int total = first * second;
followed by an if, follewed by:
return total;
Meaning: every time when your if evaluates to false, your method simply returns the value that you assigned initially!
What you could do: have an else block that prints the error message. Or that throws an exception.
But ideally, you should separate concerns here. Meaning:
write a method like boolean inRange(int first, int second). That method returns true or false, depending on first / second matching your criteria
if that method returns true, call compute(), otherwise print your message
In other words: your compute() method maybe shouldn't have that if block at all. Let that method compute the result, and have another method tell you whether you want to invoke compute() or not.
A "ladder" built from ifs behaves as a logical and relation. The first if passes when a condition applies, then the second if passes when both the previous condition applies and its own condition, and so on.
However for checking if something is off, violating any (even a single one) of the rules is enough, that is a logical or relation.
While it is not the best coding style, you could mechanically rewrite that structure into this via flipping the comparisions and dismantling the ladder:
public static int computeProduct(int first , int second)
{
int max = 40;
int min = 10;
if (first < min) {
System.out.println("Number is not in range, please try again");
return 0;
}
if (first > max) {
System.out.println("Number is not in range, please try again");
return 0;
}
if (second < min) {
System.out.println("Number is not in range, please try again");
return 0;
}
if (second > max) {
System.out.println("Number is not in range, please try again");
return 0;
}
return first*second;
}
This method displays the message and returns with 0 if the input is not valid, and returns the product if everything is fine.
Then it could become an actual logical or, which is denoted as || in Java:
public static int computeProduct(int first , int second)
{
int max = 40;
int min = 10;
if (first < min
|| first > max
|| second < min
|| second > max) {
System.out.println("Number is not in range, please try again");
return 0;
}
return first*second;
}
Now as I think of it, there is nothing wrong with your original condition either, just the result has to be flipped: when the code reaches the innermost block, everything is fine, so that is the place where you could return first*second;. And if any of the if fails, you need the message and return 0;:
public static int computeProduct(int first , int second)
{
int max = 40;
int min = 10;
if (min <= first) {
if (first <= max) {
if (min <= second) {
if (second <= max) {
return first*second;
}
}
}
}
System.out.println("Number is not in range, please try again");
return 0;
}
Now I am not so sure if this helps or not...
There you go :
public static int computeProduct(int first , int second)
{ int max = 40;
int min = 10;
if(first<=min || second<=min ||first>=max||second>=max)
{
System.out.println("Number is not in range, please try again");
return 0; //or return whatever you like
}
return first *second ;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number between 10 to 40:");
int x = scanner.nextInt();
System.out.println("Enter another number between 10 to 40:");
int y = scanner.nextInt();
int total = computeProduct(x, y);
if(total!=0){
System.out.print("Product of x and y = " + total);
}
else {
System.out.print("cannot compute as numbers are not in range");
}
}
Let's say for the user input 1, I can easily find the square of it. (A single digit input)
How do I use a recursive method to find the sum of squares (input with more than one number) e.g. 12345 should give 1*1 + 2*2 + 3*3 + 4*4 + 5*5 = 55? For the base case, it is correct to as num == 1 right? And from there, how do I compute the subsequent number behind 1?
public static int squareSum(int num) {
if (num == 1) {
return num*num;
} else {
return 0;
}
}
You have to think about the small steps first. It is all about extracting the digits and the calculating the squares.
public static int squareSum(int num) {
if (num == 0) return 0;
return (num%10)*(num%10) + squareSum(num/10);
}
For 12345 :-
f(12345)
f(1234)+5*5
f(123)+4*4+5*5
f(12)+3*3+4*4+5*5
f(1)+2*2+3*3+4*4+5*5
f(0)+1*1+2*2+3*3+4*4+5*5
The problem is, that you can't get the number at position x easily. The fact that 12345 consists of the numbers 1, 2, ... is only obvious in the decimal system. We will therefore store our number as a String, take each character and parse it to an integer. Then we square the number and add them
int i sum = 0;
String iAsString = i;
for (int i = 0; i < iAsString.length; i++) {
int currentNumber = Character.getNumericValue(iAsString.charAt(i));
sum += currentNumber * currentNumber;
}
I need to be able to input a list of numbers the last being -1 and have it print the reverse(not including -1) and then find the average. I have to use a function for finding the reverse. Im stuck because it cannot resolve my average which means I cannot run the program to see if there are other problems.
import java.util.Scanner;
public class Reverse {
public static void inReverse (int a) {
int number;
int[] value;
for (a = number - 2; a >= 0; a--) {
System.out.print(value[a] + " ");
}
}
public static double findAverage (int p, double average) {
int number;
for (p = number - 2; p >= 0; p--) {
average += value[p];
}
average = average / (number - 1);
return average;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] value;
int i, number, size;
size = 20;
System.out.println("Please enter the integers: ");
while (value[i - 1] != -1 && number < size) {
value[i] = input.nextInt();
i += 1;
number = i;
}
System.out.println("The values in reverse order are: ");
inReverse(i);
System.out.println(" ");
System.out.println("The average is " + average);
}
}
Your problem is that you have confused "local variables" with "fields".
Local variables are variables that you declare inside the body of a method. They can't be used before the declaration, and they can't be used once the method stops running - their values have ceased to exist.
Fields are variables that you declare inside your class, but outside any methods. These live inside each object of the class (or inside the class itself if you declare them as static), which means they keep their values from one method call to the next.
You have int number; and int[] value; declared inside different methods, which means they are local variables, and they are recreated each time those methods run. This isn't what you want. You either want to pass them from one method to the next, as parameters; or to have them as fields of your class.