Objects Hacks
Demonstrates learning on objects.
Basics physics calculator using class, methods, console meny, and Math operations.
More notes on Objects can be found here .
import java.util.Scanner;
import java.lang.Math;
public class OneDimensionalPhysics {
double position;
double velocity;
double acceleration;
double time;
public OneDimensionalPhysics() {
this.position = 0;
this.velocity = 0;
this.acceleration = 0;
this.time = 0;
this.enterData();
this.printMenu();
boolean useMenu = true;
}
private void printMenu() {
System.out.println("---------- Choose an Option ----------");
System.out.println("0. Calculate final velocity");
System.out.println("1. Calculate final position");
System.out.println("2. Calculate displacement");
System.out.println("3. Exit");
}
public void enterData() {
Scanner input = new Scanner(System.in);
System.out.println("Enter position, in meters: ");
this.position = input.nextDouble();
System.out.println(this.position);
System.out.println("Enter velocity, in meters per second: ");
this.velocity = input.nextDouble();
System.out.println(this.velocity);
System.out.println("Enter acceleration, in meters per second squared: ");
this.acceleration = input.nextDouble();
System.out.println(this.acceleration);
System.out.println("Enter time, in second: ");
this.time = input.nextDouble();
System.out.println(this.time);
}
public double calculateFinalVelocity() {
double finalVelocity = this.velocity + (this.acceleration * this.time);
return finalVelocity;
}
public double calculateFinalPosition() {
double finalPosition = this.position + (this.velocity * this.time) + (0.5 * this.acceleration * Math.pow(this.time, 2));
return finalPosition;
}
public static void main(String[] args) {
// instance of class
OneDimensionalPhysics newData = new OneDimensionalPhysics();
// create console menu
Scanner menuInput = new Scanner(System.in);
boolean useMenu = true;
while(useMenu) {
System.out.println("Menu option: ");
int menuChoice = menuInput.nextInt();
System.out.println(menuChoice);
switch(menuChoice) {
case 0:
// calling method on object
System.out.println("--- Final Velocity: " + newData.calculateFinalVelocity() + " ---");
break;
case 1:
System.out.println("--- Final Position: " + newData.calculateFinalPosition() + " ---");
break;
case 2:
System.out.println("--- Displacement: " + (newData.calculateFinalPosition() - newData.position) + " ---");
break;
case 3:
System.out.println("Goodbye!");
useMenu = false;
break;
}
}
System.out.println("---------- Summary ----------");
System.out.println("Final Velocity: " + newData.calculateFinalVelocity());
System.out.println("Final Position: " + newData.calculateFinalPosition());
System.out.println("Displacement: " + (newData.calculateFinalPosition() - newData.position));
}
}
OneDimensionalPhysics.main(null);