【发布时间】:2015-03-15 07:21:35
【问题描述】:
我正在上初等编程课,到目前为止,其中很多内容对我来说都是有意义的,我们已经开始使用方法,但我并不完全确定我是否理解“静态”,“ void”和“return”语句。
特别是对于这个作业,我以为我已经弄清楚了,但它在 main 方法的行上说“找不到符号直方图”,尽管我显然是从另一个方法返回它。谁能帮帮我?
作业:“您看到在编写程序时可能经常需要直方图,因此您决定让该程序使用您的程序 310a2 直方图。您可以添加到该程序或将其用作一个类。您还将编写一个类(或方法)将生成各种范围内的随机数。您可能希望星号表示不同的值(1、100 或 1000 个单位)。您可能还希望使用星号以外的字符,例如 $ 到表示你的图表的单位。运行程序足够的次数来说明程序的各种能力。
需要的语句:输出、循环控制、决策、类(可选)、方法。
样本输出:
10 月份的销售额
每日销售图表
2 37081 *************************************
3 28355 ****************************
4 39158 ***************************************
5 24904 ************************
6 28879 ******************************
7 13348 ************* "
这是我所拥有的:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public String histogram (int randomNum) //creates the histogram string
{
String histogram = "";
int roundedRandom = (randomNum/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
randInt(randomNum);
System.out.print(randomNum + " ");
histogram (randomNum);
System.out.print(histogram + "\n");
}
}
}
编辑:感谢你们,现在我已经弄清楚了静态的含义。现在我有一个新问题;程序运行,但直方图返回为空。有人可以帮我理解为什么吗?新代码:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public static String histogram (int marketValue) //creates the histogram string
{
String histogram = "";
int roundedRandom = (marketValue/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public static void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
int marketValue = randInt(randomNum);
System.out.print(marketValue + " ");
String newHistogram = histogram (randomNum);
System.out.print(newHistogram + "\n");
}
}
}
【问题讨论】:
-
对于初学者,我建议将方法名称更改为
getHistogram以避免将其与变量混淆。 -
main()必须是static。因此histogram()需要为static以便main可以调用它。 -
代码 sn-ps 用于 javascript。只需使用编辑器工具栏中的
{}(代码示例)按钮标记您的代码块。 -
marketValue的哪些值返回空字符串?当然,它应该在任何时候值低于 1000。 -
这里是理解静态方法的好资源introcs.cs.princeton.edu/java/21function