mercredi 6 février 2019

How can I run a simple for loop instead of recurring if-statements?

I'm am trying to write a piece of code that reads 5 inputs and then works out the lowest input given through a for-loop. Currently I have written 4 if-statements to make this happen, however I'm wondering if I can write a simple for-loop for this. The point is not to use an array to save the input. This is my code:

    int smallestNumb = 0;
    int largestNumb = 0;

    Scanner numbIn = new Scanner(System.in);
    System.out.println("Enter 5 numbers");
    int number1 = numbIn.nextInt();
    int number2 = numbIn.nextInt();
    int number3 = numbIn.nextInt();
    int number4 = numbIn.nextInt();
    int number5 = numbIn.nextInt();

    smallestNumb = number1;

    if(smallestNumb > number2) {
        smallestNumb = number2;
    }
    if(smallestNumb >  number3) {
        smallestNumb = number3;
    }
    if(smallestNumb > number4) {
        smallestNumb = number4;
    }
    if(smallestNumb > number5){
        smallestNumb = number5;
    }

Aucun commentaire:

Enregistrer un commentaire