2014-10-27 130 views
0

我剛剛想出了這個代碼,打印我只有一行5個隨機樂透號碼和1個隨機巨型號碼。我需要創建一個循環,詢問用戶「您想要多少票?」,然後打印用戶要求的行數,而不是一行。我將如何做到這一點?我相信它是一個for循環,但我不知道。爪哇樂透號碼發生器LOOP

公共靜態無效的主要(字串[] 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] + ")"); 
    } 

} 

}

回答

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; 
    } 
} 
+0

謝謝@luisluix!這有很大幫助。 – evolution8 2014-10-27 06:00:51

0

添加掃描器讀取彩票數目希望給用戶。(掃描儀使用從命令線讀取值)。然後創建一個for循環,並使用從用戶獲取的票數作爲for循環的條件值。然後將所有上面的代碼添加到for循環中。

祝你好運!!!