我需要以这种形式打印我的最终阵列1 2 3 4 5 MEGA:6 现在它正在打印所有已连接的数字,我不知道如何制作间距并在数组中的第5和第6个数字之间添加单词mega
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();
}
}
}
答案 0 :(得分:1)
只需添加空格,并进行条件检查,如果您在最后一个数字处决定是否打印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(" ");
}
答案 1 :(得分:0)
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
}
}
答案 2 :(得分:0)
使用此:
for(int i = 0; i < array.length; i++)
{
if(i == 5)
System.out.print("MEGA:");
System.out.print(array[i] + " ");
}