Random int array not printing min and max - java

I am new to Java (and coding in general). I need to write a method that gets an integer, creates an array made of random numbers of the length of the integer, range 1-50
(inclusive) and finds the maximum and minimum number.
I was able to fill the array with random numbers. However, my min and max are not printing. I have been looking at this for hours with no luck - any advice would be very helpful! Thank you.
import java.util.Scanner;
import java.util.Random;
class MinMax {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
//user input a number
System.out.println("Please enter an integer from 1 to 50: ");
int userNum = in .nextInt();
System.out.println();
int x;
int randNum;
int y;
//create random numbers and print
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println(randNum);
int[] array = new int[userNum];
for (x = 1; x < 1; x++) {
array[x] = randNum;
System.out.println(array[x]);
//find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
//find min
} else if (array[s] < smallest) {
System.out.println(smallest);
} //for
} //if
} //for
} //for
} //main method
} //class

//find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
//find min
} else if (array[s] < smallest) {
System.out.println(smallest);
} //for
} //if
Look closely at this code. Inside the loop, you are setting
largest = array[s];
and then immediately checking
if (array[s] > largest)
Of course it's not, you just made them equal!
Put the assignments inside the conditions:
// Remove largest = array[s]
if (array[s] > largest) {
largest = array[s];
}
Similarly for smallest.
Note: I would recommend against commenting on closing braces. Note only is it unnecessary effort, it is confusion-prone: in this snippet of code above, the //for and //if are reversed. Additionally, it doesn't tell you which "if" or "for" it is closing.
Simply looking at the indentation is an easier way.

Your program does not fill the array with random numbers. It creates several arrays and fills each of them with a single number. You should change this part of the program:
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println(randNum);
int[] array = new int[userNum];
for (x = 1; x < 1; x++) {
array[x] = randNum;
System.out.println(array[x]);
/* min-max code */
}
}
to this:
Random r = new Random();
int[] array = new int[userNum];
for (int i = 0; i <= userNum; i++) {
array[i] = r.nextInt(50) + 1;
System.out.println(array[i]);
}
/* min-max code */
This will create a single array, fill it with random numbers, and print each element of the array, which seems to be what you intended.
The code that finds the minimum and maximum is also incorrect.
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
} else if (array[s] < smallest) {
System.out.println(smallest);
}
}
You should only set largest or smallest when array[s] is actually the largest or smallest value in the array so far. To check whether or not this is the case, you can use Math.min() and Math.max(), which return the smallest or largest, respectively, of two values.
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = Math.max(array[s], largest);
smallest = Math.min(array[s], smallest);
}
System.out.println(largest);
System.out.println(smallest);

This is what you looking for::
import java.util.Scanner;
import java.util.Random;
public class MinMax {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
// user input a number
System.out.println("Please enter an integer from 1 to 50: ");
int userNum = in.nextInt();
System.out.println();
int x;
int randNum;
int y;
int[] array = new int[userNum];
// create random numbers and print
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println("number " + i + ":: " + randNum);
array[i - 1] = randNum;
}
// print array
for (int s = 0; s < array.length; s++) {
System.out.println("array[" + s + "] number :: " + array[s]);
}
// find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
if (array[s] > largest) {
largest = array[s];
// find min
} else if (array[s] < smallest) {
smallest = array[s];
}
}
System.out.println("\nLargets Number:: " + largest);
System.out.println("Smallest Number:: " + smallest);
} // main method
} // class
Don't confuse too much when you are using loops.Some mistakes you done while writing code.
1> You have declared array int[] array = new int[userNum];
in for loop. which mean it will create as much arrays as loop iterate. and not accessible outside loop.
2> Same with variables largest and smallest int largest = array[0];
int smallest = array[0];
3> for (x = 1; x < 1; x++) control never ever enter the loop since your condition x<1 is never satisfy because you have initiated x=1 and and it will never ever be less than 1 as in condition (x<1).
Suggestion :: To find largest you have to traverse through array and check every element for largest and smallest and store it in separate variable rather than printing it at every check.
In my code i have used three for loops::
1>> to generate and print random number. In same loop i'm filling array with generated number.
2>> Here just printing array separately for better presentation in output.
3>> Finding largest and smallest by assigning values in if block if they satisfy condition.
I hope this will help you to understand code.

Related

Random array elements

I'm very new to coding.
I'm writing this code and I'm struggling because I need to make a code that makes an array with 8 random integers and then it swaps the largest integer with the first number in the array.
When doing this though I'm getting an error and I cannot seem to fix it.
import java.util.Scanner;
import java.util.Random;
public class finalExam {
public static void main(String []args) {
Scanner input = new Scanner(System.in);
Random spinner = new Random();
int [] userInputs = new int [8];
for (int i = 0; i < userInputs.length; i++) {
userInputs[i] = spinner.nextInt(100)+1;
System.out.println(userInputs[i]);
}
int largest = userInputs[0];
for(int j = 1; j < userInputs.length; j++) {
if(userInputs[j] > largest)
largest = userInputs[j];
}
System.out.println("Your largest number is: " + largest);
int holder;
int [] arr = new int[101];
for (int m = 0; m <= arr.length; m++) {
holder = largest;
userInputs[0] = userInputs[largest];
holder = userInputs[0];
}
}
}
The error comes from the last bit of your code. userInputs[largest] is out of bound because the array is only 8 integers long (while largest can have a value of 100).
Since you need the position of the largest number, you'll have to save it in largestPosition when you identify which number is the largest, like so:
int largest = userInputs[0];
int largestPosition = 0;
for(int j = 1; j < userInputs.length; j++) {
if(userInputs[j] > largest){
largest = userInputs[j];
largestPosition = j;
}
}
That said, the loop which you used at the end also isn't needed here. You could just swap the first value of the array with the largest one using this method:
int first = userInputs[0];
userInputs[0] = largest;
userInputs[largestPosition] = first;

How to find the smallest and largest element in an array of random integers?

Hi guys I'm writing a program to do the thing below. I can't figure out how to write it. I've only figured out how to do generate the random ints but other than that I'm completely lost. I would love it if you guys help me!
program that creates an array of size 10, and fills it with random integers between 1 and 100. The program then outputs the largest and the smallest integers in the array.
This is what I have so far:
public class LargestSmallest
{
public static void main (String [] args)
{
int [] number = new int [2];
System.out.println ("The random numbers generated are: ");
for (int count =0; count < number.length ; count++)
{
number[count] = (int)(Math.random()*100+1);
System.out.println (number[count]);
}
}
}
At the beginning of the code, declare a couple of variables to keep track of your minimum and maximum. Set the one keeping track of your minimum to a value that will be higher than any value you will generate (so that the first time it's checked, it will be guaranteed to update) and the one keeping track of the maximum to a value smaller than any value you will generate.
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
As you generate the random numbers, do a quick comparison and update your new numbers.
if (number[count] < min)
min = number[count];
if (number[count] > max)
max = number[count];
Alternatively, if you're required to generate the numbers and THEN find the min and max, write a simple for loop to iterate through the array and do the same thing.
for (int i = 0; i < number.length; i++) {
/* Comparison and storage code here */
}
This should work for your random function:
public static void main(String[] args)
{
int[] number = new int[100];
System.out.println("The random numbers generated are: ");
for (int count = 0; count < number.length; count++)
{
number[count] = (int) (Math.random() * 100 + 1);
System.out.println(number[count]);
}
int min = 101;
int max = 0;
for (int i = 0; i < number.length; i++)
{
if (number[i] < min)
{
min = number[i];
}
if (number[i] > max)
{
max = number[i];
}
}
System.out.println("Max:" + max);
System.out.println("Min:" + min);
}

Java find lowest number messes up when inputting negative numbers

I have to find the lowest number in an array. It works when I manually make an array, but when I use a scanner to get numbers from the user and they put in a negative number, it does not consider the negative sign and acts as if the number is a positive number. Is there something scan.nextInt does to negative numbers that causes this?
System.out.println("Enter an array size.");
size = scan.nextInt();
int[] numbers = new int[size];
System.out.println("Enter each integer in the array and press Enter after each one.");
for(int i = 0; i < size; i++)
{
numbers[i] = scan.nextInt();
}
for(int j = 0; j < size; j++)
{
smallest = numbers[0];
if (numbers[j] < smallest)
{
smallest = numbers[j];
}
}
System.out.println("Smallest Number is " + smallest);
This is the code for reference
You reset the smallest variable every loop.
Try initializing it before the loop.
smallest = numbers[0];
for(int j = 0; j < size; j++)
{
if (numbers[j] < smallest)
{
smallest = numbers[j];
}
}
You have to initialize your smallest out of the loop, preferably at the beginning. And if you are going to find the smallest, assign it a big value (if largest, assign a very small value);
int smallest = Integer.MAX_VALUE;
Integer.MAX_VALUE is the greatest possible value that you can assign to an integer in Java.
And always remember to release the resources. You have to close the scanner object when you're done with it.
scan.close(); // always release resources
Here is the demo code;
Demo Code
import java.util.Scanner;
public class FindLowest {
public static void main(String[] args) {
// initialization of variables
int size;
Scanner scan = new Scanner(System.in);
int smallest = Integer.MAX_VALUE;
System.out.println("Enter an array size.");
size = scan.nextInt();
int[] numbers = new int[size];
System.out.println("Enter each integer in the array and press Enter after each one.");
for (int i = 0; i < size; i++) {
numbers[i] = scan.nextInt();
}
scan.close(); // always release resources
for (int j = 0; j < size; j++) {
// smallest = numbers[0]; // dont initialize here, initialize at beginning
if (numbers[j] < smallest) {
smallest = numbers[j];
}
}
System.out.println("Smallest Number is " + smallest);
}
}
Output Sample
Enter an array size.
5
Enter each integer in the array and press Enter after each one.
1
-2
3
-4
5
Smallest Number is -4

Minimum number and its index in a random array

The problem is to find the minimum number in the random array 50 numbers. It should be between 0-100 and its index. I don't know what's the wrong with my code. It prints more than one minimum value and I haven't found a way to make limit to the array:
You are not generating random number properly.
To find a random number in range 0..99,use
Random r = new Random();
int randomInt = r.nextInt(100);
Try this
public class RandomTest {
public static void main(String[] args) {
int arr[] = new int[50];
Random r = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = r.nextInt(100);
System.out.println(arr[i]);
}
int minimum = arr[0];
for (int j = 1; j < arr.length; j++) {
if (minimum > arr[j])
minimum = arr[j];
}
System.out.println("Minimum value-->" + minimum);
}
}
Output
Output will vary as per the generated number.In my case,I got
Minimum value-->4
You shouldn't print inside the "for" loop.
The loop determines which value is the minimum.
Once it has ended, print the result.
for{
...
...
}
System.out.println(Minimum);
You can use the following code:
int[] a = ...; // after random for
int min = a[0];
int minIndex = 0;
for(int i = 1; i < a.length(); i++) {
if(a[i] < min) {
min = a[i];
minIndex = i;
}
}
System.out.println(minIndex);

Java - Finding minimum number

The following code is supposed to read through some numbers and put ' <== Smallest number' next to the smallest. What's my problem here? It doesn't seem to be working! Every time it seems to assign the wrong number as the minimum.
import java.util.ArrayList;
import java.util.Scanner;
public class arrayex1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter numbers: ");
for (int i = 0; i < 10; i++) {
int num = input.nextInt();
numbers.add(num);
}
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(findMin(numbers)) == i) { // If the 'smallest' index value is equal to i.
System.out.println(numbers.get(i) + " <== Smallest number");
} else {
System.out.println(numbers.get(i));
}
}
}
public static int findMin(ArrayList<Integer> n) {
int min = 0; // Get value at index position 0 as the current smallest.
for (int i = 0; i < n.size(); i++) {
if (n.get(i) < min) {
min = i;
}
}
return min;
}
}
if (numbers.get(findMin(numbers)) == i) { // If the 'smallest' index value is equal to i.
By calling numbers.get() you fetch the value of the slot at i.
The variable min in findMin() is actually the index of the minimum number in n.
Change this:
if (n.get(i) < min)
to:
if (n.get(i) < n.get(min))
Store the return value of findMin() before entering the for loop:
final int min_idx = findMin(numbers);
for (int i = 0; i < numbers.size(); i++) {
if (min_idx == i) { // If the 'smallest' index value is equal to i.
System.out.println(numbers.get(i) + " <== Smallest number");
} else {
System.out.println(numbers.get(i));
}
}
You can use collection sort method for sorting an list. Documentation
After the sort first element will be the smallest one
Here is an improved, working sample (though without the Scanner inputs for easy testing):
public static void main(String[] args){
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(7);
numbers.add(3);
int minIndex = findMin(numbers);
for(int i = 0; i < numbers.size(); i++){
if(minIndex == i){ // If the 'smallest' index value is equal to i.
System.out.println(numbers.get(i) + " <== Smallest number");
}else{
System.out.println(numbers.get(i));
}
}
}
public static int findMin(ArrayList<Integer> n){
int minValue = Integer.MAX_VALUE; // Get value at index position 0 as the current smallest.
int minIndex = -1;
for(int i = 0; i < n.size(); i++){
if(n.get(i) < minValue){
minIndex = i;
}
}
return minIndex;
}
There was some confusion as to if the findMin method returned the minimum value, or the minimum index. It now returns the minimum index. findMin is also now called only once, not for every iteration in the loop, which is a little cleaner (and slightly faster).
if (n.get(i) < min)
should be:
if (n.get(i) < n.get(min))
See it
Just change the following code and it will work for sure.
**if (numbers.get(findMin(numbers)) == numbers.get(i))**
{ // If the 'smallest' index value is equal to i.
System.out.println(numbers.get(i) + " <== Smallest number");
}
and
public static int findMin(ArrayList<Integer> n)
{
int min = 0; // Get value at index position 0 as the current smallest.
for (int i = 0; i < n.size(); i++)
{
**if (n.get(i) < n.get(min))**
{
min = i;
}
}
return min;
}
You see the unexpected behavior because you don't obey the contract for List.get(). The method expects an index as argument and returns you the value. You should not compare the value returned by get() to an index.
Also, in your findMin() method you should initialize min to Integer.MAX_VALUE.

Categories

Resources