Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.util.Arrays;
- import java.util.Scanner;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public class NBody {
- public static void main(String[] args){
- double totalTime = 157788000.0;
- double dt = 25000.0;
- String pfile = "data/planets.txt"; // ./data/planets.txt
- if (args.length > 2) {
- totalTime = Double.parseDouble(args[0]);
- dt = Double.parseDouble(args[1]);
- pfile = args[2];
- }
- String fname = pfile;
- Planet[] planets = readPlanets(fname);
- double radius = readRadius(fname);
- System.out.printf("%d\n", planets.length);
- System.out.printf("%.2e\n", radius);
- for (int i = 0; i < planets.length; i++) {
- System.out.printf("%11.4e %11.4e %11.4e %11.4e %11.4e %12s\n",
- planets[i].myXPos, planets[i].myYPos,
- planets[i].myXVel, planets[i].myYVel,
- planets[i].myMass, planets[i].myFileName);
- }
- StdDraw.setScale(-radius, radius);
- StdDraw.picture(0,0,"images/starfield.jpg");
- for(double t = 0.0; t < totalTime; t += dt) {
- double[] xForces = new double[planets.length];
- double[] yForces = new double[planets.length];
- for (int i = 0; i < planets.length; i++) {
- xForces[i] = planets[i].calcNetForceExertedByX(planets);
- yForces[i] = planets[i].calcNetForceExertedByY(planets);
- }
- for (int i = 0; i < planets.length ; i++) {
- planets[i].update(dt, xForces[i], yForces[i]);
- }
- StdDraw.picture(0,0,"images/starfield.jpg");
- Arrays.stream(planets).forEach(p -> p.draw());
- StdDraw.show(10);
- }
- Arrays.stream(planets).forEach(p -> p.draw());
- }
- public static double readRadius(String fname) {
- try {
- Scanner scanner = new Scanner(new File(fname));
- scanner.next();
- double radius = scanner.nextDouble();
- scanner.close();
- return radius;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- return -1.0;
- }
- public static Planet[] readPlanets(String fname) {
- Planet[] planets = new Planet[5];
- try {
- Scanner scanner = new Scanner(new File(fname));
- scanner.next();
- scanner.next();
- for (int i = 0; i < planets.length; i++) {
- planets[i] = new Planet(scanner.nextDouble(),
- scanner.nextDouble(),
- scanner.nextDouble(),
- scanner.nextDouble(),
- scanner.nextDouble(),
- scanner.next());
- }
- scanner.close();
- } catch (FileNotFoundException ex) {
- Logger.getLogger(NBody.class.getName()).log(Level.SEVERE, null, ex);
- }
- return planets;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement