2017-04-10 64 views
0

程序问题:声明一个数组来保存八个整数。使用for循环将八个随机整数添加到该数组中,范围从50到100。重复是可以的。接下来,将数组传递给对数组进行排序的方法,并返回另一个只包含原始数组中最大和最小元素的数组。主要打印这两个值。然后在每个循环中使用a来显示排序数组的所有元素,并用一个空格分隔一行。后一个循环也应计算数组中的奇数和偶数,并确定数组中所有元素的总和。创建调用方法时返回数组的值

输出示例:

The lowest element is 59 
The highest element is 96 
Here is the array 
59 64 76 77 80 88 91 96 
Evens: 5, odds: 3 
Total: 631 

我的代码:

import java.util.Random; 
import java.util.Arrays; 

public class X { 

    private static Random rand; 

    public static void main(String[] args){ 
     int[] randomEight = numbers(); 
     System.out.println("Here is the array"); 
     System.out.println(Arrays.toString(randomEight)); 
     System.out.println(); 
    } 

    @SuppressWarnings("unused") 
    public static int[] numbers(){ 
    for (int x = 1; x <= 8; x++){ 
    //Random rand; 
     int randomNum = rand.nextInt((100 - 50) + 1) + 50; 
     int[] randomEight = {randomNum}; 
     //(50)(Math.random() * 101); 

     return randomEight; 
     } 
// int[] randomEight; 
    return null; 
    } 
} 

代码问题:我可以计算出大部分,但我无法返回数组的值在(50-100)之间的8个整数的随机集合中。我的代码不断产生错误输出。我可能正在推翻整个情况,但是有人可以引导我或给我一个想法。其余部分很容易理解,我可能会在未来更新代码。

+0

你不应该你的循环的第一次迭代中返回。你应该等到循环结束。 –

回答

0

有你的代码的几个问题下面的解释:

(1)您没有实例化Random类,这是导致NullPointerException,使创建使用new运营商Random类的物体,像​​

(2)你需要的for循环之前声明数组和插入的随机数到每个元件

(3)阵列的索引从0开始,因此需要访问数组里的元素柯randomEight[0]randomEight[1],等等。直到randomEight[7],所以你的循环变得for(int x = 0; x < 8; x++)

private static Random rand = new Random(); 

    public static void main(String[] args){ 
     int[] randomEight = numbers(); 
     System.out.println("Here is the array"); 
     System.out.println(Arrays.toString(randomEight)); 
     System.out.println(); 
    } 

    public static int[] numbers(){ 
     int[] randomEight = new int[8]; 
     for (int x = 0; x < 8; x++){ 
      randomEight[x] = rand.nextInt((100 - 50) + 1) + 50; 
     } 
     return randomEight; 
    } 
+0

补充说,它仍然没有返回值。 –

+0

你可以看看上面的代码以及解释问题的步骤 – developer

+0

是的,现在绝对有效!会添加一个math.random更有效的随机兰特?我觉得它会更多地压缩代码。 –

0
//Declare an array to hold eight integers. 
int[] randNums = new int[8]; 

//Use a for loop to add eight random integers, all in the range from 50 to 100, inclusive, to this array. Duplicates are okay. 
Random rand = new Random(); // <-- You forgot to instantiate Random 
for (int i = 0; i < randNums.length; i++) { 
    randNums[i] = rand.nextInt((100 - 50) + 1) + 50; // <-- I suggest you put the random int directly to the element to simplify it and avoid more issues 
} 
+0

非常感谢您的支持!将加入math.random也是另一种选择,而不是随机兰特? –

+0

@ A.B。当然!作为参考,你可以阅读更多关于'Math.random()'[这里](https://stackoverflow.com/questions/7961788/math-random-explained)。请点击检查,如果这个答案为你解决。谢谢。 – lxcky