[英]How to display numbers less than 3 from an Array
我应该编写一个接受 6 个用户输入并显示小于 3 的数字的程序。我不知道问题出在哪里,也找不到任何帮助。
public class Apples {
public static void main(String [] args{
double [] numList = new double [6];
Scanner scan = new Scanner(System. in);
for (int i = 0; i<6; i++){
numList[i]=scan.nextDouble(); //user input
}
Arrays.sort(numList[i]); //sort user input
for (numList < 3)
System.out.println(numList);
}
}
}
我会这样:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for(int i=0; i<6; i++) {
double number = scan.nextDouble();
if(number < 3.0) {
System.out.println(number);
}
}
}
所以:
for(numList < 3)
不是正确的 Java 语法。 您可能的意思是if(number < 3)
这可能是由于复制/粘贴造成的,但存在一些问题,让我向您展示一种解决方案:
public static void main(String [] args){
double [] numList = new double [6];
Scanner scan = new Scanner(System. in);
// until here everything is fine
for (int i = 0; i<numList.length; i++){ // just a hint: use the array's length. Maybe you want to change the array one day and add 20 numbers to it..
numList[i]=scan.nextDouble(); // you forgot the . and it is called nextDouble() (capital D)
}
Arrays.sort(numList); // sorting is fine, just make sure you sort the whole array (not just one element)
for (int i = 0; i<numList.length; i++){ // here I assume you want to print every element smaller than 3, so you still need to iterate over the whole array (maybe the user inputs only twos
if(numList[i]<3){ // test if the number is smaller than 3
System.out.println(numList[i]); // and print it
}
}
}
但是,如果您只想打印数组的 3 个最小元素,那么您的方法是正确的(尽管您仍然需要写出整个for
:
for(int i=0; i<3;i++){
System.out.println(numList[i]);
}
最后一个 for 不能那样工作。 使用 for 您可以像在第一个中一样或通过列表/数组迭代槽数。 我不明白你是想要最小的 3 还是小于 3 的。如果你想要最小的 3,你可以这样做:
double smallList[] = new double[3]
for (int i=0;i<3;i++) {
smallList[i] = numList[i];
}
或者如果你想一张一张打印出来:
for (int i=0;i<3;i++) {
System.out.println(numList[i]);
}
如果你想要小于 3 的,你必须这样做:
for (int i=0;i<numList.length;i++) {
if (numList[i]<3) {
System.out.println(numList[i]);
}
}
两种打印方式。
double[] numList = new double[6];
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
numList[i] = scan.nextDouble(); // user input
}
// then do
Arrays.stream(numList).filter(a -> a < 3).forEach(System.out::println);
// or
for (double n : numList) {
if (n < 3) {
System.out.println(n);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.