vendredi 27 octobre 2017

Random int array not printing min and max

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



Aucun commentaire:

Enregistrer un commentaire