Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
public class WaterHeater{
//public fields set to private
private double water = 1;
private double kilowatts= 2;
private double joules = 3600;
private double temp = 70;
private double jkg = 4200;
private double energy;
private double time;
//Constructor method
public WaterHeater (double water, double kilowatts, double joules, double temp, double jkg) {
}
//Accessors and mutators
//Accessor for Water
public double getWater() {
return water;
}
public void setWater(int water) {
this.water = water;
}
//Accessor for Kilowatts
public double getKilowatts() {
return kilowatts;
}
public void setKilowatts(int kilowatts) {
this.kilowatts = kilowatts;
}
//Accessor for Temperature
public double getTemp() {
return temp;
}
public void setTemp(int temp) {
this.temp = temp;
}
//Method for Energy used
public double getEnergy() {
energy = water*jkg*temp;
return energy;
}
public void setEnergy() {
this.energy = energy;
}
//Method for Time to boil
public double getTime() {
time = energy/kilowatts;
return time;
}
public void setTime() {
this.time = time;
}
}
public class Kettle extends WaterHeater{
public Kettle(double water, double kilowatts, double joules, double temp, double jkg) {
super(water, kilowatts, joules, temp, jkg);
}
public static void main( String args[] )
{
userInput kettleinput = new userInput();
System.out.println("\nEnergy used: ");
System.out.println("Time to boil: ");
}
}
public class userInput {
public static void main(String args[])
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
double getWater;
// These must be initialised
String strWater = null;
int intWater = 0;
System.out.print("Enter amount of water used: ");
System.out.flush();
// read string value from keyboard
try {
strWater = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intWater = Integer.parseInt(strWater);
}
catch (NumberFormatException nfe) {
System.out.println("Whoops: " + nfe.toString());
System.exit(1);
}
double getKilowatts;
// These must be initialised
String strKilowatts = null;
int intKilowatts = 0;
System.out.print("Enter amount of Kilowatts used: ");
System.out.flush();
// read string value from keyboard
try {
strKilowatts = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intKilowatts = Integer.parseInt(strKilowatts);
}
catch (NumberFormatException nfe) {
System.out.println("Whoops: " + nfe.toString());
System.exit(1);
}
double getTemp;
// These must be initialised
String strTemp = null;
int intTemp = 0;
System.out.print("Enter the temperature of water raised by: ");
System.out.flush();
// read string value from keyboard
try {
strTemp = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intTemp = Integer.parseInt(strTemp);
}
catch (NumberFormatException nfe) {
System.out.println("Whoops: " + nfe.toString());
System.exit(1);
}
}
}
Sorry for the long code. I have a problem finding a solution to display the result of the user inputs. I have the methods created in WaterHeater and i want to use them to calculate energy used and time to boil when the user enters Water, Kilowatts and Temp. The methods are already done i just cant find a way to use them. So when the Kettle class is running the user enters Water, Kilowatts and Temp and it will give a result. Any help is appriciated.
I would change the following:
move your code from the userInput main method into the constructor. Then all your variables that you need to use like intWater and intKilowatts i would make member variables. I would then provide public accessor methods.
Then your Kettle class main method you need to instantiate a new kettle and pass through the values from the user input class. Then you can just get the values you need from the kettle class which inherits from that water heater class and provides the required methods to output.
First off, you need to explain yourself a little better. I do not really understand what you really need but here is my try.
WaterHeater
You aren't setting the object's values within the custom constructor.
If some values are constants, just treat them as they are (private static final).
Values such time, energy don't need to be fields as they are calculated every time the user gets them.
Kettle & userInput
Both have a static function called main. That's illegal. I recommend you to move all the code in the latter function into the first one.
Kettle's main function's code do NOT make sense. That wouln't even compile.
userInput is a class so call it UserInput (be consistent).
Please, take a deep breath, get focused and explain better what you need and what you already have. Always try to show a code that, at least, compiles.
Related
I am doing some homework for my java programming class, but this code is giving me trouble. The online program that grades it says there is a problem with my output, but I really don't see why. Can anyone help?
The assignment:
Write a class named Car that has the following fields:
yearModel: The yearModel field is an int that holds the car's year model.
make: The make field is a String object that holds the make of the car.
speed: The speed field is an int that holds the car's current speed.
In addition, the class should have the following methods :
Constructor : The constructor should accept the car's year model and make as arguments .
These values should be assigned to the object 's yearModel and make fields. The
constructor should also assign 0 to the speed field.
Accessor: The appropriate accessor methods should be implemented to access the values
stored in the object 's yearModel, make, and speed fields.
accelerate: The accelerate method should add 5 to the speed field when it is called.
brake: The brake method should subtract 5 from the speed field each time it is called.
Demonstrate the class in a program that contains a Car object , and then calls the
accelerate method five times. After each call to the accelerate method , get the current
speed of the car and print it on a separate line. Then, call the brake method five times,
each time printing the current speed of the car on a separate line.
My code:
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int model, String m) {
yearModel = model;
make = m;
speed = 0;
}
public int getYearModel() {
return yearModel;
}
public String getMake() {
return make;
}
public int getSpeed() {
return speed;
}
public int accelerate() {
speed += 5;
return speed;
}
public int brake(int b) {
b -= 5;
return b;
}
}
class CarDemo {
public static void main(String[] args) {
Car c = new Car(1992, "Mustang");
int s = 0;
s = c.getSpeed();
for(int i = 0; i < 5; i++) {
System.out.println("The " + c.getYearModel() + " " + c.getMake() + "is going: " + s);
s = c.accelerate();
System.out.println("Now the " + c.getYearModel() + " " + c.getMake() + "is going: " + s);
}
}
}
Edit:
Based on the suggestions below, I have edited my code to the following; however, the system still says that my output is incorrect.
public class Car{
private int yearModel;
private String make;
private int speed;
public Car(int y, String m){
yearModel = y;
make = m;
speed = 0;
}
public int getYearModel(){
return yearModel;
}
public String getMake(){
return make;
}
public int getSpeed(){
return speed;
}
public void accelerate(){
speed += 5;
}
public void brake(){
speed -= 5;
}
}
class CarDemo{
public static void main(String[] args){
Car theCar = new Car(2010, "Porsch");
for(int i = 0; i < 5; i++){
theCar.accelerate();
System.out.println(theCar.getSpeed());
}
for(int count = 0; count < 5; count++){
theCar.brake();
System.out.println(theCar.getSpeed());
}
}
}
for brake you need to do speed -= 5, not b -= 5. Also I do not think the brake method needs an input argument.
In addition you accelerate 5 times but never brake
Your main issue is the brake method. The requirements state that it should subtract 5 from the current speed. So, you should make it like your accelerate method, but subtracting 5 instead of adding. It shouldn't take in a parameter.
Also, I don't know if this would cause an issue, but your accelerate and brake methods shouldn't return the speed, according to the requirements. Change their return types to void, and remove the return statements.
Lastly, You test main doesn't do exactly what the requirements say to do. Read it carefully to see what it should do, and do EXACTLY what it says.
Follow the specification.
The spec says:
accelerate: The accelerate method should add 5 to the speed field when it is called.
brake: The brake method should subtract 5 from the speed field each time it is called.
These 2 methods have no return type and take no arguments.
So, they should be:
public void accelerate() {
speed += 5;
}
// brake should not take an argument
public void brake() {
// this should be speed, not b
speed -= 5;
}
Additionally, your demo should follow the spec (in comments):
class CarDemo {
public static void main(String[] args) {
//Demonstrate the class in a program that contains a Car object
Car c = new Car(1992, "Mustang");
for (int i = 0; i < 5; i++) {
//and then calls the accelerate method five times.
c.accelerate();
//After each call to the accelerate method, get the current speed of the car and print it on a separate line.
System.out.println(c.getSpeed());
}
for (int i = 0; i < 5; i++) {
//Then, call the brake method five times,
c.brake();
//each time printing the current speed of the car on a separate line.
System.out.println(c.getSpeed());
}
}
}
When working off of a well-written, explicit specification as has been provided for your assignment, it can be very helpful to do what I've done above--include the spec as comments and fill in the code around them.
You're printing The " + c.getYearModel() + " " + c.getMake() + "is going: " + s 5 times. You should put that outside the loop so it's printed once only.
IMHO I don't think you need to be returning the speed from the accelerate() function either. I'd suggest making that a void function and using the getSpeed() method instead of assigning to an intermediate variable.
I am currently taking the Prog Fund I & II class. If you are using Pearson, then this should help. I had the answer correct the first time. You just have to format it correctly in the proper order as so.
import java.util.Scanner;
public class Car
{
private int yearModel; // Holds the car's year model
private String make; // Holds the make of the car
private int speed; // Holds the car's current speed
public static void main(String[] args)
{
// Creates car object
Car vehicle = new Car(2018, "Barbie Mobile");
// Creates object for user input
Scanner keyboard = new Scanner(System.in);
// Holds the speed of the car
int speed = 0;
// Calls accelerate 5 times
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
// Calls break 5 times
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
}
public Car(int year, String maker)
{
// Assigns values to car's year model and make
yearModel = year;
make = maker;
// Assigns 0 to the speed field
speed = 0;
}
/* #return gets year model */
public int getYearModel()
{
return yearModel;
}
/* #return The speed */
public int getSpeed()
{
return speed;
}
/* #return Gets the making of car */
public String getMake()
{
return make;
}
/* Adds 5 to speed when called */
public void accelerate()
{
speed += 5;
}
/* Subtracts 5 from speed when called */
public void brake()
{
speed -= 5;
}
}
I am taking the same class right now, using Pearson Revel. If anyone else comes across this problem, this should help.. Spoiler alert, I will be posting the answer to the problem below
Pearson Revel is such a pain in the butt, they do a horrible job describing how they want the programs structured and output displayed, and if anything is off by even one space or something similar, you lose all points. That being said, the problem demonstrates the calling of the program under "Sample Run" as java Car. So it sounds like the main program that creates a Car object and calls all of it's methods is within the same class (test it out in a text editor, you'll see that if you create a seperate class under the Car class and call Car.java from the command line, it will throw an error; stating the class Car does not have a main. So therefore, it's safe to say you need to create the main method inside of the Car class (wish they would just say that, right?).
Here is my graded & passing answer.
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int year, String make) {
this.yearModel = year;
this.make = make;
this.speed = 0;
}
public void brake() {
this.speed -= 5;
}
public void accelerate() {
this.speed += 5;
}
public int getSpeed() {
return this.speed;
}
public String getMake() {
return this.make;
}
public int getYearModel() {
return this.yearModel;
}
public static void main(String[] args) {
Car myCar = new Car(2019, "Tacoma");
for (int i=0;i < 5;i++) {
myCar.accelerate();
System.out.println(myCar.getSpeed());
}
for (int i=0;i < 5;i++) {
myCar.brake();
System.out.println(myCar.getSpeed());
}
}
}
And here is Revel's suggested answer after completion
public class Car {
public static void main(String[] args) {
Car batmobile = new Car(1965, "Bat Mobile");
for(int i=0; i<5; i++){
batmobile.accelerate();
System.out.println(batmobile.getSpeed());
}
for(int i=0; i<5; i++){
batmobile.brake();
System.out.println(batmobile.getSpeed());
}
}
private int yearModel;
private String make;
private int speed;
public Car(int yearModel, String make){
this.yearModel = yearModel;
this.make = make;
this.speed = 0;
}
public int getYearModel(){
return this.yearModel;
}
public String getMake(){
return this.make;
}
public int getSpeed(){
return this.speed;
}
public void accelerate(){
this.speed += 5;
}
public void brake(){
this.speed -= 5;
}
}
So basically I'm doing a java tutorial but in order to follow along I need to make a class file. Everything was already given to me but it gives me an error. The error is: Delete else statement or something along those lines. But when I delete it it tells me to put another else statement there.
The code is : Is this a problem with eclipse or is there something wrong with the code?
import java.io.*;
import java.text.*;
public class In {
static InputStreamReader r = new InputStreamReader(System.in);
static BufferedReader br = new BufferedReader(r);
// Read a String from the standard system input
public static String getString() {
try {
return br.readLine();
} catch (Exception e) {
return "";
}
}
// Read a number as a String from the standard system input
// and return the number
public static Number getNumber() {
String numberString = getString();
try {
numberString = numberString.trim().toUpperCase();
return NumberFormat.getInstance().parse(numberString);
} catch (Exception e)
{
// if any exception occurs, just return zero
return new Integer(0);
}
}
// Read an int from the standard system input
public static int getInt() {
return getNumber().intValue();
}
// Read a long from the standard system input
public static long getLong() {
return getNumber().longValue();
}
// Read a float from the standard system input
public static float getFloat() {
return getNumber().floatValue();
}
// Read a double from the standard system input
public static double getDouble() {
return getNumber().doubleValue();
}
// Read a char from the standard system input
public static char getChar() {
String s = getString();
if (s.length() >= 1)
return s.charAt(0);
else
return’\ n’;
}
}
What is actually causing the error here is that whatever messed up marks you have around \n are not apostrophes... I have no idea what they are. After rewriting the code exactly as you did, except with apostrophes (plus using curly braces in the if and else statements because I prefer it that way), there were no errors:
public static char getChar ()
{
String s = getString();
if (s.length() >= 1){
return s.charAt(0);
}else{
return '\n';
}
}
Please, in the future, make sure to use correct indentations in your questions to make it much easier for us to read.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am a java noob. I keep getting errors in the main method. Please help! I think I'm not calling the methods the right way. Everything else should be working.
import java.util.Scanner;
public class Assignment5 {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
inputName(kbd);
inputIncome(kbd);
inputMarried(kbd);
calculateThreshold();
incomeBelowThreshold();
incomeAboveThreshold();
taxBelowThreshold();
taxAboveThreshold();
totalTaxes();
displayResults();
}
public static String inputName (Scanner kbd) {
System.out.print("What is your name?");
String name = kbd.nextLine();
return name;
}
public static double inputIncome (Scanner kbd) {
System.out.print("What is your annual income?");
double userIncome = kbd.nextDouble();
return userIncome;
}
public static char inputMarried (Scanner kbd) {
System.out.print("Are you married? (y for yes, n for no)");
char married = kbd.next().charAt(0);
return married;
}
public static double calculateThreshold (char married) {
double incomeThreshold;
if (married == 'y') {
incomeThreshold = 80000;
} else {
incomeThreshold = 40000;
}
return incomeThreshold;
}
public static double incomeBelowThreshold (double userIncome , double incomeThreshold) {
double incomeBelowThreshold;
if (userIncome <= incomeThreshold) {
incomeBelowThreshold = incomeThreshold - userIncome;
} else {
incomeBelowThreshold = userIncome;
}
return incomeBelowThreshold;
}
public static double incomeAboveThreshold (double userIncome, double incomeThreshold) {
double incomeAboveThreshold;
if (userIncome >= incomeThreshold) {
incomeAboveThreshold = incomeThreshold - userIncome;
} else {
incomeAboveThreshold = 0;
}
return incomeAboveThreshold;
}
public static double taxBelowThreshold (double incomeBelowThreshold) {
double taxBelowThreshold;
taxBelowThreshold = incomeBelowThreshold * .25;
return taxBelowThreshold;
}
public static double taxAboveThreshold (double incomeAboveThreshold) {
double taxAboveThreshold;
taxAboveThreshold = incomeAboveThreshold *.35;
return taxAboveThreshold;
}
public static double totalTaxes (double taxBelowThreshold, double taxAboveThreshold) {
double totalTaxes;
totalTaxes = taxBelowThreshold + taxAboveThreshold;
return totalTaxes;
}
public static void displayResults (String Name, char married, double income, double totalTaxes) {
System.out.print("Name:" + Name);
String marriedStatus;
if (married == 'y') {
marriedStatus = "Married";
} else {
marriedStatus = "Single";
}
System.out.print("Marital Status:" + marriedStatus);
System.out.printf("Income: %.2f" + income);
System.out.printf("Taxes: %.2f" + totalTaxes);
}
}
It looks like some of your methods are expecting arguments and you are not providing them.
For example
public static double calculateThreshold (char married){}
you cannot call this method calculateThreshold();
You need to pass in the char for married
calculateThreshold ('y');
THANK YOU!!!!!!
calculate threshold(char) in the type Assignment 5 is not applicable for the arguments ()
In the future, please ALWAYS post as much information about the actual error as possible. Don't make everybody guess :)
In this case:
1) Save the return value of "married":
public static void main(String[] args) {
...
char married = inputMarried(kbd);
2) Then pass it to "calculateThreshold()". Save the return value of "threshold() while you're at it:
...
double threshold = calculateThreshold (married);
3) Be sure to do the same for the rest of your program.
One error is that you have methods that require a parameter, but you are not passing one. calculateThreshold(), for instance, takes one parameter, and incomeBelowThreshold() takes two. You are also not returning values from your input routines; this is not an error, but may be flagged as a warning (depending on how you're editing and compiling your stuff), but you're going to need the values from your input routines to pass to your other routines, possibly converting them beforehand.
Actually all your methods return some answers in which it is suppose to deliver to the next method or so...
Your mistake is you are not assigning the returned values to a variable..so please correct it
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
inputName(kbd);
inputIncome(kbd);
inputMarried(kbd);
// modify this line calculateThreshold();
calculateThreshold('a');
// modify this line incomeBelowThreshold();
incomeBelowThreshold(2.1, 2.2);
// modify this line incomeAboveThreshold();
incomeAboveThreshold(2.1, 2.2);
// modify this line taxBelowThreshold();
taxBelowThreshold(2.1);
// modify this line taxAboveThreshold();
taxAboveThreshold(2.1);
// modify this line totalTaxes();
totalTaxes(2.1, 2.1);
// modify this line displayResults();
displayResults("",'a', 2.1, 2.1);
}
I've been working on this program for a few weeks now, it's our final project in my Java programming class and it has been giving me (and a lot of other students) some pretty good headaches.
We need to create a program that allows a user to enter, display and remove new planes along with the plane's speed, altitude and type of plane.
I've been having the most problems with getting the main class to communicate with the other classes. Because of this, I don't know if my LinkedList is going to work properly, or if at all. I'm worried that the list is not going to properly store all the fields together and that the node is not properly coded.
I could really use any help or advice you can provide. Code is below. I'm open to any and all suggestions. The code does not have to stay in exactly the same classes it is currently in. If something would work better somewhere else, I'd be happy to try it.
Main Class. This is where the user will be interacting with the program. I have been having a hard time getting the methods from other classes to work in this class. I'm sure it is something simple that I am missing.
package airTraffic;
import java.util.*;
public class Main {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
do {
try {
System.out.println("Please enter command to proceed: ");
System.out.println("Enter new aircraft = e");
System.out.println("Display all aircraft = d");
System.out.println("Show specific flight = s");
System.out.println("Remove specific flight = r");
String command = in.next();
in.next(command);
if ( (in.next(command)).equals("e") ) {
ATControl.addToList(); // need to somehow "start" this class
} else if ( (in.next(command)).equals("d") ) {
ATControl.displayAll();
} else if ( (in.next(command)).equals("s") ){
ATControl.showFlight();
} else if ( (in.next(command)).equals("r") ) {
ATControl.removeFlight();
} else if ( (in.next(command)).equals(null) ) {
}
} catch (InputMismatchException exc) {
System.out.println("Wrong entry, please try again:");
}
} while (true);
}
}
Linked List and Node - I called it Aircraft. I think this is where the list is stored and created. Manipulation to the list occurs in the next class (ATControl), or at least I think it will.
package airTraffic;
import java.util.LinkedList;
public class Aircraft {
// stores data
private static final int INITIAL_ALLOCATION = 20;
private int size = INITIAL_ALLOCATION;
//declare LinkedList and node names
static LinkedList <String> list = new LinkedList <String> ();
private Aircraft head = new Aircraft ();
private Aircraft tail = new Aircraft ();
// tells list to add nodes
public void addNodes (int n, LinkedList<String> s) {
s = list;
head.next = tail;
tail.next = tail;
size = n;
Aircraft temp = head;
for (int i= 0; i < size; ++i) {
temp.next = new Aircraft ();
temp = temp.next;
}
temp.next = tail;
}
private String value;
Aircraft craft;
public Aircraft (String v) {
value = v;
}
public Aircraft () {
}
public String get () {
return value;
}
public void set (String v) {
value = v;
}
public Aircraft next = null;
//auto generated method from ATControl
public static void add(String flight) {
// a for or while loop might be needed here. Seems to easy to just have an empty add class
}
//auto generated method from ATControl
public static void remove() {
}
}
ATControl class. This is where (I think) the list is manipulated, allowing the user to add, remove and show the flights.
package airTraffic;
import java.util.*;
public class ATControl{
// implement Aircraft class (node) - empty argument list??
Aircraft aircraft = new Aircraft ();
static Scanner in = new Scanner (System.in);
// list of planes
static String [] planeList = {"Wide-body Airliner = w", "Regional Airliner = r", "Private Plane = p",
"Military = m", "Cargo only: c", "Unknown = u"};
//add plane and details
public static void addToList () {
System.out.printf("Enter flight number: ");
String flight = in.nextLine();
Aircraft.add(flight);
//type of plane
System.out.printf("Enter type of plane, ", "Choose from: " + planeList);
String type = in.nextLine();
try {
if (type == "w") {
System.out.println("Wide-body Airliner");
}else if (type == "r") {
System.out.println("Regional Airliner");
}else if (type == "p") {
System.out.println("Private Plane");
}else if (type == "m") {
System.out.println("Military");
}else if (type == "c") {
System.out.println("Cargo only");
}else if (type == "u") {
System.out.println("Unknown");
} else type = null;
}
catch (InputMismatchException i) {
System.out.println("You must enter valid command: " + planeList);
}
Aircraft.add(type);
//plane speed
System.out.printf("Enter current speed: ");
String speed = in.nextLine();
Aircraft.add(speed);
//add Altitude
System.out.printf("Enter current altitude: ");
String alt = in.nextLine();
Aircraft.add(alt);
}
//show flight
public static void showFlight () {
System.out.printf("Enter flight number for details: ");
in.nextLine();
Aircraft.get(Aircraft, index);
}
// display all flights
public static void displayAll () {
System.out.printf("All flights: " );
}
//remove flight
public static void removeFlight () {
System.out.printf("Enter flight number to be removed: ");
in.nextLine();
Aircraft.remove();
}
}
Any ideas? Thank you!
To "start" ATControl, you need to create a new instance of it:
ATControl control = new ATControl();
control.addToList();
Same with your Aircraft. You will want to create new instances with new, and then call Add(), etc. on them.
You will also probably want to pass your Scanner from main into the new ATControl and use it to read the input, instead of using a brand new Scanner
When using object oriented design, think of your objects as representations of actual objects. Your aircraft class should represent an actual aircraft. The aircraft should keep track of things that are associated with it. So things like flight number, speed, altitude, etc.. should be properties of that class.
public class Aircraft{
private int speed;
private int altitude;
private int flightNum;
//
//Regional Airliner, Military, Private Plane, etc.
private String type;
public void setSpeed(int speed){
this.speed = speed;
}
public int getSpeed(){
return speed;
}
//
//TODO: Getters and Setters for the rest of the aircraft properties
}
Now pretty much everything else should be handled by your ATControl class. An array list of type Aircraft seems much more logical to use in this case.
public class ATControl{
private ArrayList<Aircraft> currentFlights;
//
//Constructor gets called on initialization
public ATControl(){
currentFlights = new ArrayList<Aircraft>();
}
//
//User input should be handled in main class and passed into this
public void addFlight(int flightNum, int speed, int altitude){
Aircraft newCraft = new Aircraft();
//
//assign the properties we just got from the user to our new aircraft
newCraft.setFlightNumber(flightNum);
newCraft.setSpeed(speed);
//
//Now add our new flight to the list of current flights
currentFlights.add(newCraft);
}
}
Your main class can remain pretty much as you have it. I would handle all user input there, though.
public class Main {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
ATControl denverTrafficControl = new ATControl();
//
//Handle user input here: get the speed, altitude, flightNum, etc..
denverTrafficControl.addFlight(flightNum, speed, altitude);
}
}
This is how it should be done. Hopefully this has helped you grasp the objected oriented design a bit better. Let the main class handle I/O and your other actual "object" classes handle the data. Good luck.
Your general design seems to ignore object oriented principles. As I see it, aircraft should hold its type, speed and altitude together in one object.
Why reinvent the wheel? There are plenty of premade (and well tested) collection classes already built into the JRE (e.g. ArrayList, LinkedList). Make use of them to hold your aircraft instances.
These two changes should drastically reduce the amount of code you need to write/maintain and the overall complexity of the program should be reduced considerably.
I come across few of the times called helper objects... can anybody elaborate what are those helper objects and why do we need them?
Some operations which are common to a couple of classes can be moved to helper classes, which are then used via object composition:
public class OrderService {
private PriceHelper priceHelper = new PriceHelper();
public double calculateOrderPrice(order) {
double price = 0;
for (Item item : order.getItems()) {
double += priceHelper.calculatePrice(item.getProduct());
}
}
}
public class ProductService {
private PriceHelper priceHelper = new PriceHelper();
public double getProductPrice(Product product) {
return priceHelper.calculatePrice(product);
}
}
Using helper classes can be done in multiple ways:
Instantiating them directly (as above)
via dependency injection
by making their methods static and accessing them in a static way, like IOUtils.closeQuietly(inputStream) closes an InputStream wihtout throwing exceptions.
at least my convention is to name classes with only static methods and not dependencies XUtils, and classees that in turn have dependencies / need to be managed by a DI container XHelper
(The example above is just a sample - it shouldn't be discussed in terms of Domain Driven Design)
These are objects that "sit to the side" of the main body of code, and do some of the work for the object. They "help" the object to do it's job.
As an example, many people have a Closer helper object. This will take various closeable objects, for example, java.sql.Statement, java.sql.Connection, etc and will close the object, and ignore any errors that come out of it. This tends to be because if you get an error closing an object, there is not much you can do about it anyway, so people just ignore it.
Rather than having this boilerplate:
try {
connection.close();
} catch (SQLException e) {
// just ignore… what can you do when you can't close the connection?
log.warn("couldn't close connection", e);
}
scattered around the codebase, they simply call:
Closer.close(connection);
instead. For example, look at guava closeQuietly.
A 'helper' method is typically a method to make something easier, whatever it is. Sometimes they're used to make things more readable/clearly organized (some may argue this, but it's ultimately very subjective):
public void doStuff() {
wakeUp();
drinkCoffee();
drive();
work();
goHome();
}
Where, each 'helper method' on their own are fairly complex... the concept becomes really clear and simple.
Another very good use of helper methods is to provide common functionality across many different classes. The best example of this is the Math class which contains a ton of static helper methods to help you calculate things like the log of a number, the exponent of a number... etc.
Where you draw the line as to what's a helper method and what's just a regular method is pretty subjective, but that's the gist of it. Other answers here are pretty good too.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Helpers {
public static String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
return dateFormat.format(new Date());
}
public static boolean isTimeABeforeTimeB(String timeA, String timeB) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
Date dA = dateFormat.parse(timeA);
Date dB = dateFormat.parse(timeB);
if (dA.getTime() < dB.getTime()) {
return true;
} else {
return false;
}
} catch (Exception e) {
//
}
return false;
}
public static String getDateAndTimeInput(String prompt) {
Scanner input = new Scanner(System.in);
String ans;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
dateFormat.setLenient(false);
boolean dateValid;
do {
System.out.print(prompt);
ans = input.nextLine();
ans = ans.trim();
dateValid = true;
try {
Date d = dateFormat.parse(ans);
} catch (Exception e) {
dateValid = false;
}
} while (!dateValid);
return ans;
}
public static String getStringInput(String prompt) {
Scanner input = new Scanner(System.in);
String ans;
do {
System.out.print(prompt);
ans = input.nextLine();
ans = ans.trim();
} while (ans.length() == 0);
return ans;
}
public static double getDoubleInput(String prompt) {
Scanner input = new Scanner(System.in);
double ans = 0;
boolean inputValid;
do {
System.out.print(prompt);
String s = input.nextLine();
//Convert string input to integer
try {
ans = Double.parseDouble(s);
inputValid = true;
} catch (Exception e) {
inputValid = false;
}
} while (!inputValid);
return ans;
}
public static int getIntegerInput(String prompt) {
Scanner input = new Scanner(System.in);
int ans = 0;
boolean inputValid;
do {
System.out.print(prompt);
String s = input.nextLine();
// Convert string input to integer
try {
ans = Integer.parseInt(s);
inputValid = true;
} catch (Exception e) {
inputValid = false;
}
} while (!inputValid);
return ans;
}
public static int getIntegerInput(String prompt, int lowerBound, int upperBound) {
Scanner input = new Scanner(System.in);
int ans = 0;
boolean inputValid;
do {
System.out.print(prompt);
String s = input.nextLine();
// Convert string input to integer
try {
ans = Integer.parseInt(s);
if (ans >= lowerBound && ans <= upperBound) {
inputValid = true;
} else {
inputValid = false;
}
} catch (Exception e) {
inputValid = false;
}
} while (!inputValid);
return ans;
}
}
that is an example of of a Helper Class. It contains method which of are common use of the other classes in the project.
Example if someone wants to enter an Integer number from a class hew ill have to type in this: String num = Helpers.getIntegerInput("input your number");
The prompt is the output that is show to the user. Other examples to input a String, double, date and time etc.
Helper class, in my opinion, is similar to normal functions declared outside of classes in C++. For example, if you need a global constant for many classes, then you can define a helper class that encloses a final static const variable.
You can see a helper class as a toolbox that can be used by other classes to perform task like testing if a string is a palindrome, if a given number is prime, if an array contains negative number etc. You can create helper class by making all its methods static and its constructor private, and optionally you can also make the class final. Thus it can not be instantiated and one can easily access to all its methods directly.
public final class HelperClass{
private HelperClass(){
}
public static boolean isPositive(int number) {
if (number >= 0)
return true;
else
return false;
}
}
Here the function can be use directly to test a number :
HelperClass.isPositive(5);
this helper class help you to validate multiple edit text fields at once
public class MyHelperClass {
public void toast(Context context, String message){
Toast toast=new Toast(context);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setText(message);
toast.show();
}
public void validateEditText(Context context,List<EditText> editTextList)
{
boolean result=false;
for (int i=0;i<editTextList.size();i++)
{
if (editTextList.get(i).getText().toString().trim().equals(""))
{
result=true;
toast(context," Required fields are not empty !");
i=editTextList.size();
}
}
}
}