I used this code to calculate the max value and the median element in an array of integers, but when I call the methods in my client class, both of these two methods produce an output of zero. The name of the array is "grades" and it is made of randomly generated integers
import java.util.*;
public class StudentGrades {
private int [] grades;
//Constructor
public StudentGrades ( int students)
{
Random number = new Random();
grades = new int[students];
for (int i = 0 ; i < students ; i++)
{
grades[i] = number.nextInt(99) + 1;
}
}
double median;
public void median()
{
Arrays.sort(grades) ;
double median ;
if (grades.length % 2 == 0)
{
int indexA = (grades.length - 1 ) /2;
int indexB = (grades.length)/2;
median = ((double) (grades[indexA] + grades[indexB]))/2;
}
else
{
int medIndex = (grades.length-1) / 2;
median = grades[ medIndex ];
}
}
public double getMedian()
{
return median;
}
int max;
public int getHighest()
{
for(int i = 0 ; i < grades.length - 1 ; i++)
{
int max = 0;
if(grades[i] > max)
{
max = grades[i];
}
}
return max;
}
In my driver, I simply had to prove that the method worked correctly, so it's:
System.out.println(" The highest grade is" + grades.getHighest());
System.out.println("The median grade is" + grades.getMedian());
Few mistakes.
1.) Might be calling getMedian(), whereas the logic is inside median() method.
2.) Inside method, getHighest(),
a.) No need to loop the array, since array is already sorted. So i have commented the code.
Just get the value at last index of array.
public class Test {
static int max;
static double median;
static int[] grades = { 2, 3, 4, 5, 62, 34 };
public static void main(String args[]) {
Arrays.sort(grades);
median();
getHighest();
System.out.println(median);
System.out.println(max);
}
public static void median() {
if (grades.length % 2 == 0) {
int indexA = (grades.length - 1) / 2;
int indexB = (grades.length) / 2;
median = ((double) (grades[indexA] + grades[indexB])) / 2;
} else {
int medIndex = (grades.length - 1) / 2;
median = grades[medIndex];
}
}
public double getMedian() {
return median;
}
public static int getHighest() {
/* for (int i = 0 ; i < grades.length ; i++) {
if (grades[i] > max) {
max = grades[i];
}
}*/
max = grades[grades.length - 1];
return max;
}
Output
4.5
62
Related
I'm currently working on a homework assignment and the final task of the assignment is to write a method to find the largest gap between consecutive numbers in an unsorted array. Example: if the array had the values {1,2,3,4,5,20} the gap would be 15. Currently the array is holding 20 values generated at random.
I'm totally lost for how I would make this happen. Initially my idea for how to solve this would be using a for loop which runs through each value of the array with another loop inside to check if the current value is equal to the previous value plus 1. If it is then store that number as the minimum in the range. Another problem I ran into was that I have no idea how to store a second number without overwriting both numbers in the range. Basically nothing i've tried is working and could really use some help or at least a nudge in the right direction.
What the method does right now is only store the value for "a" after it finds a number that isn't consecutive in the array.
Here's the code I have so far
import java.util.Arrays;
class Main {
public static void main(String[] args) {
Main m = new Main();
m.runCode();
}
public void runCode()
{
Calculator calc = new Calculator();
calc.makeList(20);
System.out.println("List:");
calc.showList();
System.out.println("Max is: " + calc.max());
System.out.println("Min is: " + calc.min());
System.out.println("Sum is: " + calc.sum());
System.out.println("Ave is: " + calc.average());
System.out.println("There are " + calc.fiftyLess() + " values in the list that are less than 50");
System.out.println("Even numbers: " + calc.Even());
}
}
class Calculator {
int list[] = new int[20];
public void makeList(int listSize)
{
for (int count = 0; count < list.length; count++) {
list[count] = (int) (Math.random() * 100);
}
}
public void showList()
{
for (int count = 0; count < list.length; count++)
{
System.out.print(list[count] + " ");
}
}
public int max()
{
int max = list[0];
for (int count=0; count<list.length; count++){
if (list[count] > max) {
max = list[count];
}
}
return max;
}
public int min()
{
int min = list[0];
for (int count=0; count<list.length; count++){
if (list[count] < min) {
min = list[count];
}
}
return min;
}
public int sum()
{
int sum = 0;
for (int count=0; count<list.length; count++){
sum = sum + list[count];
}
return sum;
}
public double average()
{
int sum = sum();
double average = sum / list.length;
return average;
}
public int fiftyLess()
{
int lessThan = 0;
for (int count =0; count<list.length;count++)
{
if (list[count] < 50)
{
lessThan++;
}
}
return lessThan;
}
public int Even()
{
int isEven = 0;
for (int count = 0; count<list.length;count++)
{
if (list[count] % 2 == 0)
{
isEven++;
}
}
return isEven;
}
public int Gap()
{
int a = 0;
int b = 0;
int gap = math.abs(a - b);
for (int count = 1; count<list.length;count++)
{
if (list[count] != list[count] + 1)
{
a =list[count];
}
}
}
}
By using the java8 stream library you could achieve this in fewer lines of code.
This code segment iterates the range of the array, and subtracts all consecutive numbers, and returns the max difference between them or -1, in case the array is empty.
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference =
IntStream.range(0, list.length - 1)
.map(i -> Math.abs(list[i + 1] - list[i]))
.max().orElse(-1);
System.out.println(max_difference);
}
}
Alternatively you could do this with a traditional for loop.
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference = -1;
int difference;
for (int i = 0; i < list.length - 1; i++) {
difference = Math.abs(list[i + 1] - list[i]);
if(difference > max_difference)
max_difference = difference;
}
System.out.println(max_difference);
}
}
Output for both code segments:
15
I'm trying to create a recursive function that returns the average of the digits in a number. For example the average of the number 123 is 2.
I know how to write a function that sums the digits.
public static int sum (int n) {
if (n<10)
return n;
return n%10 + sum(n/10);
}
I also know how to count the digits
public static int numCount(int n) {
if (n<10)
return 1;
return 1 + numCount(n/10);
}
However I can't figure out how to calculate the average without using pre existing functions.
You can recursively iterate the array while keeping both accumulative sum and an index that shows which items were already iterated:
public class MyClass {
public static void main(String args[]) {
int[] arr = {1,2,3};
System.out.println(avg(arr)); // 2.0
}
private static double avg(int[] arr) {
return avg(arr, 0, 0);
}
private static double avg(int[] arr, int index, int sum) {
if (index == arr.length) {
return (double) sum / index;
}
return avg(arr, index + 1, sum + arr[index]);
}
}
Demo
Try this:
int recursive(int num, int startingSize) {
if(num < 10){
return num;
}
num = num % 10 + recursive(num/10, startingSize++);
return num/startingSize;
}
and for example : recursive(123, 1)
count=0;
public static int sum (int n) {
count++;
if (n<10)
return n;
return n%10 + sum(n/10);
}
double average = (double)sum(123)/count;
System.out.println("average:"+ average);
I mean if we are just talking numbers we don't even need recursive functions here
String s = Double(10.45).toString();
Int size = s.length();
int count = 0;
Int sum = 0;
for (int i = 0; i < size; I++ ) {
try {
sum += Integer.valueOf(s[i]);
++count;
} catch (Exception e) {}
}
return sum / count;
That should give you an. Average regardless of number, whole or real.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
This should be a fairly simple homework assignment, but I've been pounding my face on it for a while now ... When executed, it should just populate an array and find the mean and standard deviation. I'm getting an out of bounds exception, but only in the arrayDeviation method. Any direction would be appreciated.
import java.util.Scanner;
import java.util.Random;
public class StandardDeviation
{
//declare global variables
final static int ELEMENTS = 100;
public static void main(String [] args)
{
//declare variables
final int RANGE = 500;
int[] numList = new int[ELEMENTS];
Random rand = new Random();
//populate array
for(int count = 0; count < ELEMENTS; count++)
{
numList[count] = rand.nextInt(RANGE) + 1;
}
//call printArray
printArray(numList);
//call arrayAverage
double mean = arrayAverage(numList);
System.out.println("\nMean: " + mean);
//call arrayDeviation
double standardDeviation = arrayDeviation(numList, mean);
System.out.print("Standard deviation: " + standardDeviation);
} //end main
//output 10 elements per line
public static void printArray(int[] list)
{
final int ELEMENTS_PER_LINE = 10;
for(int count = 0; count < ELEMENTS; count++)
{
System.out.printf("%-4d", list[count]);
if ((count + 1) % ELEMENTS_PER_LINE == 0)
{
System.out.println();
}
}
}
//returns average as double
public static double arrayAverage(int[] list)
{
int sum = 0, count;
double average;
for(count = 0; count < ELEMENTS; count++)
{
sum = sum + list[count];
}
average =(double) sum / count;
return average;
}
//calculate and return standard deviation
public static double arrayDeviation(int[] list, double mean)
{
double sum = 0.0, standardDeviation;
int count;
for(count = 0; count < ELEMENTS; count++);
{
sum = sum + Math.pow((list[count] - mean), 2);
}
standardDeviation = Math.sqrt(sum / 2);
return standardDeviation;
}
} //end class
Staring at this code for like 10 minutes I couldn't see why it's giving that Exception.Pasting it in Netbeans and it instatly highlights an empty for-loop
public static double arrayDeviation(int[] list, double mean)
{
double sum = 0.0, standardDeviation;
int count;
for(count = 0; count < ELEMENTS; count++); //This semicolon is your
//problem
{
sum = sum + Math.pow((list[count] - mean), 2);
}
I am trying to use java to pass an array to get the mean, median,mode , max an min in java. I am currently having an issue passing the array to a function and return its value so i can output the results. I believe i have the loops correct to solve the mean median and mode but i cannot get them to send and receive as wanted. How can I pass the array and send back the values needed?
UPDATE: i have updated the code it will compile and i can input the number of years but i get several errors following after that. it is also not printing the outputs
Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i'
at java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2646)
at java.util.Formatter$FormatSpecifier.(Formatter.java:2675)
at java.util.Formatter.parse(Formatter.java:2528)
at java.util.Formatter.format(Formatter.java:2469)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at la5cs1110_woodspl_03.pkg17.pkg2016.La5cs1110_WoodsPl_03172016.main(La5cs1110_WoodsPl_03172016.java:56)
Java Result: 1
public static void main(String[] args) {
int i;
List<Double> hArray = new ArrayList<>();
int nYears = 0, y = 0;
double rMax = 0.00,rMin = 100.00;
//get input check if between 1-80
while(y == 0){
String userData = JOptionPane.showInputDialog
("Enter number of years");
nYears = Integer.parseInt(userData);
if (nYears > 1 && nYears <= 80 )
y = 1;
}
y = 0;
while(y <= nYears){
for(i = 0; i < 12; i++){
Random rand = new Random();
double rNum = rand.nextFloat() * (rMax - rMin) + rMin;
hArray.add(rNum);
}
double mean = getMean (hArray);
double median = getMedian (hArray);
double mode = getMode (hArray);
double max = getMaxValue(hArray);
double min = getMinValue (hArray);
System.out.printf("In year %i the Mean = %d , mode = %d, median = %d," +
" max = %d, min = %d", y , mean, median, mode, max, min);
y++;
}
}
private static double getMean(List<Double> hArray) {
double sum = 0;
for (int i = 0; i < hArray.size(); i++) {
sum += hArray.get(i);
}
return sum / hArray.size();
}
//Median
private static double getMedian(List<Double> hArray) {
int middle = hArray.size()/2;
if (hArray.size() %2 == 1) {
return hArray.get(middle);
} else {
return (hArray.get(middle-1) + hArray.get(middle)) / 2.0;
}
}
//Mode
public static double getMode(List<Double> hArray) {
double maxValue = 0, maxCount = 0;
for (int i = 0; i < hArray.size(); ++i) {
int count = 0;
for (int j = 0; j < hArray.size(); ++j) {
if (hArray.get(j) == hArray.get(i)) ++count;
}
if (count > maxCount) {
maxCount = count;
maxValue = hArray.get(i);
}
}
return maxValue;
}
public static double getMaxValue(List<Double> hArray){
double maxValue = hArray.get(0);
for(int i=1;i < hArray.size();i++){
if(hArray.get(i) > maxValue){
maxValue = hArray.get(i);
}
}
return maxValue;
}
public static double getMinValue(List<Double> hArray){
double minValue = hArray.get(0);
for(int i=1;i<hArray.size();i++){
if(hArray.get(i) < minValue){
minValue = hArray.get(i);
}
}
return minValue;
}
}
Your hArray is a List. You should convert it to an array first.
getMean(hArray.toArray)
Check out this.
This does not compile, you try to pass a Double to a method, which expects a double[]. So you have to change the parameter of your methods and use a List and just pass in the hArray (see Tibrogargan answer - i.e., you would have to modify each of your implementations) or do the following:
create a Double[]
Double[] hArray2 = hArray.toArray(new Double[hArray.size()]);
change your methods' signature, so that they expect an Double[]
private static double getMean(Double[] hArray) { ...}
pass hArray2 instead of hArray
double mean = getMean(hArray2);
// ...
That should be it.
Replace the section where you're trying to pass a single element from the array to your statistics functions with calls using the whole array and change the signature of the calls so they take a List<Double> param, not a double[]. Something like this:
double mean = getMean (hArray);
double median = getMedian (hArray);
double mode = getMode (hArray);
double max = getMaxValue(hArray);
double min = getMinValue (hArray);
//Mean
private static double getMean(List<Double> hArray) {
double sum = 0;
for (int i = 0; i < hArray.size(); i++) {
sum += hArray.get(i);
}
return sum / hArray.size();
}
See also: How do you calculate the variance, median, and standard deviation in C++ or Java?
Fix for median:
Copied directly from this above link with some minor modifications to use a List as a param
public Double median(List<Double> list)
{
Double[] array = list.toArray(new Double[list.size()]);
Arrays.sort(data);
if (data.length % 2 == 0)
{
return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
}
else
{
return data[data.length / 2];
}
}
Fix for mode:
public Double mode(List<Double> list)
{
java.util.TreeMap<Double,Integer> map = new java.util.TreeMap<>();
Double maxVal = null;
int maxCount = 0;
for (Double d : list) {
int count = 0;
if (map.containsKey(d)) {
count = map.get(d) + 1;
} else {
count = 1;
}
map.put(d, count);
if (count > maxCount) {
maxVal = d;
maxCount = count;
}
}
return maxVal;
}
I need to find the mean, median, mode, and range from an input file.
[input file has the numbers{60,75,53,49,92,71}]
I don't know how to print the calculations from the range out or calculate the mode.
It's pretty bad, I'm very new to Java.
It would be great if anyone could help me with it.
import java.io.*;
import java.util.*;
public class grades {
public static double avg(double[] num) {
double total = 0;
int j = 0;
for (; j < num.length; j++) {
total += num[j];
}
return (total / j);
}
public double getRange(double[] numberList) {
double initMin = numberList[0];
double initMax = numberList[0];
for (int i = 1; i <= numberList.length; i++) {
if (numberList[i] < initMin) initMin = numberList[i];
if (numberList[i] > initMax) initMax = numberList[i];
double range = initMax - initMin;
}
return range;
}
public static void main(String[] args) throws IOException {
double[] num = new double[12];
File inFile = new File("data.txt");
Scanner in = new Scanner(inFile);
for (int i = 0; i < num.length && in.hasNext(); i++) {
num[i] = in.nextDouble();
// System.out.println(num[i]);
}
double avg = grades.avg(num);
System.out.println("Arithmetic Mean = " + avg);
System.out.printf("Median = %.2f%n", grades.getMedian(num));
System.out.println("Range = " + range);
}
public static double getMedian(double[] num) {
int pos = (int) num.length / 2;
return num[pos];
}
}
I don't know how to print the calculations from the range out or calculate the mode.
You have already written a function to calculate the Range. Here is how you can print the Range.
System.out.println("Range = " + getRange(num));
Here is a quick code snippet to calculate the Mode:
public static double calculateMode(final double[] numberList) {
double[] cnts = new double[numberList.length];
double mode = 0, max = 0;
for (int i = 0; i < numberList.length; i++) {
/* Update Count Counter */
cnts[numberList[i]]++;
/* Check */
if (max < cnts[numberList[i]]) {
/* Update Max */
max = cnts[numberList[i]];
/* Update Mode */
mode = numberList[i];
}
}
/* Return Result */
return mode;
}
try sorting the element into an array.it will give following results:
[49,53,60,71,75,92]
suppose you stored it in array A.
int arrLength=A.length();
for(i=0,sum=0;i<arrlength;i++)
sum=sum+A[i]
mean=sum/arrLength;
median=A[arrLength/2]
I think you didn't sort the elements before finding median.
Do same thing to calculate range.It will be easier , I feel