wrong results from simple java method [duplicate] - java

This question already has answers here:
Simple division in Java - is this a bug or a feature?
(5 answers)
Closed 7 years ago.
I'm trying to write a program that asks for the size of an array of integers, the values of the array, and then finds the average of the positive integers and prints it. When I run it, I sometimes get wrong results. I haven't identified on what the wrong results depends but for example if I enter the following input: "array size: 4, array values: 1, 2, -5, 5" I get an average of "2.0"
Here's my code:
import java.util.Scanner;
public class Mitra {
private static Scanner user_input;
double avg (int[] arr, int size)
{
int sum = 0;
int numbers = 0;
for (int i=0; i<size;i++)
{
if (arr[i]>0)
{
sum = sum+arr[i];
numbers++;
}
else{
continue;
}
}
double average = sum/numbers;
return average;
}
public static void main(String[] args) {
user_input = new Scanner (System.in);
System.out.println("enter array length");
int alength = user_input.nextInt();
int[] array_1 = new int[alength];
for (int i=0; i<alength;i++)
{
System.out.println("Enter array value "+i);
array_1[i] = user_input.nextInt();
}
Mitra obj = new Mitra();
double result = obj.avg(array_1, alength);
System.out.println("The average of the positive numbers of the array is "+result);
}
}

Change
double average = sum/numbers;
to
double average = (double)sum/numbers;
to force floating point division.
Otherwise, int division (which is the operation that takes place when dividing two variables of int type) will give you 2 when dividing 8/3 (as you do in your example).

When you evaluate sum/numbers it stores the result in a temporary variable(and the decimal part is already truncated) and then assigns it on the left side.You need to typecase it with (Double) like this:
double average = (double)sum/numbers;

Related

Array to input 100 numbers

I need to allow the user to type exactly 100 numbers, so 100 inputs, and then print the minimum number out of those. It'd be very inefficient to type 100 .nextInt() lines and I thought that I could use an array of exactly 100 inputs and then once it's done find the min and print it out. But I do not know how to do it, so what is a simple way to do that? Thanks
You can do it without an array lets see how.
int smallest=Integer.MAX_VALUE;//assume smallest to be largest integer
for(int i=0;i<100;i++){
int num=sc.nextInt();//this will run 100 times and hence will input 100 number
if(num<smallest){//if number is smaller than smallest then num is smallest
smallest=num;
}
}
System.out.println(smallest);
Try this code sample.
I ran it on my computer and it works.
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
int [] Numbers = new int[100];
Scanner input = new Scanner (System.in);
for (int x=0;x<100;x++){
System.out.println("Enter Number");
Numbers[x]= input.nextInt();
}
int min = Numbers[0];
for (int x=1;x<100;x++){
if (Numbers[x] < min){
min = Numbers[x];
}
}
System.out.println("The Min number is :"+min);
}
}
Hope this Helps :-)
You don't need array, this example is using recursive function/method:
import java.util.Scanner;
public class Code{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
int min = prompt(sc, 1, 5); /* prompts for 5 values, change as required */
sc.close();
System.out.printf("Minium value is: %d%n", min);
}
private static int prompt(Scanner sc, int count, int times){
System.out.printf("Enter number %d of %d: ", count, times);
int n = sc.nextInt();
if(count == times){
return n;
}
return Math.min(n, prompt(sc, (1 + count), times));
}
}
thanks for asking this can be done without any array as explained in other answers but if you want to use a array declare it as
int arr[]=new int[100];
enter the values in it using a for loop,
then apply
Arrays.sort(arr);
arr[0] will be the minimum value element.

Exception in thread "main" java.lang.IndexOutOfBoundsException: [duplicate]

This question already has answers here:
sublist index out of bound exception
(3 answers)
Closed 4 years ago.
The program uses methods to:
get the numbers used to calculate the average,
get the number of lowest numbers to drop before calculating the
get the weight, a double greater than 0 and less than or equal to 1,
calculate the weighted average of the numbers (except the lowest n numbers) entered by the user, and
print the results.
The first method should take no arguments and return an array list of doubles.
The second method should take no arguments and return a single integer, the number of the lowest numbers to drop before calculating the average.
The third method should take no arguments and return a double (the weight)
The fourth method should take three arguments: an array list of numbers (the return value of the first method above); an integer (the number of smallest items to drop before calculating the average); and a double (the weight). This method should return a double (the weighted average of all the numbers except the lowest n values).
The fifth method should take four arguments: an array list of numbers (the return value of the first method above); an integer (the number of smallest numbers to drop before calculating the average); a double (the weight); and a double (the weighted average returned from the fourth method above). This method should have no return value.
For example:
If the user gives these numbers for calculating the average:
40 60 80 100 20
and the user gives the number 2 to indicate how many of the lowest values should be dropped before calculating the average, and gives a weight of 0.5, then the program should give as output:
The weighted average of the numbers is 40.0, when using the data 40.0, 60.0, 80.0, 100.0, 20.0, where 0.5 is the weight used, and the average is computed after dropping the lowest 2 values.
import java.util.*;
import java.lang.*;
import java.util.ArrayList;
import java.util.Collections;
public class MyClass
{
public static ArrayList<Double> getALInfo()
{
Scanner in=new Scanner(System.in);
ArrayList<Double> inputs = new ArrayList<>();
System.out.println("Please enter 5 - 10 integers, Q to quit: ");
String [] tokens = in.nextLine().split("\\s");
for (int i = 0; i < tokens.length; i++)
inputs.add(Double.parseDouble(tokens[i]));
return inputs;
}
public static int getLowestnum()
{
int lowNum = 0;
System.out.println("How many of the lowest values should be dropped? ");
Scanner in = new Scanner(System.in);
lowNum = in.nextInt();
return lowNum;
}
public static double weight()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the weight: ");
double weight = in.nextDouble();
return weight;
}
public static double calculateAvg(ArrayList<Double> inputs,double weight, int lowNum)
{
double sum = 0;
double average = 0;
Collections.sort(inputs);
ArrayList<Double> inputs1 = new ArrayList<Double>(inputs.subList(lowNum, inputs.size()+1));
for (int i = 0; i < inputs1.size(); i++)
{
if (inputs1.get(i) > lowNum)
{
sum = sum + inputs.get(i);
}
}
sum=weight*sum;
average = (sum / inputs1.size());
return average;
}
public static void getAvg(ArrayList<Double> inputs,int n,double weight, double average)
{
System.out.println("The weighted average of the numbers is " + average + ", when using the data " + inputs + " where " +weight+ " is the weight used, and the average is computed after dropping the lowest " +n+" values");
}
public static void main(String args[])
{
int lowNum = 0;
double average;
double weight=0;
ArrayList<Double> inputs= getALInfo();
lowNum = getLowestnum();
weight=weight();
average = calculateAvg(inputs,weight, lowNum);
getAvg(inputs, lowNum,weight, average);
}
}
The program is running fine util you enter the weight after that it shows an array out of bounds exception error. Can you point out where im going wrong .
The error comes from new ArrayList<Double>(inputs.subList(lowNum, inputs.size()+1))
Because you try to reach, as end index, the last element +1 so it does not exists
Solve :
new ArrayList<Double>(inputs.subList(lowNum, inputs.size()))
!! Also, your for loop is wrong
don't need to check with this strange if
you don't pick up from the correct list : use better names
for (int i = 0; i < inputs1.size(); i++) {
if (inputs1.get(i) > lowNum) {
sum = sum + inputs.get(i);
}
}
Solve
ArrayList<Double> subList = new ArrayList<>(inputs.subList(lowNum, inputs.size()));
for (int i = 0; i < subList.size(); i++) {
sum = sum + inputs.get(i);
}

Logical error in loop program

import java.util.Scanner;
public class Unit2Err2{
public static void main( String[] args ){
Scanner scan = new Scanner(System.in);
double sum = 0;
double count = 0;
double in = scan.nextDouble();
while (scan.nextDouble()!= 0){
sum = sum + in;
count++;
}
double avg= sum/count;
System.out.println("The average is " +avg);
}
}
Input: 5 4 3 0 6 4 3
In particular I don't have any errors, I did have a error which said:
incomparable types: boolean and int.
But I fixed it, my issue now is that the average should be 4 instead of 5. I'm wondering where the error is in this, I have tried rearranging it so my average comes out to 4 , but then I often end up with the same error as above.
import java.util.Scanner;
public class Unit2Err2{
public static void main( String[] args ){
Scanner scan = new Scanner(System.in);
double sum = 0;
double count = 0;
double in ;
while ( (in = scan.nextDouble())!= 0){
sum = sum + in;
count++;
}
double avg= sum/count;
System.out.println("The average is " +avg);
}
}
when you first use nextDouble here double in = scan.nextDouble(); it has read a value from the terminal.
You need to re-assign in at each iteration:
while ((in = scan.nextDouble()) != 0){
sum += in;
count++;
}
The program stops and waits for input when it sees the "scan.nextDouble()" statement. Having two in a row is going to read both 5 and 4 without doing anything with the values.
The current code assigns the first input of 5 to the variable in. After that, in is never assigned the value. So 5 is being added each loop iteration.

How to calculate the percentage of even numbers in an array?

i am beginner and here is the method I am struggling with.
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...
public static double percentEven(int[]a){
int count = 0;
double percent = 0.0;
if (a.length > 0){
for ( int i = 0; i < a.length; i++){
if ( a[i] % 2 == 0){
count++;
}
}
percent =(count/a.length)*100.0;
}
return percent;
}
i keep returning 0.0 when array contains a mix of even and odd elements but works fine for all even element array or all odd array? i can't see where the problem is?
thanks in advance.
count/a.length returns 0 since you are dividing two ints, and the second operand is larger than the first. Change it to (double)count/a.length in order to perform floating point division.
Alternately, change the order of operations to :
percent = 100.0*count/a.length;
For a simple division like 2*100.0/5 = 40.0, the above logic would work fine but think about the situation where we have 51*100.0/83 the output would be less readable and its always advisable to truncate the percentage to a limited decimal digits.
An example:
int count = 51;
Double percent = 0.0;
int length = 83;
percent = count*100.0/length;
System.out.println(percent);
output: 61.44578313253012
When you truncate it:
Double truncatedDouble = new BigDecimal(percent ).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(truncatedDouble);
output: 61.446
#Bathsheba : Well said, thanks for the suggestion.
Here is sample code :
public class PercentEven {
public static void main(String args[]){
int count = 0;
int[] a={2, 5, 9, 11, 0}; // this can be dynamic.I tried diff values
double percent = 0.0;
if (a.length > 0){
for ( int i = 0; i < a.length; i++){
if ( a[i] % 2 == 0){
count++;
}
}
percent = (100*count/a.length);
}
System.out.println(percent);
}
}
List<Integer> numbers = Arrays.asList(a);
int number = numbers.stream().filter(n->n%2==0).count();
int percent = number*100.0/numbers.size();
I have done this in java 8

output blank--Java program to calculate average of array

I am writing a program that takes 10 floating point numbers as inputs, and displays the average of the numbers followed by all of the numbers that are greater than the average. I am using a method that takes an array of doubles as a parameter and returns the average of the data in the array. However, my problem is that when I run my program the output window is completely blank. I assume this is because I did not call in my method to the main method. However, I am not sure how to write that code. Thank you.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
}
public double average(double[] number) {
Scanner scanner = new Scanner(System.in);
int x = 0;
double sum = 0;
double[] numberList = new double[10]; //array to hold all numbers
double[] largerList = new double[10]; //array to hold numbers greater than the average
int numberIndex = 0;
int largerIndex = 0;
System.out.printf("Please enter 10 floating-point numberes.\nIf more than 10 values are entered, the numbers following 10 are ignored.\nIf less than 10 numbers are entered, the program will wait for you to enter 10.\n");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
sum += numberList[x]; //add up all inputs to find sum
} catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
scanner = new Scanner(System.in);
i = -1;
numberIndex = 0;
largerIndex = 0;
numberList = new double[10];
largerList = new double[10];
continue;
}
}
for (int i = 0; i < number.length; i++) {
sum = sum + number[i];
double average = sum / number.length;
System.out.println("Average value of your input is: " + average);
System.out.println();
//return average;
if (x > average) {
largerList[largerIndex] = x; //add negative input to negativeList array
largerIndex = largerIndex + 1;
}
}
for (int i = 0; i < largerIndex; i++) {
System.out.println(largerList[i]);
}
return 0;
}
}
to answer the main question...
However, my problem is that when I run my program the output window is completely blank. I assume this is because I did not call in my method to the main method. However, I am not sure how to write that code.
public static void main(String[] args) {
new Average().average(new double[10]);
}
Or maybe you are thinking something like this...
public static void main(String[] args) {
double[] numbers = {2,3,4,5,6,4,3,2,1,3};
new Average().average(numbers);
}
A output run from above (with the doubles given):
Please enter 10 floating-point numberes.
If more than 10 values are entered, the numbers following 10 are ignored.
If less than 10 numbers are entered, the program will wait for you to enter 10.
2
3
3
4
1
2
3
4
5
1
Average value of your input is: 0.2
Average value of your input is: 0.5
Average value of your input is: 0.9
Average value of your input is: 1.4
Average value of your input is: 2.0
Average value of your input is: 2.4
Average value of your input is: 2.7
Average value of your input is: 2.9
Average value of your input is: 3.0
Average value of your input is: 3.3
1.0
1.0
1.0
Press any key to continue . . .
If you have question about the code itself, then it would be better to create a new question or edit it to make it more clear.
Good luck with your coding.
Your method average() takes an array of doubles, but then retrieves an other array from standard input. That doesn't make sense.
Either get the doubles and pass them to the method, or don't pass them to the method and get them from standard input.
What you need to do is create an instance of Average class in your main method and call the average() method.
Why parse double array in your average() method when you take the input from user?
well,you are using a non static method "average()" for your task which needs an instances of the class to run which are not creating anywhere.so there are only two options:-
#1.create an instances of your class then call it.
public static void main(String... s)
{
Average obj=new Average();
obj.average();
}
#2.make "average()" a static method by adding static keyword.
public static double average()
{
//your code.....
}
public sttatic void main(String... s)
{
average();
}
your dont need to keep an argument in your method.

Categories

Resources