我是一名初学Java程序员,并且已经花了很长时间。我需要将下面的程序转换为OOP格式,并且无法在没有错误的情况下进行编译。我想我会发布工作的非格式化程序,而不是我失败和不稳定的尝试。如果有人可以将以下程序转换为OOP,那将非常感激。请原谅任何低效率或邋iness,因为我是新手。
感谢您的帮助:)
import java.util.Scanner; 公共课EstimatePi {
//Public static variables used because they are used throughout the different methods
public static Scanner in = new Scanner(System.in);
//2 * Math.random - 1 is used to guarentee that the max value is gonna be 1 and min is gonna be -1
public static double x = (2 * Math.random() - 1);
public static double y = (2 * Math.random() - 1);
public static double radius = 1.0;
public static double numOnBoard;
public static double totalPi;
public static int numThrows;
public static int trials;
public static int hits(double x, double y, int trials) {
numOnBoard = 0;
for (int i = 1; i < trials; i++) {
//Same Algorithm as above
x = (2 * Math.random() - 1);
y = (2 * Math.random() - 1);
//If x2 + y2 <= r2 then its a hit on the board.
if ((Math.pow(x, 2) + Math.pow(y, 2)) <= (Math.pow(radius, 2))) {
numOnBoard++;
}
}
//returns the num of hits on the board
return (int)numOnBoard;
}
//Method to calculate pi, and store that data in an array
public static double[] piColumn( double numOnBoard, double numThrows)
{ double []piColumn = new double[trials];
for(int i = 0; i < piColumn.length;i++)
{
//Formula to calculate the pi
piColumn[i] = (4 * (numOnBoard) / numThrows);
}
return piColumn;
}
public static void main (String [ ] args)
{
//The number of darts thrown per trial is asked
System.out.println("How many times should the dart be thrown per trial?");
numThrows = in.nextInt();
System.out.println();
//The number of trials is asked
System.out.println("How many trials do you want to simulate?");
trials = in.nextInt();
System.out.println();
//forloop to iterate the internal code while counter < trials
for (int counter = 0; counter < trials; counter++) {
//number of hits methods is declared as a integer
int hits = hits(x,y,numThrows);
//the calculation of pi is declared as a double
double []estimatedPi = piColumn(hits,numThrows);
//total = total + the estimatation of pi
for(int i = 0; i < trials; i++){
totalPi += estimatedPi[i];
}
//Formatting the output
System.out.printf("%s %d %s %s", "Trial [",(counter + 1),"]", ": pi = ");
System.out.printf("%1.5f\n",estimatedPi[counter]);
}
//The average pi is the total pi's divided by the number of trials the user enters
double averagePi = (totalPi / trials / trials);
System.out.printf("%s %1.5f\n", "Estimation of pi = ",averagePi);
}
}
答案 0 :(得分:0)
我受到这个问题的启发,写了一部漫画project。我试图使代码尽可能面向对象,但留在&#34;域&#34;并且不要使用大量的设计模式,框架等。另外,我试图遵循测试优先的意识形态。您可以查看commits history并查看工作是如何逐步进行的。
谢谢你,javacoder,体验和乐趣。