如何运行简单的for循环,而不是重复执行if语句?

时间:2019-02-06 22:08:41

标签: java for-loop if-statement

我正在尝试编写一段代码,该代码读取5个输入,然后计算出通过for循环给出的最低输入。目前,我已经编写了4个if语句来实现这一目标,但是我想知道是否可以为此编写一个简单的for循环。关键是不要使用数组来保存输入。这是我的代码:

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

4 个答案:

答案 0 :(得分:0)

您可以循环提问5次,然后每次检查新问题是否较小

int smallestNumb = Integer.MAX_VALUE, choice;
Scanner numbIn = new Scanner(System.in);

for(i = 0 ; i < 5 ; i++){
    System.out.println("Enter a number");
    choice = numbIn.nextInt();
    if(smallestNumb > choice) {
        smallestNumb = choice;
    }
}

System.out.println(smallestNumb);

答案 1 :(得分:0)

public static void main(String[] args) {
    int smallestNum = Integer.MAX_VALUE;

    Scanner numIn = new Scanner(System.in);
    System.out.println("Enter 5 numbers");

    int num = 0;

    for(int i = 0; i < 5; i++) {
        num = numIn.nextInt();
        if(num < smallestNum)
            smallestNum = num;
    }

    System.out.println(smallestNum);
}

答案 2 :(得分:0)

您可以使用带有var args的方法(我不处理空的情况):

public int getSmallest(int... numbers){
  int smallestNumb = numbers[0];
  if (numbers.length==1) 
    return smallestNumb;

  for (int i=1; i<numbers.length; i++){
    smallestNumb = Math.min(smallestNumb, numbers[i]);
  }
  return smallestNumb;
}

并使用它:

int smallest = getSmallest(number1, number2, number3, number4, number5)

或链Math.min(),例如:

smallestNumb = number1;
smallestNumb = Math.min(smallestNumb, number2);
smallestNumb = Math.min(smallestNumb, number3);
smallestNumb = Math.min(smallestNumb, number4);
smallestNumb = Math.min(smallestNumb, number5);

答案 3 :(得分:0)

您可以即时确定最小的数字:

{{1}}