Calling a method adding input - java

I'm having problems finding out how to get the output based on the user inputs for my Main class. I already have keyboard entry where the users can enter a value, which will be held. I'm guessing I will need to use that e.g. (input.input1());. However I also need to include the method which calculates the result e.g calculations.theAverageMassFfTheVehicle from the CalculatingRocketFlightProfile class, I'm just not sure how to combine the two to get the result.
//Calculations class
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
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 double theVehiclesMaximumVelocity;
public CalculatingRocketFlightProfile(double totalImpulse, double averageImpulse, double timeEjectionChargeFires, double massEmptyVehicle,
double engineMass, double fuelMass) { //Constructor for this class
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires = timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
//Mutators and Accessors
//Accessors
//Methods for calculations - Calculating outputs, using inputs.
public double theAverageMassOfTheVehicle() {
return massEmptyVehicle + ((engineMass + (engineMass - fuelMass) )/ 2); //Formula to calculate Average mass
}//method
public double theVehiclesMaximumVelocity() { //Formula to calculate Maximum velocity
return totalImpulse / getTheAverageMassOfTheVehicle();
}//method
//Returns - GET
public double getTheAverageMassOfTheVehicle() {
return theAverageMassOfTheVehicle;
}//method
public double getTheVehiclesMaximumVelocity() {
return theVehiclesMaximumVelocity;
}//method
}//class
//Main class
public class Main { //Master class
public static void main( String args[] ) //Standard header for main method
{
kbentry input = new kbentry();
System.out.print("\nPlease enter a number for Total Impulse: " );
System.out.println("You have entered : " +input.input1());
System.out.print("\nPlease enter a number for Average Impulse: " );
System.out.println("You have entered : " +input.input2());
System.out.print("\nPlease enter a number for Time ejection charge fires: " );
System.out.println("You have entered : " +input.input3());
System.out.print("\nPlease enter a number for the Mass of the vehicle: " );
System.out.println("You have entered : " +input.input4());
System.out.print("\nPlease enter a number for the Mass of the engine: " );
System.out.println("You have entered : " +input.input5());
System.out.print("\nPlease enter a number for the Mass of the fuel: " );
System.out.println("You have entered : " +input.input6());
//Output
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile();
System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() +
"\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity());
}
}
//kbentry
public class kbentry{
double input1(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//Total Impulse entry
String strTotalImpulse = null; // These must be initialised
int intTotalImpulse = 0;
//System.out.print("Please enter a number for Total Impulse: ");
//System.out.flush();
// read string value from keyboard
try {
strTotalImpulse = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intTotalImpulse = Integer.parseInt(strTotalImpulse);
}
catch (NumberFormatException nfe) {
System.out.println("Error! Please enter a number!" + nfe.toString());
}

The problem is that you're CalcultingRocketFlightProfile class needs parameters, but you're creating calculations without passing any parameters to the new CalcultingRocketFlightProfile.
You should store those inputs in variables, then pass those variables to the constructor in your new CalcultingRocketFlightProfile that you declare.

Well, first off you are not actually passing any of your input to the Calculations class. I am not sure what input.input1() is or if you have an input class that you did not post. Either way you can do this a couple different ways.
First off give your input variables a meaningful name so you know which ones you are dealing with. Then pass all of your input.
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile(input1, input2, etc..)
or
Place all your input variables into your calculations class. Then store user input as calculations.totalImpulse, etc... Then you call your calculation methods to display answers.
-EDIT-
Just have 2 classes, your main and calculations class. There is no need for another class just to handle keyboard input.
Example
Main class
public class Main {
public static void main( String args[] ) {
Scanner keyboard = new Scanner(System.in);
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile();
System.out.print("\nPlease enter a number for Total Impulse: " );
calculations.totalImpulse = keyboard.nextDouble();
System.out.println("You have entered : " + calculations.totalImpulse);
}
}
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
// Do all of your maths, and methods for answer return
}
You were not actually taking the keyboard input and assigning it to anything. Using a scanner object you can assign the input to a variable in your calculations class. If you do that for all of them, you dont actually need a constructor in your calculations class, you just use it to do all that math and return answers.

Related

java returning and calling variables

I am new to java and I am trying to make this bmi calculator but I am having trouble returning and calling variables. I am sure that I am doing something very wrong but have been unable to figure out how to properly do this after searching the internet my guess is I do not know what I should be searching. I will post the code, I am getting 4 errors in my main that are as follows:
required: double,double,double,double
found: no arguments
reason: actual and formal argument lists differ in length
I am assuming that I have improperly set up my variables but could really use a bit of guidance. Thank you in advance.
import java.util.Scanner;
public class cs210 {
public double weight;
public double height;
public double bmi;
public double wcal;
public double mcal;
public double age;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
method1 ();
method2 ();
method3 ();
method4 ();
method5 ();
}
public static void method1 () {
System.out.println ("This program implements a Health Assistance Calculator ");
System.out.println ("Given a weight, height, and age, it will compute:\n");
System.out.println ("BMI - Body Mass Index");
System.out.println ("Calories needed per day to maintain weight");
}
public double method2 (double weight, double height, double wcal, double bmi) {
Scanner keyboard = new Scanner (System.in);
System.out.println ("Please enter your weight:");
weight = keyboard.nextDouble ();
System.out.println ("Press 1 if weight was entered in Kg \n Press 2 if weight was entered in Lbs");
double wunits = keyboard.nextDouble();
if (wunits == 1) {
System.out.println("Thank you");
} else if (wunits == 2){
weight = weight / 2.2;
System.out.println("Thank you");
}
else {
System.out.println ("Please try again");
return 0;
}
System.out.println("Please enter your height:");
height = keyboard.nextDouble ();
System.out.println ("Press 1 if height was entered in meters \n Press 2 if height was entered in inches");
int hunits = keyboard.nextInt();
if(hunits ==1) {
System.out.println("Thank you");
} else if (hunits == 2){
height = height / 0.0254;
}else {
System.out.println("Please try again");
return 0;
}
System.out.println("Please enter your age in years:");
age = keyboard.nextDouble ();
bmi = weight / Math.pow(height, height);
return ( bmi + age + height + weight);
}
public static double method3(double weight, double age, double height) {
double paf = 1.375;
double mcal;
mcal = (13.397 * weight + 4.799 * height + 5.677 * age + 88.362) * paf;
return mcal;
}
public static double method4(double weight, double age, double height, double paf){
double wcal;
wcal = (93247 * weight + 3.098 * height - 4.330 * age + 447.593) * paf;
return wcal;
}
public double method5(double bmi, double mcal, double wcal){
System.out.println("Your BMI is:" + bmi);
System.out.println("A BMI in the range of 18.5 to 24.9 is considered normal\n");
System.out.println("To maintain your current weight:");
System.out.println("Men need" + mcal + "per day");
System.out.println("Women need" + wcal + "per day");
return 0;
}
}
You define method2 like this:
public double method2 (double weight, double height, double wcal, double bmi) {
// ...
It has four parameters, all double, just like your error message said. Then you call it like this:
method2 ();
Without any parameters at all, again just like the error message said. Since you defined it with four parameters, every time you call it you need to do it with four parameters. The values you use as parameters will be the values that the variables weight, height, wcal and bmi gets inside the function, and if you don't have any parameters the computer will not know what values to use for those variables and therefore throw an error to complain. So you could, as an example, do it like this:
method2(34.9, 23.4, 23.5, 34.1); // Just picked four random numbers here.
But looking at the structure of your program, it looks like you don
t want to pass any values to the function at all (since you let the user enter the values inside the function). Then you could just get rid of the parameters, and declare the variables inside the function:
public double method2 () {
double weight, height, wcal, bmi;
// ...
Now the variables will be available inside method2, but not anywhere else. If you want to use the same values later in the other functions, you could instead of declaring them inside your function declare them in your class, and they will become available anywhere in your class, but not anywhere else.
You will have to fix the same issue with the parameters for method3, method4 and method5 as well.
You need to pass parameters when you call to methods. If you call to method
public double method2 (double weight, double height, double wcal, double bmi)
You need to call it to like this method2 (50, 2, 200, 25.5);
When you call in to your other methods such as method3, method4, method5 ; you have to give appropriate parameters to those. But when it comes to your method1. It will not expecting any parameters so you don't want to pass any parameter to that method.
I think this small document will help you to understand method and arguments.
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html
Its better to add your BMI logic and method to separate class then within the main method create and object and to the rest of manipulation. Otherwise it will hard to maintain and update properties and when you do it in that way remove your static methods. and use proper names for each and every method.
This code will give compilation errors because you have called methods in wrong way and you have call method2 and method5 within static method.
in method2() you have given 4 parameter but you are not using even a single parameter because you are getting from user.
like your modified code is
import java.util.Scanner;
public class cs21`enter code here`0 {
public static double weight;
public static double height;
public static double bmi;
public double wcal;
public double mcal;
public static double age;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
cs210 cs=new cs210();
method1 ();
double val=cs.method2 ();
double value1=cs.method3 (weight,age,height);
double value2=cs.method4 (weight,age,height);
cs.method5 (bmi,value1,value2);
}
public static void method1 () {
System.out.println ("This program implements a Health Assistance Calculator ");
System.out.println ("Given a weight, height, and age, it will compute:\n");
System.out.println ("BMI - Body Mass Index");
System.out.println ("Calories needed per day to maintain weight");
}
public double method2 () {
Scanner keyboard = new Scanner (System.in);
System.out.println ("Please enter your weight:");
weight = keyboard.nextDouble ();
System.out.println ("Press 1 if weight was entered in Kg \n Press 2 if weight was entered in Lbs");
double wunits = keyboard.nextDouble();
if (wunits == 1) {
System.out.println("Thank you");
} else if (wunits == 2){
weight = weight / 2.2;
System.out.println("Thank you");
}
else {
System.out.println ("Please try again");
return 0;
}
System.out.println("Please enter your height:");
height = keyboard.nextDouble ();
System.out.println ("Press 1 if height was entered in meters \n Press 2 if height was entered in inches");
int hunits = keyboard.nextInt();
if(hunits ==1) {
System.out.println("Thank you");
} else if (hunits == 2){
height = height / 0.0254;
}else {
System.out.println("Please try again");
return 0;
}
System.out.println("Please enter your age in years:");
age = keyboard.nextDouble ();
bmi = weight / Math.pow(height, height);
return ( bmi + age + height + weight);
}
public static double method3(double weight, double age, double height) {
double paf = 1.375;
double mcal;
mcal = (13.397 * weight + 4.799 * height + 5.677 * age + 88.362) * paf;
return mcal;
}
public static double method4(double weight, double age, double height){
double wcal;
double paf=1.375;
wcal = (93247 * weight + 3.098 * height - 4.330 * age + 447.593) * paf;
return wcal;
}
public void method5(double bmi, double mcal, double wcal){
System.out.println("Your BMI is:" + bmi);
System.out.println("A BMI in the range of 18.5 to 24.9 is considered normal\n");
System.out.println("To maintain your current weight:");
System.out.println("Men need" + mcal + "per day");
System.out.println("Women need" + wcal + "per day");
}
}
Actually to make your code work the way it is written you should:
make all the fields and methods static
remove parameters from all methods declarations
declare local variable paf in method4.
That being said the code in that form is quite ugly. You should think about the following improvements:
class name should start from capital letter
class name should be something meaningful (e.g. BcmCalculator)
fields should be private
method should have meaningful names ( printGreetings, readUsersAttributes, etc)
in main method you should create instance of the class and call its methods
paf should be a constant (ie field private static final double PAF = 1.375;).
There are further possible improvements, but this should be enough for the beginning.

Java Scanner Input not allowing input

I'm trying to add entries to an ArrayList in Java and I had it working, but now it isn't. Here is the code
import java.util.*;
public class SalesPerson
{
// define an array of allowable sales person to be three
static String[] salesPerson = new String[3];
/**
* Calculates the total annual compensation for a salesperson by
* multiplying annual sales by commission rate and then adding the salary
*/
public static void compensation()
{
try {
String[] salesperson = new String[3];
// use scanner class to read input from the user
Scanner input = new Scanner(System.in);
// List to add entries to an array list
ArrayList<String> list = new ArrayList<>();
// do..while loop to add salespersons
do {
System.out.println("Want to compare additional " //GLD-changed verbiage here
+ "salespeople? (y/n)"); //GLD-changed verbiage here
if (input.next().startsWith("y")) {
System.out.println("Enter the salesperson's name:");
addSalesPerson(list).add(input.next());
System.out.println("Enter annual amount for salesperson");
addSalesPerson(list).add(input.next());
} else {
break;
}
}
while (true);
// System.out.println(addSalesPerson(list).get(1));
// check to see if only two sales persons have been entered
if (addSalesPerson(list).size() < 2 || addSalesPerson(list).size() > 4) {
throw new Exception("You may only enter two sales persons.");
}
Object[] arr;
arr = addSalesPerson(list).toArray(new String[addSalesPerson(list).size()]);
// loop through the length of the array
for (Object arr1 : arr) {
salesperson = (String[]) arr;
}
// for this, we will compare two sales people only
float sale2 = Float.parseFloat(salesperson[1]);
float sale4 = Float.parseFloat(salesperson[3]);
// subtract based on which variable is greater to ensure no negative values
float difference = sale2 > sale4 ? sale2 - sale4 : sale4 - sale2;
// print out the difference
System.out.printf("To match the other sales person's amount "
+ "you will need to get $%.2f more\n\n", difference);
} catch (Exception e) {
// handle any exception by displaying an error message
System.out.println("Something went wrong while processing your "
+ "input. Please be sure you only entered numeric values"
+ " and or the correct amount of salespersons.");
}
}
/**
* Adds sales people to an array list
* #param salesperson
* #return ArrayList
*/
static public ArrayList addSalesPerson(ArrayList<String> salesperson)
{
for (int i=0; i<salesPerson.length; i++) {
if (salesperson.get(i).equals("")) {
break;
}
salesperson.add(salesperson.get(i));
}
return salesperson;
}
}
And then I am calling these static methods in two other files
public class Getters
{
public static void handleSalesPersonCompensation()
{
SalesPerson.compensation();
}
}
public class ComparisonWk5
{
public static void main(String args[])
{
Getters.handleSalesPersonCompensation();
}
}
The output of these should be
Want to compare additional salespeople? (y/n)
y
Enter the saleperson's name: My Name
Enter the annual amount for salesperson: 200000
Want to compare an additional salespeople? (y/n)
y
Enter the saleperson's name: My Name 2
Enter the annual amount for salesperson: 100000
To match the other person's amount, you will need to get $100000 more
But the output is:
Want to compare additional salespeople? (y/n)
y
Enter the salesperson's name:
Something went wrong while processing your input. Please be sure you only entered numeric values and or the correct amount of salespersons.
Everytime after I type "y", it shows the salesperson's name input but also displays the exception right after without having the ability to enter a name.
Any help would be appreciated
The stack trace is this:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at SalesPerson.addSalesPerson(SalesPerson.java:96)
at SalesPerson.compensation(SalesPerson.java:48)
at Getters.handleSalesPersonCompensation(Getters.java:61)
at ComparisonWk5.main(ComparisonWk5.java:31)
Thanks

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()

Java error: constructor in class cannot be applied to given types

I just added the constructor Building and I thought everything would work fine, but I'm getting an error on line 43. When I create the object, Building b = new Building();, it says I need to have a double and int in the argument, so I did as it said, but I just keep getting more errors. What am I doing wrong?
// This program lets the user design the area and stories of a building multiple times
// Author: Noah Davidson
// Date: February 20, 2014
import java.util.*;
public class Building // Class begins
{
static Scanner console = new Scanner(System.in);
double area; // Attributes of a building
int floors;
public Building(double squarefootage, int stories)
{
area = squarefootage;
floors = stories;
}
void get_squarefootage() // User enters the area of floor
{
System.out.println("Please enter the square footage of the floor.");
area = console.nextDouble();
}
void get_stories() // The user enters the amount of floors in the building
{
System.out.println("Please enter the number of floors in the building.");
floors = console.nextInt();
}
void get_info() // This function prints outs the variables of the building
{
System.out.println("The area is: " + area + " feet squared");
System.out.println("The number of stories in the building: " + floors + " levels");
}
public static void main(String[] args) // Main starts
{
char ans; // Allows for char
do{ // 'do/while' loop starts so user can reiterate
// the program as many times as they desire
Building b = new Building(); // Creates the object b
b.get_squarefootage(); // Calls the user to enter the area
b.get_stories(); // Calls the user to enter the floors
System.out.println("---------------");
b.get_info(); // Displays the variables
System.out.println("Would you like to repeat this program? (Y/N)");
ans = console.next().charAt(0); // The user enters either Y or y until
// they wish to exit the program
} while(ans == 'Y' || ans == 'y'); // Test of do/while loop
}
}
Your problem is this line here: Building b = new Building(); // Creates the object b
Your constructor is set up to take two arguments, a double and an int, but you pass neither.
Try something like this to remove the error:
double area = 0.0;
int floors = 0;
Building b = new Building(area, floors);
Perhaps a better idea would be to just have a constructor that took no parameters:
public Building() {
this.area = 0.0;
this.floors = 0;
}
After I apply these changes, the code compiles and runs... (see the picture below)
I have fixed and tested your code. It now runs. You need to add two arguments to the constructor (double and int).
import java.util.*;
public class Building // The class begins
{
static Scanner console = new Scanner(System.in);
double area; // Attributes of a building
int floors;
public Building (double squarefootage, int stories)
{
area = squarefootage;
floors = stories;
}
void get_squarefootage() // The user enters the area of floor
{
System.out.println ("Please enter the square footage of the floor.");
area = console.nextDouble();
}
void get_stories() // The user enters the amount of floors in the building
{
System.out.println ("Please enter the number of floors in the building.");
floors = console.nextInt();
}
void get_info() // This function prints outs the vaibles of the building
{
System.out.println ("The area is: " + area + " feet squared");
System.out.println ("The number of stroies in the building: " + floors + " levels");
}
public static void main(String[] args) // Main starts
{
char ans; // Allows for char
do{ // 'do/while' loop starts so user can reiterate
// the program as many times as they desire
double a = 1;
int c = 2;
Building b = new Building(a, c); // Creates the object b
b.get_squarefootage(); // Calls the user to enter the area
b.get_stories(); // Calls the user to enter the floors
System.out.println("---------------");
b.get_info(); // Displays the variables
System.out.println("Would you like to repeat this program? (Y/N)");
ans = console.next().charAt(0); // The user enters either Y or y until
// they wish to exit the program
} while(ans == 'Y' || ans == 'y'); // Test of do/while loop
}
}
import java.util.Scanner;
public class Building // Class begins
{
static Scanner console = new Scanner(System.in);
double area; // Attributes of a building
int floors;
void get_squarefootage() // User enters the area of floor
{
System.out.println("Please enter the square footage of the floor.");
this.area = console.nextDouble();
}
void get_stories() // The user enters the amount of floors in the building
{
System.out.println("Please enter the number of floors in the building.");
this.floors = console.nextInt();
}
void get_info() // This function prints outs the variables of the building
{
System.out.println("The area is: " + area + " feet squared");
System.out.println("The number of stories in the building: " + floors + " levels");
}
public static void main(String[] args) // Main starts
{
char ans; // Allows for char
do{ // 'do/while' loop starts so user can reiterate
// the program as many times as they desire
Building b = new Building(); // Creates the object b
b.get_squarefootage(); // Calls the user to enter the area
b.get_stories(); // Calls the user to enter the floors
System.out.println("---------------");
b.get_info(); // Displays the variables
System.out.println("Would you like to repeat this program? (Y/N)");
ans = console.next().charAt(0); // The user enters either Y or y until
// they wish to exit the program
} while(ans == 'Y' || ans == 'y'); // Test of do/while loop
}
}

Output user data to display class

package developer;
import java.util.*;
import java.lang.Math.*;
public class Developer
{
static Scanner console = new Scanner(System.in);
String workType; // This will be either an app, or game
String name;
int pay;
int weekPay;
int hrsWorked;
double tax;
public Developer()
{
name = "Ciaran";
}
Developer(String appType, String coderName)
{
workType = appType;
name = coderName;
}// End developer
Developer(String appType, int pay) // Class to choose the pay rate depending on if it is a game or app
{
System.out.println("Are you coding an app or a game? ");
appType = console.next();
if(appType == "app")
{
pay = 20;
}
if(appType == "game")
{
pay = 30;
}
else
{
System.out.println("Please enter either 'app' or 'game' ");
}
}// End developer
Developer(int hrsWorked, double tax, int weekPay, int pay) // Class to choose the tax bracket which the developer is in
{
System.out.println("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
weekPay = hrsWorked * pay;
if(weekPay >= 865)
{
tax = 0.4;
}
else
{
tax = 0.21;
}
}// End developer
Developer(int weekPay, int tax) // Gets the pay after tax
{
weekPay = weekPay * tax;
}// End developer
public void display()
{
System.out.println("This display method works");
System.out.println("User: " + name);
}
public static void main(String[] args)
{
Developer myDev = new Developer();
myDev.display();
} // End main
}// End public class developer
I am trying to get this program to ask the user what their name is; if they are developing a game or app and the amount of hours worked on it. With all this information I want to calculate how much the dev earns including tax. I cannot seem to get the display() method to ask the user the questions though and I have no idea what to do. I am hoping somebody out there can help me.
System.in will read input from the command line. You should wrap it with a java.util.Scanner and nextLine like this:
Scanner scanner = new Scanner(System.in);
String user_input = scanner.nextLine();
Be sure to check
scanner.hasNextLine()
before continuing or you'll get an error.
There are few things that could be done differently in your code, so let's break it down:
1.No need to make console static type, you can use:
private Scanner console = new Scanner(System.in);
2.weekPay is of type int, but your tax is double, if you don't want weekPay to be cast to integer, change it to:
double weekPay;
3.Later on, you are calculating weekPay after tax, so let's introduce a variable for that:
double weekPayAfterTax;
4.All these Developer() methods are constructors, and I think you are slightly confused here. Of course, you can have many constructors, but for us, let's keep only the no-params constructor:
public Developer() {
name = "Ciaran";
//you could initialise all the other variables here as well,
//I'll leave it as an exercise for you :)
}
5.Let's create a method that will ask all the questions and set respective variables:
void setData() {
//let's get the name
System.out.print("What's your name: ");
name = console.nextLine();
System.out.print("Are you coding an app or a game? ");
//since we want the user to enter 'app' or 'game'
//we need to loop until we got these
//we can do this by creating endless while loop,
//which we will end when we have correct input
while (true) {
workType = console.next();
if (workType.equals("app")) {
pay = 20.0;
//stop the loop
break;
}
else if (workType.equals("game")) {
pay = 30.0;
//stop the loop
break;
}
else {
System.out.print("Please enter either 'app' or 'game': ");
//back to top
}
}
//ok, we're out the loop, let's get number of hours
System.out.print("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
//calculate weekPay
weekPay = hrsWorked * pay;
if(weekPay >= 865) {
tax = 0.4;
}
else {
tax = 0.21;
}
//calculate pay after tax
weekPayAfterTax = weekPay - weekPay * tax;
}
6.Let's update our display() method to show all the info:
public void display() {
System.out.println("This display method works");
System.out.println("User: " + name);
System.out.println("Work type: " + workType);
System.out.println("Pay: " + pay);
System.out.println("Week pay: " + weekPay);
System.out.println("Week pay after tax: " + weekPayAfterTax);
}
7.In your main method, you can finally create an instance of Developer class and get the data:
public static void main(String[] args) {
Developer myDev = new Developer();
myDev.setData();
myDev.display();
}
The code above can be improved (such as checking if user entered number where it's expected), and your problem can of course be done differently, but here's the start.
Please check out some tutorials to learn the basics, such as this one, or this one. Most of all, experiment and don't let others put you down for not understanding something.

Categories

Resources