当我尝试运行该程序时,它将接受输入,但仅对所有打印输出0.0 0.0 0.0。我需要它来打印估算的数字,然后将平均值打印到2位小数精度。为什么只打印0,而不打印数字
import java.util.Scanner;
import java.util.Arrays;
public class pcCalculate
{
double[] pcPrice = new double [10];
public static void main(String[] args)
{
Quiz input = new Quiz();
Quiz display = new Quiz();
Quiz avgCalc = new Quiz();
input.arrayInput();
display.displayPCPrices();
avgCalc.avgPCCalc();
}
public void displayPCPrices()
{
System.out.println(Arrays.toString(pcPrice));
}
public double avgPCCalc()
{
int sum = 0;
for (int i=0; i < pcPrice.length; i++)
{
sum = (int) (sum + pcPrice[i]);
}
double average = sum / (double)pcPrice.length;
return average;
}
public void arrayInput()
{
Scanner price = new Scanner(System.in);
System.out.println("Enter Prices");
pcPrice[0] = price.nextDouble();
pcPrice[1] = price.nextDouble();
pcPrice[2] = price.nextDouble();
pcPrice[3] = price.nextDouble();
pcPrice[4] = price.nextDouble();
pcPrice[5] = price.nextDouble();
pcPrice[6] = price.nextDouble();
pcPrice[7] = price.nextDouble();
pcPrice[8] = price.nextDouble();
pcPrice[9] = price.nextDouble();
}
}
答案 0 :(得分:0)
从主目录调用displayPCPrices方法,并将pcPrice作为参数传递:
import java.util.Scanner;
import java.util.Arrays;
public class pcCalculate
{
public static void main(String[] args)
{
double[] pcPrice = new double [10];
Scanner price = new Scanner(System.in);
System.out.println("Enter Prices");
pcPrice[0] = price.nextDouble();
pcPrice[1] = price.nextDouble();
pcPrice[2] = price.nextDouble();
pcPrice[3] = price.nextDouble();
pcPrice[4] = price.nextDouble();
pcPrice[5] = price.nextDouble();
pcPrice[6] = price.nextDouble();
pcPrice[7] = price.nextDouble();
pcPrice[8] = price.nextDouble();
pcPrice[9] = price.nextDouble();
displayPCPrices(pcPrice);
}
public void displayPCPrices(Array pcPrice)
{
System.out.println(Arrays.toString(pcPrice));
}
public double avgPCCalc()
{
int sum = 0;
for (int i=0; i < pcPrice.length; i++)
{
sum = (int) (sum + pcPrice[i]);
}
double average = sum / (double)pcPrice.length;
return average;
}
}
编辑:就像您知道的那样,main(String [] args)是您的程序将始终启动的地方,您从那里调用其他方法并开始工作。没有别的会调用您的main方法。
EDIT2:如果您想就您的编码实践进行对话,向我发送消息,我看到您已经更改了问题,并且缺少了一些可以帮助您轻松解决此问题的基本概念。
答案 1 :(得分:0)
数组在循环中更好,在这种情况下,我会这样:
import java.util.Scanner;
import java.util.Arrays;
public class pcCalculate {
double[] pcPrice = new double [10];
public static void main(String[] args){
Scanner price = new Scanner(System.in);
for(int i=0; i< pcPrice.length; i++){
System.out.print("Set Price " + (i + 1) + ":");
pcPrice[i] = price.nextDouble();
}
displayPCPrices();
System.out.println("The average is :" + avgPCCalc());
}
public void displayPCPrices()
{
System.out.println("The prices are: " + "\n");
for(int i = 0; i< pcPrice.length; i++){
System.out.print(pcPrice[i] + " ");
}
}
public double avgPCCalc()
{
double sum = 0;
for (int i=0; i < pcPrice.length; i++)
{
sum += pcPrice[i];
}
double average = sum / 10;
return average;
}
}