How to find the largest value from an array in Java? - java

I am writing a program which can tracking three dices' total appears.Here are my codes:
import java.util.*;
class dice{
public static void main (String[] args){
Random rnd = new Random();
int[] track = new int[19];
for (int roll=0; roll<10000; roll++){
int sum=0;
for(int i = 0; i < 3; i++) {
//roll the 6-face dice
int n = rnd.nextInt(6) + 1;
sum+=n;
}
++track[sum];
}
System.out.println("Sum\tFrequency");
for(int finalSum=3; finalSum<track.length;finalSum++){
System.out.println(finalSum+"\t"+track[finalSum]);
}
System.out.println("the largest frequency is %d", //how to find it?)
}
}
Now I am almost done. But how can I find the largest appearance and print it separately? Thank you.

You can try below code:
Arrays.sort(arr);
System.out.println("Min value "+arr[0]);
System.out.println("Max value "+arr[arr.length-1]);

public int largest(int[] myArr) {
int largest = myArr[0];
for(int num : myArr) {
if(largest < num) {
largest = num;
}
}
return largest;
}
Set the variable largest to the first item in the array. Loop over the array, whenever the current num you're in is bigger than the current largest value, set largest to num.

Related

How to find the min and max values with number of occurances for each

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();
}
}

How to copy random generated numbers to the selection sort method. (JAVA)

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.

getting max value in an array

simple question. I'm new to using arrays and multiple classes and could use some help. Basically, my program is supposed to sort the array in ascending order(done) and then output the max number. But I have to use two classes (client class and other) I always seem to have trouble bringing the code from one class and implementing it into another. I'm trying to implement my getMaxValue into the client class to output it. I'm sure I'm missing something simple or overlooking it. Any help or suggestions would be appreciated!
First Class:
public class Chapter8Number16{
public static void selectionSort(int[]array){
int temp;
int max;
int numbers[] = new int[0];
for(int i = 0; i< array.length;i++){
max=indexOfLargestElement(array, array.length-i);
temp=array[max];
array[max]=array[array.length-i-1];
array[array.length-i-1]=temp;
}
}
private static int indexOfLargestElement(int[]array,int size){
int index=0;
for(int i = 1; i<size;i++){
if (array[i]>array[index])
index=i;
}
return index;
}
public static int getMaxValue(int[] array){
int maxValue = array[0];
for(int i=1;i < array.length;i++){
if(array[i] > maxValue){
maxValue = array[i];
}
}
return maxValue;
}
}
Client Class:
import java.util.Random;
public class Chapter8Number16Client {
public static void main(String[]args){
int[]numbers=new int[6];
int highest=0;
Random rand = new Random();
for(int i=0;i<numbers.length;i++)
{
numbers[i]=rand.nextInt(100)+1;
highest += numbers[i];
}
Chapter8Number16.selectionSort(numbers);
Chapter8Number16.getMaxValue(array);
System.out.println("The sorted array: ");
for(int i=1; i<numbers.length;i++)
System.out.print(numbers[i] + "\t");
System.out.println();
System.out.println();
System.out.println("The highest number is: ");
System.out.println(maxValue[i]);
}
}
Your code has compilation issues, anyways, below code should help:
System.out.println("The highest number is: "+Chapter8Number16.getMaxValue(numbers));
You must save the maxvalue into a variable like
int max = Chapter8Number16.getMaxValue(array);
ora if you want just to print it:
System.out.println(Chapter8Number16.getMaxValue(array));
The maximum value is returned by your function,so you must assign it to a variable
int max = Chapter8Number16.getMaxValue(numbers);
System.out.println(max);

Program only works whe negative numbers entered in array last

For some reason my computePositiveSum final output for "The sum of the positive numbers" is wrong when a negative number is entered before any positive numbers. It seems like what's happening is instead of ignoring the negative numbers it subtracts it's sum from the total. So if my input was (-4,2,3) it would say the sum of positive numbers was 1. I'm not really sure what is wrong with the method.
/* Description: Write a program that reads in a sequence of numbers
(not necessary integers) from standard input until 0
is read, and stores them in an array. This is done
using iteration (choose for, while, or do while loop).
You may assume that there will not be more than 100 numbers.*/
import java.util.Scanner;
import java.text.DecimalFormat;
public class Assignment2
{
public static void main (String[] args)
{
Scanner scan= new Scanner(System.in);
int count=0;
double[] num= new double[100];
for(int i=0;i<num.length;++i)
{
num[i]= scan.nextDouble();
if (num[i] == 0) {
break; }
count++;
}
double min= findMin(num,count);
double pos= computePositiveSum(num, count);
int c= countNegative(num,count);
DecimalFormat fmt = new DecimalFormat ("0");
DecimalFormat fmt2 = new DecimalFormat ("$0.00");
System.out.println("The minimum number is " +fmt.format(min));
System.out.println("The sum of the positive numbers is "+fmt2.format(pos));
System.out.println("The total number of negative numbers is " +c);
}//End Main
public static double findMin(double[] num, int count)
{
double min = num[0];
for(int i=1;i<count;i++){
if(num[i] < min)
{
min = num[i];
}
}
return min;
}//end findMin
public static double computePositiveSum(double[] num, int count)
{
double pos=num[0];
for(int i=1;i<count;i++){
if(num[i] > 0)
{
pos=pos+num[i];
}
}
return pos;
}
public static int countNegative(double[] num, int count)
{
double a=num[0];
int c=0;
for(int i=0;i<count;i++){
if(num[i] < 0)
{
c++;
}
}
return c;
}//end countNegative
}
You are assigning to the actual sum pos the value of the first element in the array. So if the first element is negative it will be added to the sum (there is no check in the code to know if it's positive or not).
To fix this, initialize the sum pos (by the way, it is not a descriptive name) with 0. Then iterate in the for loop from 0, not from 1.
public static double computePositiveSum(double[] num, int count)
{
double pos = 0;
for (int i = 0; i < count; i++) {
if (num[i] > 0) {
pos = pos + num[i];
}
}
return pos;
}
Note: I would recommend you to name your variables with a more descriptive name. I would have declared pos with the name sum. Of course this has nothing to do with the result, but is useful for people to understand the code.
because you are doing
double pos = num[0];
then going through the remainder of the array you need to do
double pos = 0;
for (int i = 0; ...)
You're not checking the first element of the array
public static double computePositiveSum(double[] num) {
double sum = 0.0;
for(double d : num) {
if(d > 0) {
sum += d;
}
}
return sum;
}
You need to check if element 0 is greater than zero.

Generating data for an array via Random class and sorting

Use the Random class to get numbers from 0 to 99 and store them into the array. Use a for loop to get each random number, store each into the array, and print each value.
Then use the bubble sort to sort the array, and print out the stored array.
here is my program
import java.util.Random;
public class Randomness
{
public static void main(String[] args)
{
Random randomNum = new Random();
for (int number = 0; number <= 99; ++number)
{
int num = randomNum.nextInt(100);
System.out.print(num + " ");
int numValues = num;
int [] values = new int[numValues];
boolean swap;
do
{
swap = false;
int temp;
for (int count = 0; count < numValues-1; count++)
if (values[count] > values[count+1])
{
temp = values[count];
values[count] = values[count+1];
values[count+1] = temp;
swap = true;
}
} while (swap);
System.out.print(values[count] + " ");
}
}
}
i get error
System.out.print(values[count] + " "); array required, but Random found.
please help!
You aren't creating any random values in your array. You are creating an array of random length (between 0 to 99). You need to initialize each element of your array with a random:
Random randomNum = new Random();
int numValues = 100;
int[] values = new int[numValues];
for (int number = 0; number < numValues; ++number)
{
int num = randomNum.nextInt(100);
System.out.print(num + " ");
values[number] = num;
}
Then do the bubble sort.

Categories