0

嗨,Java 新手,这是我的第二个任务。我已经使用数组列表为彩票代码编写了一个方法,我有两个问题:

  • 为请求的每一行生成相同的混洗列表。
  • 线条打印下来不跨越。

public static void irishLottery() {
    Scanner input = new Scanner(System.in);
    double cost = 0;
    System.out.println("How many lines of lottery up to 10 would you like?");
    int linesam = input.nextInt();

    ArrayList<Integer> numbers = new ArrayList<Integer>();
    //define ArrayList to hold Integer objects

    for (int lottonos = 0; lottonos < 45; lottonos++) {
        numbers.add(lottonos + 1);
    }
    Collections.shuffle(numbers);

    System.out.print("Your lottery numbers are: ");

    for (int lncounter = 1; lncounter <= linesam; lncounter++) {
        for (int j = 0; j < 6; j++) {
            System.out.println(numbers.get(j) + " ");

        }
    }
}
4

1 回答 1

2

对于第一个问题:每次要显示新行时重新排列列表:

for (int lncounter = 1; lncounter <= linesam; lncounter++) {  
    Collections.shuffle(numbers);
    for (int j = 0; j < 6; j++) {
        System.out.println( numbers.get(j) + " ");
    }
}

对于第二个问题,不要使用 println(),而是使用 print(),因为 println() 会打印一个新行:

for (int lncounter = 1; lncounter <= linesam; lncounter++) {  
    Collections.shuffle(numbers);
    for (int j = 0; j < 6; j++) {
        System.out.print(numbers.get(j) + " ");
    }
    System.out.println(); // new line before next line
}

请注意,Java 中循环的标准习惯用法是从 0 开始:

for (int lncounter = 0; lncounter < linesam; lncounter++) {  
    Collections.shuffle(numbers);
    for (int j = 0; j < 6; j++) {
        System.out.print(numbers.get(j) + " ");
    }
    System.out.println(); // new line before next line
}
于 2013-05-20T12:12:21.657 回答