【问题标题】:Larger Than n Array大于 n 的数组
【发布时间】:2017-02-16 00:37:28
【问题描述】:

我在尝试编写一个接受两个参数的方法时遇到了麻烦:一个数组和一个数字 n,所有参数都假定为整数。它还应该显示数组中大于数字 n 的数字。

这是我第一次使用数组,并尝试做这种事情。所以,我非常不确定该怎么做,或者如何用这个问题来做。

import java.util.Random; // Initialize random class
import java.util.Scanner; //Create the scanner class

public class ArrayNumbers {

    public static void getNumbers(int computerArray[], int n){

        for(int element : computerArray){
            if(n < element){
            System.out.println(element);
            }
        }
    }

    public static void main(String[] args) {
        int computerArray1[] = new int[100];
        Random rand = new Random();

        for(int count1=10; count1>1; count1++){
            computerArray1[n] = rand.nextInt(100);
            getNumbers(computerArray1[1],1);
       }
    }
}

【问题讨论】:

  • Dylan,人们已经在 20 多分钟前回答了您的问题。这是你想要的吗?

标签: java arrays class methods


【解决方案1】:

将你的 main 更改为(参见 cmets inline)

public static void main(String[] args) {
    int computerArray1[] = new int[100];
    Random rand = new Random();

    for(int count1=0; count1 < 100; count1++){  // loop to 100
        computerArray1[count1] = rand.nextInt(100);  // n does not exist
   }
   // do after data is input?
   getNumbers(computerArray1,1);  // pass the whole array

}   

【讨论】:

    【解决方案2】:
        int computerArray1[] = new int[100];
    

    根据此处数组的大小100,当count1 到达100 时,应用程序将崩溃,因为该数组只能从0-99 寻址。

        for(int count1=10; count1>1; count1++){
            computerArray1[n] = rand.nextInt(100); // count1 instead of n?      
            // computerArray1[1] is just the int at index 1 in the array
            getNumbers(computerArray1[1],1); 
       }
    

    所以你可能打算这样做......

        for(int count1=0; count1<100; count1++){
            computerArray1[count1] = rand.nextInt(100);
            getNumbers(computerArray1,1);
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      相关资源
      最近更新 更多