Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
}
for (int i = 10 ; i > numbers.length ; i++)
{
int min = numbers [i];
if ( numbers [i] > min)
numbers [i] = input.nextInt();
}
System.out.println("the min values is " + min );
我停在这里..请帮助答案 0 :(得分:0)
至少要输入10个输入
Scanner input = new Scanner(System.in);
int min = InStream.range(0, 10)
.peek(i -> System.out.println("Please enter number"))
.map(i -> input.nextInt())
.min();
System.out.println("the min values is " + min);
你的代码有什么问题
for (int i = 10 ; i > numbers.length ; i++)
这不起作用,因为最后一个索引是[9]
而不是[10]
你也在递增而不是递减,你需要像
for (int i = numbers.length-1 ; i >= 0 ; i--)
您可以在调试器中看到此内容,或者阅读ArrayIndexOutOfBoundException: 10
答案 1 :(得分:0)
首先,你需要了解很多东西,你的代码是错误的。
方法1:
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
}
int min = numbers [0]; // Need to initialize it here outside the loop
for (int i = 1 ; i < numbers.length ; i++) // Need to count from 2nd element to the last
{
if ( numbers [i] < min) // changing condition if number is less than min
min = numbers [i]; // setting min to that number
}
System.out.println("the min values is " + min );
方法2: 在这里,我们检查使用输入值本身时的最小值。
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
boolean flagForMin = true;
int min;
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
if(flagForMin) {
min=numbers[i];
flagForMin=false;
} else {
if ( numbers [i] < min)
min = numbers [i];
}
}
System.out.println("the min values is " + min );
这些是使用for循环方法,你可以通过在循环和放大之前初始化来改变循环。在循环的最后一个语句中递增计数器。
EG:
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
boolean flagForMin = true;
int min;
int i = 0;
while( i < numbers.length)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
if(flagForMin) {
min=numbers[i];
flagForMin=false;
} else {
if ( numbers [i] < min)
min = numbers [i];
}
i++;
}
System.out.println("the min values is " + min );
答案 2 :(得分:0)
您不必使用2个for
循环。你甚至不需要一个数组。看看:
import java.util.*;
public class Main {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int min = Integer.MAX_VALUE;
for (int i = 0; i < 10; i++) {
System.out.println("Please enter number");
int number = input.nextInt();
if (number < min) {
min = number;
}
}
System.out.println("the min values is " + min);
}
}