猿问

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

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


代码运行但没有按预期工作。最小和最大的数字都是错误的


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

        }


米脂
浏览 161回答 1
1回答

哔哔one

正如评论所指出的,内循环(基于 j)是完全没有必要的。int temp = numbersArray[0];for (int i = 1; i < numbersArray.length; i++) {&nbsp; &nbsp; if(numbersArray[i] > temp) {&nbsp; &nbsp; &nbsp; &nbsp; temp = numbersArray[i]&nbsp; &nbsp; }}只需在 if 中将 > 切换为 < 即可获得最小/最大。
随时随地看视频慕课网APP

相关分类

Java
我要回答