【发布时间】:2016-10-28 22:18:17
【问题描述】:
问题:我已完成此作业的第 1-4 步。但是,我目前停留在此作业的第 5 步和第 6 步,所以我不知道如何将我的 fizz 和 Buzz 字符串数组组合成一个单独的 fizzbuzz 字符串数组。
TL;DR 我不知道如何执行第五步和第六步。
作业:
您可以在 main 方法中完成所有这些操作。这是使用一个名为 Fizz-Buzz,一款古老的程序员游戏。
首先初始化一些变量来设置随机数的最大值和最小值以及数组的容量。 (20/100)
初始化三个新数组,一个用于随机数列表(作为整数),两个用于名为“fizz”的字符串数组, '嗡嗡声'。(20/100)
您还需要一个整数来计数。
编写一个 for 循环,为数组中的每个位置生成一个随机数。请记住,此范围将由 在文件开头初始化的两个变量。有 创建随机数的多种方法,只需找到一种适用的方法 你。 (20/100)
使用数组的计数,创建另一个数组来存储所有的嘶嘶声和嗡嗡声,而不会留下任何额外的空间 数组。 (20/100)
使用 for each 循环迭代数组并打印所有的嘶嘶声和嗡嗡声,没有其他输出。 (20/100)
到目前为止我已经完成了什么:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Random;
/**
*
* @author
*/
public class FizzBuzz {
//2a. Initialize one int array for a list of random numbers.
private static int[] anArray;
private static final int size = 10;
//2b. Initialize two String arrays called 'fizz' and 'buzz.'
public static String[] fizz;
public static String[] buzz;
public static String[] fizzbuzz;
public static Random rand = new Random();
//1. Set the maximum and minimum value of a random number.
private static final int min = 0;
private static final int max = 5;
private static int count = 0;
public static int[] list() {
anArray = new int[size];
//3. Make an integer for counting("counter" in the for loop)
//4. Write a for loop that generates a random number for
// each position in the array.
for(count = 0; count < anArray.length; count++) {
anArray[count] = randomFill();
}
return anArray;
}
public static void print() {
for (int i = 0; i < anArray.length; i++) {
System.out.println(anArray[i] + ": " + fizz[i] + buzz[i]);
}
}
public static int randomFill() {
return rand.nextInt((max - min) + 1) + min;
}
public static String[] getF() {
fizz = new String[size];
int x = 0;
int counter;
for(counter = 0; counter < fizz.length; counter++) {
if(anArray[counter] % 3 == 0) {
fizz[counter] = "fizz";
} else {
fizz[counter] = "";
}
}
return fizz;
}
public static String[] getB() {
buzz = new String[size];
int x = 0;
int counter;
for(counter = 0; counter < buzz.length; counter++) {
if(anArray[counter] % 5 == 0) {
buzz[counter] = "buzz";
} else {
buzz[counter] = "";
}
}
return buzz;
}
public static String[] getFB() {
fizzbuzz = new String[size];
return fizzbuzz;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
list();
getF();
getB();
print();
}
}
【问题讨论】:
-
你永远不会打电话给
GetFizzOrBuzz()。因此,您永远不会为fizzbuzz分配任何值。这段代码根本不起作用,因为fizzbuzz从未被初始化。您可以/应该尝试使用调试器重现此结果(您使用的任何 IDE 都应该内置一个)。 -
@Paul 嘿,感谢您的意见。我在发布问题后立即意识到这一点,并编辑了帖子以反映我调用 GetFizzOrBuzz()!