Java乐透号码生成器LOOP

时间:2014-10-27 05:01:17

标签: java arrays loops for-loop int

我刚刚想出了这个代码,它只打印了一行5个随机乐透号和1个随机兆号。我需要创建一个循环,询问用户“你想要多少票?”,然后打印用户要求的行数,而不是一行。我该怎么做?我相信它是一个for循环,但我不确定。

public static void main(String[] args)

    {

        int[] lottoNumber = new int[6];  
        {  
            lottoNumber[0] = (int) ((47 * Math.random()) + 1);  
            lottoNumber[1] = (int) ((47 * Math.random()) + 1);  
            lottoNumber[2] = (int) ((47 * Math.random()) + 1);  
            lottoNumber[3] = (int) ((47 * Math.random()) + 1);  
            lottoNumber[4] = (int) ((47 * Math.random()) + 1);  
            lottoNumber[5] = (int) ((27 * Math.random()) + 1);  
        }  

        System.out.println("Lottery Numbers: ");

        for(int i=0; i<1; i++)  
        {  
            System.out.print(lottoNumber[0] + " " );
            System.out.print(lottoNumber[1] + " " );
            System.out.print(lottoNumber[2] + " " );
            System.out.print(lottoNumber[3] + " " );
            System.out.print(lottoNumber[4] + " " );
            System.out.print("MEGA:(" + lottoNumber[5] + ")");
        }

    }

}

2 个答案:

答案 0 :(得分:0)

添加扫描程序以读取想要用户的故障单数量。(扫描程序用于从命令行读取值)。然后创建一个for循环并使用从用户获得的票数作为for循环的条件值。然后将以上所有代码添加到for循环内部。

祝你好运!!!

答案 1 :(得分:0)

首先,使用扫描仪类询问门票数量。 其次,您需要为生成故障单的代码创建一个方法。 第三,用打印循环getticket。 就是这样。这是(工作)代码:

import java.io.*;
import java.util.Scanner;
public class test{

public static void main(String[] args)
{
    System.out.print("Enter number of tickets: ");
    Scanner numReader= new Scanner(System.in);
    int num = numReader.nextInt();
    System.out.println("Lottery Numbers: ");
    System.out.println();
    for(int i=0; i<num; i++)  
    {  
        int[] lottoNumber = getTicket();
        System.out.print(lottoNumber[0] + " " );
        System.out.print(lottoNumber[1] + " " );
        System.out.print(lottoNumber[2] + " " );
        System.out.print(lottoNumber[3] + " " );
        System.out.print(lottoNumber[4] + " " );
        System.out.print("MEGA:(" + lottoNumber[5] + ")");
        System.out.println();
    }  

}  
    public static int[] getTicket()
    {
        int[] lottoNumber = new int[6];
        {  
        lottoNumber[0] = (int) ((47 * Math.random()) + 1);  
        lottoNumber[1] = (int) ((47 * Math.random()) + 1);  
        lottoNumber[2] = (int) ((47 * Math.random()) + 1);  
        lottoNumber[3] = (int) ((47 * Math.random()) + 1);  
        lottoNumber[4] = (int) ((47 * Math.random()) + 1);  
        lottoNumber[5] = (int) ((27 * Math.random()) + 1);  
        }  
        return lottoNumber;
    }
}