public class Part4 {
public static void main(String args []) {
Random rand = new Random();
int total = 0;
for(int i = 0;i< 10;i++) {
total += rand.nextInt(101);
}
double avg = (double) total/10;
System.out.println("The average of 10 marks is " +avg);
}
}
我的代码完美无缺,但我不知道如何将我的代码放在过程方法中。你可以帮帮我吗?
答案 0 :(得分:2)
这样做。您可以使用参数金额来说明要计算平均值的数量。
public double calculateAverage(int amount) {
Random rand = new Random();
int total = 0;
for (int i = 0; i < amount; i++) {
total += rand.nextInt(101);
}
double avg = (double) total / amount;
System.out.println("The average of 10 marks is " + avg);
return avg;
}
答案 1 :(得分:2)
以下示例显示如何将计算委托给方法,如何通过实例化类Part4来调用它
public class Part4
{
public double getAvgRandNum(int num)
{
Random rand = new Random();
int total = 0;
for(int i = 0;i< num ;i++)
{
total += rand.nextInt(101);
}
double avg = (double) total/num;
return avg;
}
public static void main(String args []) {
Part4 prt = new Part4()
double avgRes = prt.getAvgRandNum(10)
System.out.println("The average of 10 marks is " +avgRes);
}
}
在Main中,我们实例化(创建一个对象)类Part4.Once一个对象被创建“prt”只需使用点运算符来访问(调用)它的方法getAvgRandNum。
答案 2 :(得分:0)
您似乎已经处于学习Java的早期阶段,所以我认为我会在一个更简单的“更简单”的流行音乐中出现。溶液
public class Part4
{
//This is the method you need to call
public static double calculateAverage(int amount) {
Random rand = new Random();
int total = 0;
for (int i = 0; i < amount; i++) {
total += rand.nextInt(101);
}
double avg = (double) total / amount;
return avg;
}
public static void main(String args []) {
//And this is how we call it
double avgRes = calculateAverage(10)
System.out.println("The average of 10 marks is " +avgRes);
}
}
感谢Moh123和Mosa,我借了一些代码。