Java: Using Try/Catch Exception to check if user input is Double - java

I am writing a simple program that allows a user to enter two separate doubles for a foot and inch measurement. The program is intended to take these values and convert them to centimeters and output them. Additionally I am to include two exceptions: one to make sure the numeric values are positive and not negative (this one I have completed) and another to make sure the input entered is a double value and not a string value (this one I am having a hard time with). So if a user enters an input... for example 'Bill' instead of a number, it is to display an error message and ask the user to re-enter the input values again.
It seems like perhaps I would be best off gathering the user input as a string (rather than doubles as I currently am), which I convert to doubles and return them as doubles to their corresponding methods: getFootValue() and getInchValue() -- but I am not too sure.
How should I go about implementing this by way of a custom exception? I cannot simply utilize the InputMismatchException, I need to make my own titled NonDigitNumberException().
Here is what I have so far...
import java.util.Scanner;
public class Converter
{
private double feet;
private double inches;
public Converter(double feet, double inches)
{
this.feet = feet;
this.inches = inches;
}
public double getFootValue()
{
return feet;
}
public double getInchValue()
{
return inches;
}
public double convertToCentimeters()
{
double inchTotal;
inchTotal = (getFootValue() * 12) + getInchValue();
return inchTotal * 2.54;
}
public String toString()
{
return ("Your result is: " + convertToCentimeters());
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class TestConverter
{
public static void main(String[] args)
{
/* Create new scanner for user input */
Scanner keyboard = new Scanner(System.in);
do
{
try
{
/* Get the feet value */
System.out.print("Enter the foot value: ");
double feet = keyboard.nextDouble();
if (feet < 0) throw new NegativeNumberException();
/* Get the inches value */
System.out.print("Enter the inch value: ");
double inches = keyboard.nextDouble();
if (inches < 0) throw new NegativeNumberException();
else
{
Converter conversion = new Converter(feet, inches);
/* Print the converted result */
System.out.println(conversion);
break;
}
} catch(InputMismatchException ignore){}
catch(NegativeNumberException error)
{
System.out.println("A negative-numeric value was entered, please enter only positive-numeric values...");
}
}while(true);
/* Close the keyboard */
keyboard.close();
}
}
class NegativeNumberException extends Exception
{
public NegativeNumberException()
{
super();
}
public NegativeNumberException(String errorMessage)
{
super(errorMessage);
}
}
Thanks for any help!

You're over complicating things. You can simply use the Scanner.hasNextDouble() method.
Example:
Assuming this code is inside your main method.
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter value");
double myValue = 0;
if(scanner.hasNextDouble()){
myValue = scanner.nextDouble();
}else{
System.out.println("Wrong value entered");
}
}
}
you can then go on and use myValue with your Converter class.
UPDATE
It seems that you must create your own exception class according to what you have told me within the comments. So, I have decided to implement that for you and hopefully, you can be able to carry on from here.
Custom Exception Class
public class NonDigitNumberException extends InputMismatchException {
public NonDigitNumberException(String message){ // you can pass in your own message
super(message);
}
public NonDigitNumberException(){ // or use the default message
super("input is not a digit");
}
}
Negative Number Exception Class
public class NegativeNumberException extends IllegalArgumentException {
public NegativeNumberException(String message){ // you can pass in your own message
super(message);
}
public NegativeNumberException(){ // or use the default message
super("negative number is not valid");
}
}
Validator Method
public static double inputValidator(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter a value"); // prompt user for input
String getData = scanner.next(); // get input
if(getData.length() >= 1){
if(!Character.isDigit(getData.charAt(0)) && getData.charAt(0) != '-') throw new NonDigitNumberException();
}
for (int i = 1; i < getData.length(); i++) {
if(!Character.isDigit(getData.charAt(i))) throw new NonDigitNumberException();
}
return Double.parseDouble(getData); // at this point the input data is correct
}
Negative Number Validator
public static boolean isNegative(double value){
if(value < 0) throw new NegativeNumberException();
return false;
}
Main method
public static void main(String[] args) {
try {
double myValue = inputValidator();
System.out.println(isNegative(myValue)); // check if number is negative
}catch (NegativeNumberException e){
e.printStackTrace();
}
catch (NonDigitNumberException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}

Do you really need a custom exception? Because keyboard.nextDouble() already throws InputMismatchException if the input is not a double.
Instead of ignoring the exception, you should show an error message (saying the user didn't type a number).

I guess, you are mixing things up:
You have to validate the input of the user first, if it is a double. If it is not, then you are getting an InputMismatchException.
Then you have to validate the input, if it is valid for your converter (is it positive?). Here you can throw your custom exception.
And then you call your Converter, which might also throw your custom exception.
So my solution would be:
import java.util.Scanner;
import java.util.InputMismatchException;
public class TestConverter {
public static void main(String[] args) {
/* Create new scanner for user input */
Scanner keyboard = new Scanner(System.in);
do {
double feet = -1, inches = -1;
Exception exception;
do {
exception = null;
/* Get the feet value */
System.out.print("Enter the foot value (positive-numeric): ");
try {
feet = keyboard.nextDouble();
} catch (InputMismatchException e) {
keyboard.next();
exception = e;
}
} while (exception != null);
do {
exception = null;
/* Get the inches value */
System.out.print("Enter the inch value (positive-numeric): ");
try {
inches = keyboard.nextDouble();
} catch (InputMismatchException e) {
keyboard.next();
exception = e;
}
} while (exception != null);
try {
if (feet < 0) throw new NegativeNumberException();
if (inches < 0) throw new NegativeNumberException();
Converter conversion = new Converter(feet, inches);
/* Print the converted result */
System.out.println(conversion);
break;
}
catch(NegativeNumberException error) {
System.out.println("A negative-numeric value was entered, please enter only positive-numeric values...");
}
} while (true);
/* Close the keyboard */
keyboard.close();
}
}
Output
Enter the foot value (positive-numeric): test
Enter the foot value (positive-numeric): 1234
Enter the inch value (positive-numeric): test
Enter the inch value (positive-numeric): 1234
Your result is: 40746.68

Related

all the Numberformat exception below the one which recently got caught are executed on their own

My programs gets two students name and three subject marks and calculate average of the student.In the middle i got to catch numberFormatexception if mark is other than integer and other two user defined exception.
whenever the numberFormatexception is caught,the other numberformatecxceptions below are caught on their own.
import java.util.*;
class ude1 extends Exception
{
public ude1()
{
System.out.println("User defind exception 1 thrown");
}
public String toString()
{
return "NegativeValueException";
}
}
class ude2 extends Exception
{
public ude2()
{
System.out.println("User defind exception 2 thrown");
}
public String toString()
{
return "ValueOutofBouundException";
}
}
class excep6
{
/* String stud_name;
int mark1,mark2,mark3;
excep6(String name,int a,int b,int c)
{
stud_name=name;
mark1=a;
mark2=b;
mark3=c;
}
public void calculator()
{
float avg=0;
avg=(mark1+mark2+mark3)/3;
System.out.println("The average of "+stud_name+" is "+avg);
} */
public static void main(String []args)
{
Scanner in = new Scanner(System.in);
int a=0,b=0,c=0,l=2;
String std="";
while(l>0)
{
try{
System.out.println("enter student name");
std=in.next();
System.out.println("enter mark1");
if(in.hasNextInt())
a=in.nextInt();
else
throw new NumberFormatException();
if(a<0)
{
throw new ude1();
}
if(a>100)
{
throw new ude2();
}
}
catch(ude1 u1)
{
System.out.println(u1.toString());a=0;
}
catch(ude2 u2)
{
System.out.println(u2.toString());a=0;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormat Exception");a=0;
}
System.out.println("enter mark2");
try{
if(in.hasNextInt())
b=in.nextInt();
else
throw new NumberFormatException();
if(b<0)
{
throw new ude1();
}
if(b>100)
{
throw new ude2();
}
}
catch(ude1 u1)
{
System.out.println(u1.toString());b=0;
}
catch(ude2 u2)
{
System.out.println(u2.toString());b=0;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException Exception");b=0;
}
System.out.println("enter mark3");
try{
if(in.hasNextInt())
c=in.nextInt();
else
throw new NumberFormatException();
if(c<0)
{
throw new ude1();
}
if(c>100)
{
throw new ude2();
}
}
catch(ude1 u1)
{
System.out.println(u1.toString());c=0;
}
catch(ude2 u2)
{
System.out.println(u2.toString());c=0;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException Exception");c=0;
}
System.out.println("The average of student "+std+" is "+(a+b+c)/3);
l--;
}
}
}
I expect
enter the name
sat
enter mark1
i
NumberFormat exception
enter mark2
34
enter mark3
56
the avg is 30
rather than
enter the name
sat
enter mark1
i
NumberFormat exception
enter mark2
NumberFormat exception
enter mark3
NumberFormat exception
enter the name
_
If you call hasNextInt() and it returns false, then call it again, it is guaranteed to return false again.
The hasNextInt() does NOT skip the token that is not an integer. It leaves in in the scanner so that you can attempt to read it as something else.
In most cases, the correct way to recover from unexpected input (e.g. a non-integer when an integer is expected) is to call nextLine() and discard the result. A nextLine() call will consume all characters up to and including the next end-of-line.
You should also take note of the comments about:
following style conventions in class names, and
inappropriate use of custom exceptions.

How does one pass parameters between methods and correctly call the method using Java?

The program should do the following:
Write a method called getheartRate that takes no parameters and returns an int (heartRate).
This method prompts the user for the patient's heart rate, reads
their input from the command line, and returns this value.
Write a method called checkHeartRate that takes an int parameter (the heart rate) and returns
a String (result). If the heart rate is above 100, return the value "High". If the heart rate is below
60, return the value "Low". Otherwise return "Normal".
Write a method called printHRResult that takes a String parameter, which is the result
from the method checkHeartRate. Print this value to the command line.
Call all three methods from the main method using appropriate parameter passing.
So far I have:
public class UnitSixInClassFall2018 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
UnitSixInClassFall2018 u = new UnitSixInClassFall2018();
u.getHeartRate();
System.out.println();
Scanner scan = new Scanner(System.in);
u.checkHeartRate(0);
// END MAIN
}
public int getHeartRate(){
System.out.print("Please enter your heart rate: ");
Scanner scan = new Scanner(System.in);
int heartRate = scan.nextInt();
return 0;
}
public void checkHeartRate(int heartRate){
if (heartRate > 100) {
String result = "High";
}
else if (heartRate < 60) {
String result = "Low";
}
else {
String result = "Normal";
}
}
public String printHRResults(String result) {
System.out.print("Your hear rate is " + result + ".");
return result;
}
}
When this is run, all that is output is "Please enter your heart rate: ". Once I enter an integer, the program ends. What is being done incorrectly?
You should change this method to return the heart rate like this:
public int getHeartRate(){
System.out.print("Please enter your heart rate: ");
Scanner scan = new Scanner(System.in);
int heartRate = scan.nextInt();
// Also add this
scan.close();
return heartRate;
}
And change this method to return the result:
public String checkHeartRate(int heartRate){
if (heartRate > 100) {
return "High";
}
else if (heartRate < 60) {
return "Low";
}
else {
return "Normal";
}
}
Then in your main method:
// get the heart rate
int heartRate = u.getHeartRate();
// Call the checkHeartRate method
String result = checkHeartRate(heartRate);
// call the printHRResults
printHRResults(result);
That should solve your problem.
First of all, you are creating two Scanner objects with the same input type (System.in), which isn't recommended. Instead, just make one Scanner object and use it everywhere in your program. This post has some good info.
An improved version of your code with an improved use of the Scanner object is as follows:
public UnitSixInClassFall2018 {
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
NewMain u = new NewMain();
int heartRate = u.getHeartRate();
System.out.println();
String result = u.checkHeartRate(heartRate);
u.printHRResults(result);
scan.close(); // Close the scanner once you are completely done using it
}
public int getHeartRate() {
System.out.print("Please enter your heart rate: ");
return scan.nextInt(); // Return the input of the user
}
public String checkHeartRate(int heartRate) {
String result = ""; // Initialize some default value
if (heartRate > 100) {
result = "High";
}
else if (heartRate < 60) {
result = "Low";
}
else {
result = "Normal";
}
return result; // Return the result calculated from the if-statements
}
public void printHRResults(String result) {
System.out.print("Your heart rate is " + result + ".");
// Originally this method returned a string but that seems unnecessary
}
}

Issues with InputMismatchException not being used properly

Im trying to create a code where I read a double and print out its square, but I also want it to know when the user enters a negative or non double constant and make them enter a new number. Im having trouble with the InputMismatchException. My code does not work properly, it compiles but the compiler just runs forever. Any suggestions would be helpful.
import java.util.*;
class constants
{
public static void main(String[] args)
{
double constant = getConstant();
System.out.println("Square of " + constant + " = " + constant*constant);
}
//-------------------------------------------------------------------------------
public static double getConstant()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter non-negative double constant");
double constant = kb.nextDouble();
try {
double selection = kb.nextDouble();
}
catch (InputMismatchException e) // where there is error.
{
System.out.println("Not a double constant. Re-enter");
}
return constant;
}
}
Here is how it can be done, the exception you need to catch is NumberFormatException. One thing though, negative numbers can still have squares, they just can't have square roots.
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
try {
double temp = kb.nextDouble();
//If the input is not a double, catch the number format exception
} catch (NumberFormatException e) {
e.printStackTrace();
}
//If the number is in proper format, (can be negative) print its square.
System.out.println("Square of " + temp+ " = " + temp*temp);
}
For some reason if you don't want to print squares of negative numbers, just check that condition before printing the result.
I understand that you are looking for the user to input such values as 15.65, 145.95, etc, but that -5.85 (negative) and 11 (integer value) should be rejected. The fact is, in java any integer is also a double
Example:
double x = 100; // is correct
double y = -15.85 // is correct
Therefore they will not generate an input mismatch exception. For that you have to check explicitely that these conditions are met and you will also have to explicitely throw the InputMismatchException.
It is also better to define your scanner once, for example as a global static variable (otherwise you may face issues if you use call getConstant() in a loop for example)
You don't need to define the selection double value. Here is an illustration that works
import java.util.InputMismatchException;
import java.util.Scanner;
class Constants
{
private static Scanner kb = new Scanner(System.in);
public static void main(String[] args)
{
double constant = getConstant();
if (constant >= 0) {
System.out.println("Square of " + constant + " = " + constant*constant);
}
}
//-------------------------------------------------------------------------------
public static double getConstant()
{
System.out.println("Enter non-negative double constant");
double constant=-1.0D;
try {
constant = kb.nextDouble();
// you don't want the negative value neither the integer value
// so you reject them by throwing the InputMismatchException
if (constant <0 || Math.floor(constant) == constant * 1.0D) {
constant = -1.0D;
throw new InputMismatchException("Not a double constant. Re-enter");
}
}
catch (InputMismatchException e) // where there is error.
{
System.out.println("Not a double constant. Re-enter");
}
return constant;
}
}

In Java, how can I use a variable initialized inside a try/catch block elsewhere in the program?

I have a basic quadratic formula program, but I've modified the beginning to end the program if any value other than a double is entered. However, because I've done this, I can't seem to be able to use the value inputted anywhere else in the program. Here are the first few lines:
import java.util.Scanner;
public class QuadraticFormula
{
public static void main(String[] args)
{
double a, b, c;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
}
The rest of the program asks for the values of b and c, and then carries out the quadratic equation, retuning the roots of whatever equation was entered. However, because the value of a is defined inside the try section, the compiler tells me that a hasn't been initialized. How do I fix this?
EDIT: I do want to use the data inputted by the user in the program (stored as doubleString)––but a number. My immediate problem is the compiler error, but is there any way to use the information inputted even though it's inside the try block? Because when I tried to equate double a to double doubleString outside the block it said doubleString didn't exist.
Like #Elliot Frisch said, you can just initialize a to a value (0) and take care that you don't get any wrong values due to failed parsing.
In your case this would probably mean to return/exit the program with the error message.
This is actually a common pattern.
import java.util.Scanner;
public class QuadraticFormula
{
public static void main(String[] args)
{
double a = 0, b, c;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
return;
}
//do work with a
Just initialize a when you declare it :
public static void main(String[] args)
{
double a = 0.0;
double b, c;
Scanner reads = new Scanner(System.in);
The other thing you can do is declare a as a "Class Property" :
public class QuadraticFormula
{
protected static double a = 0.0;
public static void main(String[] args)
{
double b, c;
Scanner reads = new Scanner(System.in);
try {
String doubleString = reads.nextLine();
QuadraticFormula.a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
}
Please note how the Class property (a) MUST be accessed using a static reference within main() as main() is static, which breaks the Java rule of using getter/setter to access Class properties. One thing I would recommend you should begin to learn how to package Class functionality outside of main()...outside of static references...
import java.util.Scanner;
public class QuadraticFormula {
protected double a = 0.0;
public static void main ( String[] args ) {
QuadraticFormula lnewItem = new QuadraticFormula();
try {
lnewItem.doSomething();
} catch ( Exception e ) {
e.printStackTrace();
}
}
public void doSomething () throws Exception {
double b, c;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
setA ( Double.parseDouble(doubleString) );
System.out.println("setA() - [" + getA() + "]");
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
}
}
public double getA () {
return a;
}
public void setA ( double a ) {
this.a = a;
}
}
Please note in the last section of code, all the static references are removed other than main(). New getter/setter methods are in place for the Class property a, thus enforcing Java's data encapsulation.
There are two fixes for this, one is to simply return from your main method when an exception is throw like so:
double a;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
return;
}
The other option stated by others is giving 'a' an initial value. I would suggest initializing it as NaN (Not a Number) and then checking it has been properly initialized before using it like so:
double a = Double.NaN;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
}
if(Double.isNaN(a)){
System.out.println("Variable 'a' is invalid, please enter a valid number.");
}
else {
double result = 2 * a;
}
instead of this line:
double a, b, c;
just replace it with this:
double a=0, b, c;

Inheriting from classes to get outputs.

I have been struggling for weeks with this issue. I cannot get a result for my calculations. I have all the methods within my Calculating class and have the user input within the Main class. Additionally At the end of my Main class I have created an object to inherit all the calculations from the Calculating class to get the results based on the inputs. It does not work. Any suggestions is highly appreciated.
//Calculating Class
public class Calculating { //Calculation class
//Declaring fields - Inputs
public double totalImpulse ;
public double averageImpulse;
public double timeEjectionChargeFires;
public double massEmptyVehicle;
public double engineMass;
public double fuelMass;
//Declaring variables for outputs
public double theAverageMassOfTheVehicle;
public Calculating() { //Constructor (inputs)
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires =timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
//Accessors and Mutators
//Methods used to calculate Average mass of the vehicle
public double theAverageMassOfTheVehicle() {
return massEmptyVehicle + ((engineMass + (engineMass - fuelMass) )/ 2); //Formula to calculate Average mass
}
//Setters
public void setTheAverageMassOfTheVehicle(double theAverageMassOfTheVehicle) {
this.theAverageMassOfTheVehicle = theAverageMassOfTheVehicle;
}//method
//Getters
public double getTheAverageMassOfTheVehicle() {
return theAverageMassOfTheVehicle;
}
}
//Master class
public class Master extends Calculating{ //Master class
public static void main( String args[] ) //Standard header for main method
{
UserEntry input = new UserEntry(); //Creating object from UserEntry class
//User entry for Total Impulse with exception handling
Double totalImpulse = null;
while(totalImpulse==null){
System.out.print("\nPlease enter Total impulse delivered: "); //System print line for input
try {
totalImpulse= input.gettotalImpulse(); //Instantiates totalImpulse from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Average Impulse with exception handling
Double averageImpulse = null;
while(averageImpulse==null){
System.out.print("Please enter Average Impulse delivered: "); //System print line for input
try {
averageImpulse= input.getaverageImpulse(); //Instantiates averageImpulse from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Time Ejection charge fires with exception handling
Double timeEjectionChargeFires = null;
while(timeEjectionChargeFires==null){
System.out.print("Please enter Time ejection charge fires: "); //System print line for input
try {
timeEjectionChargeFires= input.gettimeEjectionChargeFires(); //Instantiates timeEjectionChargeFires from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Mass of the empty vehicle with exception handling
Double massEmptyVehicle = null;
while(massEmptyVehicle==null){
System.out.print("Please enter The mass of the empty vehicle: "); //System print line for input
try {
massEmptyVehicle= input.getmassEmptyVehicle(); //Instantiates massEmptyVehicle from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Mass of the engine with exception handling
Double engineMass = null;
while(engineMass==null){
System.out.print("Please enter The mass of the engine: "); //System print line for input
try {
engineMass= input.getengineMass(); //Instantiates engineMass from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Fuel mass with exception handling
Double fuelMass = null;
while(fuelMass==null){
System.out.print("Please enter The mass of the fuel: "); //System print line for input
try {
fuelMass= input.getfuelMass(); //Instantiates fuelMass from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//Outputs based on user inputs
Calculating Master = new Calculating(); //Creates object of Calculating class
System.out.println("\nThe average mass of the vehicle: " +Master.theAverageMassOfTheVehicle() /1000);
}
}
The problem is with your constructor.
public Calculating() { //Constructor (inputs)
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires =timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
You are never passing any parameters, so how are you initalizing them?
A better constructor could be:
public Calculating(double totalImpulse, double averageImpulse,
double timeEjectionChargeFires, double massEmptyVehicle,
double engineMass, double fuelMass) {
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires = timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
Your Master class doesn't have to extend Calculating.
All you have to do within your main is to create a Calculating object initialized with the parameters you are taking from input.
Calculating calculations = new Calculating(totalImpulse,averageImpulse,timeEjectionChargeFires,massEmptyVehicle,engineMass,fuelMass);
Then you can call calculations.theAverageMassOfTheVehicle()

Categories

Resources