我正在获取函数(最小或最大)和填充数组的用户输入。然后根据输入函数我想比较连续的元素并找到最小或最大的数字。我无法理解为什么以及如何修复我的代码。代码运行但没有按预期工作。最小和最大的数字都是错误的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); }
1 回答
哔哔one
TA贡献1854条经验 获得超8个赞
正如评论所指出的,内循环(基于 j)是完全没有必要的。
int temp = numbersArray[0];
for (int i = 1; i < numbersArray.length; i++) {
if(numbersArray[i] > temp) {
temp = numbersArray[i]
}
}
只需在 if 中将 > 切换为 < 即可获得最小/最大。
添加回答
举报
0/150
提交
取消