我是初学者Java程序员,并且已经为此而辛苦了一段时间。我需要将下面的程序转换为OOP格式,并且无法在没有错误的情况下进行编译。我认为我会发布工作的非格式程序,而不是失败和断断续续的尝试。如果有人可以将以下程序转换为OOP,这将不胜感激。请原谅我是新手的任何效率低下或湿润。
感谢您的帮助:)
导入java.util.scanner;公共类估计{
//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.5fn",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.5fn", "Estimation of pi = ",averagePi);
}
}
我受到问题的启发,并写了一个漫画项目。我试图使代码尽可能地面向对象,但要留在"域"中,并且不使用大量的设计模式,框架等。而且,我尝试遵循测试优先的意识形态。您可以查看委员会历史记录,并查看工作是如何逐步进行的。
谢谢,Javacoder的经验和乐趣。