我正在获取函数(最小或最大)和填充数组的用户输入。然后根据输入函数我想比较连续的元素并找到最小或最大的数字。我无法理解为什么以及如何修复我的代码。
代码运行但没有按预期工作。最小和最大的数字都是错误的
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);
}
哔哔one
相关分类