【发布时间】:2023-03-12 07:44:02
【问题描述】:
您将开发一个程序来计算范围内每个数字的生成次数。您的程序将在 [0, 9] 范围内生成 100 个数字,您将打印一个类似于下面显示的直方图的直方图。
0 ********
1 ***********
2 ******
3 ****************
4 **************
5 *****
6 ************
7 ***********
8 ********
9 *********
要打印上面显示的直方图,您的程序必须记录每个数字生成的次数。
我正在尝试将 num 和 count 传递给 print 方法,然后通过 switch 语句将其传递为星号。但它给了我一个错误。建议?
这是我得到的错误:
必需:int,int 找到:无参数原因:实际和正式 参数列表长度不同 /tmp/java_9JsuaS/RandomSrv.java:55: 错误:类 RandomSrv 中的方法 print 不能应用于给定 类型; System.out.print("9" + this.print()); ^
import java.util.Random;
public class RandomSrv
{
public void genNums(int total)
{
for(int counter = 0; counter < total; counter++) //counter for the random gen nums//
{
int UPPER_BOUND = 10;//max number it will go to: 9
int count0 = 0; //stores counter//
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
int count = 0;
Random randObj = new Random(); //creating randoms object//
int num = randObj.nextInt(UPPER_BOUND);//num ranges 1-10//
print(num, count);
switch (num) //counts it into catagories//
{
case 0: count = count0++;
System.out.print("0 " + this.print());
break;
case 1: count = count1++;
System.out.print("1 " + this.print());
break;
case 2: count = count2++;
System.out.print("2 " + this.print());
break;
case 3: count = count3++;
System.out.print("3 " + this.print());
break;
case 4: count = count4++;
System.out.print("4 " + this.print());
break;
case 5: count = count5++;
System.out.print("5 " + this.print());
break;
case 6: count = count6++;
System.out.print("6 " + this.print());
break;
case 7: count = count7++;
System.out.print("7 " + this.print());
break;
case 8: count = count8++;
System.out.print("8 " + this.print());
break;
case 9: count = count9++;
System.out.print("9 " + this.print());
break;
}
}
}
public void print(int num, int count) //converting them to astericks//
{
for(int x = 0; x < count; x++)
{
System.out.println("*");
}
}
}
【问题讨论】:
-
代码太长,对想要的问题很复杂。我建议考虑数组,例如 int[10](从 0-9)数组中的每个位置都指的是它的值,例如:array[i++] 每次你有 i 值的数字时,i 位置被提升一。最后的打印将通过运行该数组来完成。
-
它没有告诉你如何生成数字。您可以只 generate 4 each time 然后连续打印 100 个星号。