我写了这段代码,以从用户填充的数字数组中找到最大和最小的数字,但是它不起作用

时间:2018-09-12 11:57:29

标签: java arrays loops

我正在获取功能(最小或最大)和填充数组的用户输入。然后根据输入函数,我想比较连续的元素并找到最小或最大的数字。我不明白为什么以及如何修正我的代码。

该代码可以运行,但无法正常运行。最小和最大数字都是错误的

import java.util.Scanner;

public class App {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Are you trying to find the Smallest or Largest number in an array of numbers? S/L");
        String functionExpected = sc.nextLine();

        System.out.println("How many elements you plan to enter? ");
        int lengthOfArray = sc.nextInt();

        // Populating array according to input and length
        int[] numbersArray = new int[lengthOfArray];
        for (int i = 0; i < numbersArray.length; i++) {
            System.out.println("Enter an element here: ");
            numbersArray[i] = sc.nextInt();
        }
        // Print out array
        for (int i = 0; i < numbersArray.length; i++) {
            System.out.print(numbersArray[i] + " ");
        }
        System.out.println();

        if (functionExpected.equalsIgnoreCase("L")) {
            int temp = 0;
            System.out.println("We are going to find the largest number in the array of elements you enter!");
            for (int i = 0; i < numbersArray.length; i++) {
                for (int j = 1; j < numbersArray.length;) {
                    if (numbersArray[i] > numbersArray[j]) {
                        temp = numbersArray[i];
                        break;
                    } else {
                        temp = numbersArray[j];
                        break;
                    }
                }
            }

            System.out.println("Largest of the three numbers is : " + temp);
        }
        if (functionExpected.equalsIgnoreCase("S")) {
            int temp = 0;
            System.out.println("We are going to find the smallest number in the array of elements you enter!");
            for (int i = 0; i < numbersArray.length; i++) {
                for (int j = 1; j < numbersArray.length;) {
                    if (numbersArray[i] > numbersArray[j]) {
                        temp = numbersArray[j];
                        break;
                    } else {
                        temp = numbersArray[i];
                        break;
                    }
                }
            }
            System.out.println("Smallest of the three numbers is : " + temp);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

正如评论所指出的那样,完全不需要内部循环(基于j)。

int temp = numbersArray[0];
for (int i = 1; i < numbersArray.length; i++) {
    if(numbersArray[i] > temp) {
        temp = numbersArray[i]
    }
}

只需在最小/最大的if中将>切换为<。