Question

I need to have my final array print in this form 1 2 3 4 5 MEGA:6 right now it is printing my numbers all connected and I am not sure how to make the spacing and add the word mega between the 5th and 6th number in the array

import java.util.Scanner;
public class SuperLottoPlus {
    //create array
    public static int[] generateSuperLottoNumbers()
    {
        int[] numbers;
        numbers = new int[6];
        numbers[0] = (int) (47 * Math.random()) + 1;
        numbers[1] = (int) (47 * Math.random()) + 1;
        numbers[2] = (int) (47 * Math.random()) + 1;
        numbers[3] = (int) (47 * Math.random()) + 1;
        numbers[4] = (int) (47 * Math.random()) + 1;
        numbers[5] = (int) (27 * Math.random()) + 1;
        return numbers;
    }
    //method to print ticket
    public static void printTicket(int [] array)
    {
        int i;
        for(i = 0; i < array.length ; i++)
        {
            System.out.print(array[i]);
        }

    }
   //print ticket numbers based on the amount of tickets user wants (n)
    public static void main (String[] args)
    {
        int n;
        Scanner keyboard = new Scanner(System.in);
        System.out.println("How many lottery tickets would you like?");
        n = keyboard.nextInt();
        for(int i = 0; i < n; i++)
        {
            printTicket(generateSuperLottoNumbers());
            System.out.println();
        }
    }
}
Was it helpful?

Solution

Just add the spaces, and a conditional check if you're at the last number to decide whether to print MEGA

public static void printTicket(int [] array)
{
    int i;
    for(i = 0; i < array.length ; i++)
    {
        if (i == array.length - 1) 
        {
            System.out.print("MEGA: ");
        }
        System.out.print(array[i]);
        System.out.print(" ");
    }

OTHER TIPS

public static void printTicket(int [] array)
{
    int i;
    for(i = 0; i < array.length ; i++)
    {
        if(i == array.length - 1){ //looks for last element
            System.out.print("MEGA:"); //adds word MEGA before last element
        }
        System.out.print(array[i] + " "); //prints all elements, last one after MEGA word
    }

}

Use this:

for(int i = 0; i < array.length; i++)
    {
        if(i == 5)
            System.out.print("MEGA:");
        System.out.print(array[i] + " ");
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top