如何将这些值设为正面和负面?

时间:2014-09-23 21:27:49

标签: java for-loop random

如何让这个程序打印出负值和正值,这样就会有从-100到100的随机数?

public class RandomInts {

    /* 
     * This program makes 10 random integers and prints them out on the console window.
     */
    public static void main(String[] args) {
        int[] myArray;      
        myArray = new int[10];

        for( int i = 0; i < myArray.length; i++ ){
            myArray[i] = (int)(Math.random() * 100);
        } // End of first for loop.

        for(int i=0;i<10;i++){
            System.out.println("My array is " + myArray[i]);
        } // End of second for loop.

    } // End of the main.

} // End of the class RandomInts.

2 个答案:

答案 0 :(得分:0)

你可以尝试 -

公共类RandomInts {

/* 
 * This program makes 10 random integers and prints them out on the console window.
 */
public static void main(String[] args) {
    int[] myArray;      
    myArray = new int[10];

    for( int i = 0; i < myArray.length; i++ ){
        myArray[i] = (int)(Math.random() * 200) - 100;
    } // End of first for loop.

    for(int i=0;i<10;i++){
        System.out.println("My array is " + myArray[i]);
    } // End of second for loop.

} // End of the main.

} //类的结尾为RandomInts。

答案 1 :(得分:0)

myArray[i] = r.nextInt() % 101 Random r = new Random()

的{{1}}怎么样?
相关问题