My task is to calculate the average of the Integers a user defines in an Array and print back to main using the method in my class file.
Currently I have both files to compile but can't seem to figure out why nothing is being printed. Please help, much appreciated!
Snippet of code in Test Program to examine:
// Print average of integers in array.
System.out.println("\nAverage of values in array =");
myArray.avgArray();
Snippet of code in Class Program to examine:
// Method to calculate average of integers in array.
public double avgArray()
{
int sum = 0;
for(int ctr = 0; ctr < limit; ctr++)
{
sum = sum + nrs[ctr];
}
double avg = sum /(double)limit;
return avg;
}
This code is my program for testing purposes:
import java.util.Scanner;
public class P5test
{
public static void main(String[] args)
{
// Set up Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Input size of array desired.
System.out.print("Size of array: ");
int size = keyboard.nextInt();
// Set up object.
P5class myArray = new P5class(size);
// Allow user to fill array.
System.out.println("\nEnter data for array:");
myArray.fillArray();
// Print contents of array.
System.out.println("\nContents of array:");
myArray.printArray();
// Print average of integers in array.
System.out.println("\nAverage of values in array =");
myArray.avgArray();
// Print postive values in array.
System.out.println("\nPositive values in array:");
myArray.pvaluesArray();
// Sort contents of array in ascending order.
System.out.println("\nSorted Array:");
myArray.sortArray();
myArray.printArray();
}
}
This code contains my class with the various methods I'll be implementing to main:
import java.util.Scanner;
public class P5class
{
// Constructor setting up empty array of size specified by user.
public P5class(int size)
{
limit = size;
nrs = new int[limit];
}
// Method to fill array.
public void fillArray()
{
// Set up Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
for(int ctr = 0; ctr < limit; ctr++)
{
System.out.print("Integer #" + (ctr+1) + ": ");
nrs[ctr] = keyboard.nextInt();
}
}
// Method to display contents of array.
public void printArray()
{
for(int ctr = 0; ctr < limit; ctr++)
{
System.out.println("Nrs[" + ctr + "] = " + nrs[ctr]);
}
}
// Method to calculate average of integers in array.
public double avgArray()
{
int sum = 0;
for(int ctr = 0; ctr < limit; ctr++)
{
sum = sum + nrs[ctr];
}
double avg = sum /(double)limit;
return avg;
}
// Method to examine if any positive values are present in array.
public void pvaluesArray()
{
int largest = nrs[0];
// Check to see if any other number in array is larger than first.
for(int ctr = 1; ctr < limit; ctr++)
{
if(nrs[ctr] > largest)
largest = nrs[ctr];
}
int sum = 0;
for(int ctr = 0; ctr < limit; ctr++)
{
sum = sum + nrs[ctr];
}
double average = (double)sum/limit;
for(int ctr = 0; ctr < limit; ctr++)
{
if(largest <= 0)
{
System.out.println("\nArray contains no positive integers.");
break;
}
else if (nrs[ctr] > 0)
{
System.out.println("Nrs[" + ctr + "] = " + nrs[ctr]);
}
}
}
// Method to sort array into ascending order.
public void sortArray()
{
for(int ctr0 = 0; ctr0 < limit-1; ctr0++)
{
// Make one pass of Bubble Sort.
for(int ctr = 0; ctr < limit-1; ctr++)
{
if(nrs[ctr] > nrs[ctr+1])
{
int temp = nrs[ctr];
nrs[ctr] = nrs[ctr+1];
nrs[ctr+1] = temp;
}
}
}
}
// Instance variables.
private int limit;
private int[] nrs;
}
Here is an example output of the program when Run:
----jGRASP exec: java P5test
Size of array: 5
Enter data for array:
Integer #1: 0
Integer #2: -9
Integer #3: 4
Integer #4: 7
Integer #5: 2
Contents of array:
Nrs[0] = 0
Nrs[1] = -9
Nrs[2] = 4
Nrs[3] = 7
Nrs[4] = 2
Average of values in array =
Positive values in array:
Nrs[2] = 4
Nrs[3] = 7
Nrs[4] = 2
Sorted Array:
Nrs[0] = -9
Nrs[1] = 0
Nrs[2] = 2
Nrs[3] = 4
Nrs[4] = 7
----jGRASP: operation complete.
It's returning a value, but you're not doing anything with it, try:
System.out.println("\nAverage of values in array = " + myArray.avgArray());
Or:
double avg = myArray.avgArray();
System.out.println("\nAverage of values in array = " + avg);
Or one of many other ways.
Or, instead of return avg;, you can simply print it out in the method with System.out.println(avg); and change the return type to void.
Related
I'm having trouble solving this homework problem. The problem wants me to create a program that reads user input of numbers and get the minimum and maximum values of those numbers.
Basically, the output should be as follows:
Enter number count: 10
Enter 10 numbers separated by space and press ENTER: 1 2 3 1 2 3 4 5 6 3
Min is 1 and has 2 occurrences
Max is 6 and has 1 occurrences
I was able to create methods to get the min and max. I don't know how to get the number of occurrences for the min and max with what I have. I also don't know how to get the scanner to read an input of integers on the same line.
import java.util.Scanner;
public class homework2
{
public int min(int[] array)
{
int min = array[0];
for (int i = 0; i < array.length; i++)
{
if (array[i] < min)
{
min = array[i];
}
}
return min;
}
public int max(int[] array)
{
int max = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] > max)
{
max = array[i];
}
}
return max;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the length of the array:");
int length = s.nextInt();
int[] myArray = new int[length];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < length; i++)
{
myArray[i] = s.nextInt();
}
}
}
Here's a simple program to do what you need:
public static void main(String[] args) {
int[] array = {1, 2, 3, 1, 2, 3, 4, 5, 6, 3}; // get your actual array
int first = array[0];
// initial values
int min = first;
int minOccurs = 1;
int max = first;
int maxOccurs = 1;
for(int i = 1; i < array.length; i++) {
int current = array[i];
if(current == min) {
minOccurs++;
} else if (current < min) {
min = current;
minOccurs = 1;
}
if(current == max) {
maxOccurs++;
} else if (current > max) {
max = current;
maxOccurs = 1;
}
}
System.out.println("Min is " + min + " and has " + minOccurs + " occurrences");
System.out.println("Max is " + max + " and has " + maxOccurs + " occurrences");
// prints: "Min is 1 and has 2 occurrences"
// prints: "Max is 6 and has 1 occurrences"
}
One way is to store counts of each one of the numbers you see using a HashMap. The number itself can be the key and the value can be the count that you are incrementing.
You can also use a Math lib to output a min and max from the set of keys (numbers)
https://www.geeksforgeeks.org/java-math-min-method-examples/
https://www.geeksforgeeks.org/count-occurrences-elements-list-java/
Good luck!
Once you know what the maximum is, just count how many times that occurs in the array.
However, as #Babyburger points out, you don't need an array to compute either the maximum or how many times it occurs.
Here is one way to parse a line of space separated integer numbers into int array:
int[] array = Arrays
.stream(scanner.nextLine().trim().split("\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
This should work for you. Let me know if you have questions:
import java.util.Scanner;
public class homework2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the length of the array:");
int length = s.nextInt();
System.out.println("Enter the elements of the array:");
int[] numbers = new int[length];
for (int i = 0; i < length; i++) {
numbers[i] = Integer.parseInt(s.next());
}
// take first element as max and min
int max = numbers[0];
int min = numbers[0];
// max and min exists so occurs at least once
int maxOcc = 1;
int minOcc = 1;
// start from i = 1; because we assigned the first element before
for (int i = 1; i < length; i++) {
int number = numbers[i];
if (number > max) {
max = number;
// start counting again
maxOcc = 1;
} else if (number == max) {
maxOcc++;
}
if (number < min) {
min = number;
// start counting again
minOcc = 1;
} else if (number == min) {
minOcc++;
}
}
System.out.println("max: " + max);
System.out.println("maxOcc: " + maxOcc);
System.out.println("min: " + min);
System.out.println("minOcc: " + minOcc);
}
}
Here is a solution to your problem. This takes a single string with numbers and spaces in-between, adds them to a dynamic array(ArrayList) and uses the min,max functions.
Do not initialize min and max=0 because we have to pick an integer from the provided list to start our comparison and that has to be the first element [0].
Code
import java.util.ArrayList;
import java.util.Scanner;
public class homework2 {
//Using static with functions because of the function calls in the Static
//main function
//Find the maximum number
public static int max(ArrayList<Integer> array) {
int max=array.get(0);
for(int i=0; i<array.size(); i++ ){
if(array.get(i)>max)
max = array.get(i);
}
return max;
}
//Calculate Maximum number's occurences
public static int maxOccur(int max,ArrayList<Integer> array){
int maxOccur=0;
for(int i=0; i<array.size(); i++ )
if(max==array.get(i)) maxOccur++;
return maxOccur;
}
//Find the minimum number
public static int min(ArrayList<Integer> array) {
int min=array.get(0);
for(int i=0; i<array.size(); i++ ){
if(array.get(i)<min)
min = array.get(i);
}
return min;
}
//Calculate Minimum number's occurences
public static int minOccur(int min,ArrayList<Integer> array){
int minOccur=0;
for(int i=0; i<array.size(); i++ )
if(min==array.get(i)) minOccur++;
return minOccur;
}
public static void main(String args[])
{
int minNum,maxNum;
Scanner in = new Scanner(System.in);
System.out.print("Enter the numbers separated by a space: ");
String number = in.nextLine();
//Separate the string by spaces in-between
String[] separatedNums = number.split(" ");
//Create a dynamic ArrayList to store any amount of integers
ArrayList<Integer> arrayList = new ArrayList<Integer>();
//Save the above string in the ArrayList after parsing into integer
for (String a : separatedNums)
arrayList.add(Integer.parseInt(a));
minNum=min(arrayList);
maxNum=max(arrayList);
//Output the results
System.out.println("Minimum Number="+minNum+" has
"+minOccur(minNum,arrayList)+" occurances");
System.out.println("Maximum Number="+maxNum+" has
"+maxOccur(maxNum,arrayList)+" occurances");
//Close the scanner
in.close();
}
}
This question already has answers here:
Need Java array help using scanner class to output an average and sort method
(4 answers)
Closed 6 years ago.
I have a method to output the highest value, lowest value, average value and I need a sort method. I have tried to put what is called a "bubble method" but it isn't working out. Anyone know other sort methods I can use?
import java.util.Scanner;
public class Arrayassignment {
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
System.out.println("Enter an intiger for array size.");
int number = sin.nextInt();
int array[] = new int[number];
System.out.println("Array size " + number + " initiated.\n");
System.out.println("Now enter the array intigers.");
for (int i = 0; i < number; i++) {
array[i] = sin.nextInt();
}
//System.out.println ( "\nLargest " + max (1, 3, 5) );
System.out.println("sorting" + sort(array));
System.out.println("The highest number in the array is " + max(array));
System.out.println("The smallest number in the array is " + min(array));
System.out.println("The average of the numbers in the array is " + avg(array));
}
public static int sort(int[] arg) {
for (int i = 1; i < arg.length - 1; i++) {
for (int j = i + 1; j < arg.length; j++) {
if (arg[i] > arg[j]) {
int arrange = arg[i];
arg[i] = arg[j];
arg[j] = arrange;
}
}
}
return arrange;
}
public static int max(int[] arg) {
if (arg.length == 0) {
System.out.println(" empty arguement list ");
return 0;
}
int largest = arg[0];
for (int i = 1; i < arg.length; i++) {
if (arg[i] > largest) {
largest = arg[i];
}
}
return largest;
}
public static int min(int[] arg) {
if (arg.length == 0) {
System.out.println(" empty arguement list ");
return 0;
}
int smallest = arg[0];
for (int i = 1; i < arg.length; i++) {
if (arg[i] < smallest) {
smallest = arg[i];
}
}
return smallest;
}
public static double avg(int... arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double average = (double) sum / arr.length;
return average;
}
}
There are many other sort methods you can use. The one you were trying to use is called "Bubble Sort" and is very expensive on large data sets unless they are somewhat ordered. I would recommend using selection sort or insertion sort for what you are trying to accomplish.
Here is a link to the many sorting algorithms you can implement: Sorting Algorithms
Here are some animations showing the process of these sorts (Highly recommend you look at these before implementing your algorithm):
Helpful animations
You can use any sorting method as your convenient and according to your requirement. After sorted the array you can easily pick up the minimum and maximum value from the sorted array, first element and the last element of the array.
For calculate the average you have to use separate method as you used or you can use static variable to calculate the total inside the sorting method.
Refer this code.
public class Arrayassignment {
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
System.out.println("Enter an intiger for array size.");
int number = sin.nextInt();
int array[] = new int[number];
System.out.println("Array size " + number + " initiated.\n");
System.out.println("Now enter the array intigers.");
for (int i = 0; i < number; i++) {
array[i] = sin.nextInt();
}
sin.close();
System.out.println("sorting");
printArray(array); //Before sort
sort(array);
printArray(array); //After sort
System.out.println("The highest number in the array is " + array[array.length - 1]);
System.out.println("The smallest number in the array is " + array[0]);
System.out.println("The average of the numbers in the array is " + avg(array));
}
public static void sort(int[] arg) {
int arrange;
for (int i = 0; i < arg.length - 1; i++)
for (int j = i + 1; j < arg.length; j++) {
if (arg[i] > arg[j]) {
arrange = arg[i];
arg[i] = arg[j];
arg[j] = arrange;
}
}
}
public static double avg(int... arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double average = (double) sum / arr.length;
return average;
}
public static void printArray(int[] arr) {
for (int value : arr) {
// print elements according to your convenient
System.out.println(value);
}
}
To print the array you have traversal through the array. See Above code method.
import java.util.ArrayList;
import java.util.Random;
public class Sorting
{
public static int numOfComps = 0,
numOfSwaps = 0;
public static void main(String[] args)
{
System.out.println("\nOriginal order:");
int size = 5;
ArrayList<Integer> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++)
{
list.add(i);
}
Random rand = new Random();
while(list.size() > 0)
{
int index = rand.nextInt(list.size());
System.out.print(list.remove(index) + " ");
}
System.out.println();
int[] test = convertIntegers(list);
int[] a = new int[5];
// Selection Sort
System.out.println("\n\nSelection Sort");
// Display copy of random generated number original order
System.out.println("\nOriginal order:");
System.arraycopy(test, 0, a, 0, test.length);
System.out.println(a + " ");
// Selection Sort method
selectionSort(a);
System.out.println("\nSorted order: ");
for(int element : a)
System.out.print(element + " ");
}
public static int[] convertIntegers(ArrayList<Integer> integers)
{
int[] num = new int[integers.size()];
for (int i=0; i < num.length; i++)
{
num[i] = integers.get(i).intValue();
}
return num;
}
public static void selectionSort(int[] array)
{
int startScan; // Starting position of the scan
int index; // To hold a subscript value
int minIndex; // Element with smallest value in the scan
int minValue; // The smallest value found in the scan
// The outer loop iterates once for each element in the
// array. The startScan variable marks the position where
// the scan should begin.
for (startScan = 0; startScan < (array.length-1); startScan++)
{
// Assume the first element in the scannable area
// is the smallest value.
minIndex = startScan;
minValue = array[startScan];
// Scan the array, starting at the 2nd element in
// the scannable area. We are looking for the smallest
// value in the scannable area.
for(index = startScan + 1; index < array.length; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
// Counts the number of values comparisons
numOfComps ++;
}
// Counts the number of values swaps
if(minIndex != startScan)
{
numOfSwaps ++;
}
// Swap the element with the smallest value
// with the first element in the scannable area.
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
System.out.println("\nNumber of comps = " + numOfComps);
System.out.println("Number of swaps = " + numOfSwaps);
}
}
How do I write code to copy random generated numbers to the selection sort method so that the random generated numbers can be displayed as an exact copy under the displayed heading "Selection Sort" as well as displaying the number of comparisons and swaps, and the sorted order? The code I have provided is not working properly. Thank you for any help.
for(int i = 0; i< arr.length; i++){
//generate random number here and assign to arr[i]
}
enter code here
now add another for loop to display everything inside the array, then if you want to see if it works sort it then use another loop.
What I'm trying to do is create an array based on values given by the user. The user has to give the length of the array plus the max and min values. I've managed to get the program to the point where it does output the correct amount of values (the correct length), but it just keeps outputting the exact same number (which is the max and min added). Based on research I did I tried converting them to a string so that wouldn't happen, but it still isn't working correctly. I've tried a couple of different methods including: Integer.toString, String.valueOf, and creating a whole new string. Any help would be greatly appreciated. Here's the code so far:
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Ask the user to enter the length of the array
System.out.println("Please enter the length of the array:");
int arraylength = input.nextInt();
//Ask the user to enter a max value
System.out.println("Please enter the max value:");
int max = input.nextInt();
//Ask the user to input the minimum value
System.out.println("Please enter the min value:");
int min = input.nextInt();
//Initialize the array based on the user's input
double [] userArray = new double[arraylength];
/**
*The program comes up with random numbers based on the length
*entered by the user. The numbers are limited to being between
*the minimum and maximum value.
*/
for (int i = min; i < userArray.length; i++) {
userArray[i] = Math.random() * max;
}
//This code is supposed to sort the array and print out all of the numbers in order,
//with minimum in the beginning and max in the end.
for (int i = 0; i < userArray.length; i++) {
selectionSort(userArray);
Integer.toString(min);
Integer.toString(max);
System.out.println(min + userArray[i] + max);
}
//This code uses the method average to find the average
average(userArray);
//Close Scanner
input.close();
}
public static double average(double[] data) {
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum = sum + data[i];
}
double average = sum / data.length;
return average;
}
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
//Find the minimum in the list[i...list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
//Swap list[i] with list[currentMinIndex] if necessary
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
Now, after I added that bit with the average calculation, the program did work once, though it did not compute the average (so it just created an array with min and max at the ends, sorted). It appears to be a fluke, because this is the exact same code and it hasn't done that since. Though maybe the average code somehow affected the rest?
If I understood you problem correctly, you need to change this line
System.out.println(min + userArray[i] + max);
to this:
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
My guess is, that it is java you are using. That tag would be helpful, too.
Edit:
You only need to sort your array once, and these do nothing: Integer.toString(min);
So the print routine could look like this:
selectionSort(userArray);
for (int i = 0; i < userArray.length; i++) {
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
}
I have two files that I am using for my Array median code. The first file( ArrayMedian.java) is used to collect and then calculate the median, the second file is the tester file ( ArrayMedianTest.java)
I was supplied with some source code and needed to modify it accept a set range for each number in the dataset. I got that part done and the random range displays, but now when I get to he array it no longer calculates, I really can't put my finger on what is going wrong.
Another thing I am trying to do is in the ArrayMedian, is put a while loop in there to make it terminate if a '0' is input for the dataset, but it does not seem to want to work in that file, could it be due to no main in the file?
package bonus2.u06.exercise.ex3;
import java.util.Scanner;
public class ArrayMedian {
private int[] arr; // just declare array
Scanner keyboard; // shared field
// initialize keyboard and array
public void init() {
keyboard = new Scanner( System.in );
System.out.print("Enter the dataset size: ");
int size = keyboard.nextInt(); // must be odd number
arr = new int[ size ]; // instantiate
}
// Randomize the array
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
}
}
// find the median of array
public int calcMedian() {
int half_length = arr.length/2;
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] > arr[j])
count++;
}
if (count == half_length) {
//<========= terminate this method
return arr[i];
}
}
return 0;
}
}
ArrayMedianTest:
package bonus2.u06.exercise.ex3;
public class ArrayMedianTest {
public static void main(String args[]) {
// instantiate
ArrayMedian obj = new ArrayMedian();
// execute all methods
obj.init();
obj.getRange();
int median = obj.calcMedian();
System.out.println("\nmedian : " + median);
System.out.println("\n--- done ---");
}
}
Turn out, your algorithm works perfectly fine, except in the getRange() method, you forgot to set the values of the array, so the array is an array of zeros. Here is how it should look:
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
arr[i] = myRnd; // <-- You missed this line right here!
}
}
Also, as a recomendation, if you want to put code in stackoverflow, it has to have a spacing of four at the begining of the line plus any indenting you might use. Good luck programming!