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.
Related
Not actually sure what's wrong, just that at line 81 my scan object is skipped and then the program continues with no clear attempt to read anything, thoughts on what's wrong? btw working in eclipse
import java.util.*;
public class Hospital
{
//--- Instance Variables
private Patient patient;
private Scanner scan;
private double totalPrivateRoomCharges;
private double totalSemiPrivateRoomCharges;
private double totalWardRoomCharges;
private double totalTelephoneCharges;
private double totalTelevisionCharges;
private double totalReceipts;
//--- Constructors
public Hospital()
{
scan = new Scanner(System.in);
totalPrivateRoomCharges = 0;
totalSemiPrivateRoomCharges = 0;
totalWardRoomCharges = 0;
totalTelephoneCharges = 0;
totalTelevisionCharges = 0;
totalReceipts = 0;
mainMenu();
}
//--- Methods
public void mainMenu()
{
int ans = 0;
do
{
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Main Menu");
System.out.println();
System.out.println("1) Enter Patient Billing Information");
System.out.println("2) Print Daily Summary Report");
System.out.println("3) Exit");
System.out.println();
System.out.print("Selection: ");
ans = scan.nextInt();
System.out.println();
if(ans == 1)
{
patientBillingInfo();
}
if(ans == 2)
{
printSummaryReport();
}
}
while(ans != 3);
}
// precondition: none
// postcondition: displays a menu that allows the user to enter a patient's
// billing info which includes the patient's name, the number of days the
// patient stayed in the hospital, and the type of room
// (private, semi-private, ward).
// Once the patient info is retrieved a patient object is created and a
// billing report is generated that includes the patient's name, length
// of stay, and the charges incurred including the bill total.
// The totals that are used to print the hospitals daily summary report
// are updated.
public void patientBillingInfo()
{
String name = "";
int days = 0;
String room = "";
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Patient Billing Query");
System.out.println();
System.out.println("Enter Patient Name: ");
here the scan object seems to be completely skipped and dose not read at all just moves to the next line and continues.
name = scan.nextLine(); //getting skiped
System.out.println("Enter number of days in Hospital: ");
days = scan.nextInt();
System.out.println("Enter Room type(P, S, W): ");
room = scan.next();
System.out.println();
System.out.println();
if(!((room.equalsIgnoreCase("P")) || (room.equalsIgnoreCase("S")) || (room.equalsIgnoreCase("W"))))
{
System.out.println("Incorect room information");
System.out.println("Please enter P, S, or W for room selection");
System.out.println();
patientBillingInfo();
}
else
{
if(room.equalsIgnoreCase("P"))
totalPrivateRoomCharges += 1*days;
if(room.equalsIgnoreCase("S"))
totalSemiPrivateRoomCharges += 1*days;
if(room.equalsIgnoreCase("W"))
totalWardRoomCharges += 1*days;
totalTelephoneCharges += 1*days;
totalTelevisionCharges += 1*days;
patient = new Patient(name, days,room);
}
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Patient Billing Statement");
System.out.println();
System.out.println("Patient's name: " + patient.getName());
System.out.println("Number of days in Hospital: " + patient.getDays());
System.out.println();
System.out.println("Room charge $ " + patient.getRoomCharge());
System.out.println("Telephone charge $ " + patient.getTelephoneCharge());
System.out.println("Television charge $ " + patient.getTelevisionCharge());
System.out.println();
System.out.println("Total charge $ " +patient.getTotalCharge());
System.out.println();
System.out.println();
mainMenu();
}
// precondition: none
// postcondition: a summary report is printed that includes the daily total
// room charges for each type of room, the daily total telephone charges,
// and the daily total television charges. The report also includes the
// total receipts for the day.
public void printSummaryReport()
{
double tPRC = 225.0*totalPrivateRoomCharges;
double tSPRC = 165.0*totalSemiPrivateRoomCharges;
double tWRC = 95.0*totalWardRoomCharges;
double tTpC = 1.75*totalTelephoneCharges;
double tTvC = 3.50*totalTelevisionCharges;
double tR = tPRC+tSPRC+tWRC+tTpC+tTvC;
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Daily Billing Summary");
System.out.println();
System.out.println("Room Charges");
System.out.println(" Private: $" + tPRC);
System.out.println(" Semi-Private: $" + tSPRC);
System.out.println(" Ward: $" + tWRC);
System.out.println("Telephone Charges: $" + tTpC);
System.out.println("Telvision Charges: $" + tTvC);
System.out.println();
System.out.println("Total Receipts: $" + tR);
System.out.println();
}
}
edit: so it just occurred to me that maybe just maybe the rest of the code that this goes with might be useful dunno why I didn't think about this sooner but here's the rest
the class that actually runs
public class Administrator
{
public static void main(String[] args)
{
Hospital hospital = new Hospital();
}
}
and the class that works the patient info
public class Patient
{
//--- Constants
public final double PRIVATE = 225.00;
public final double SEMI = 165.00;
public final double WARD = 95.00;
public final double TELEPHONE = 1.75;
public final double TELEVISION = 3.50;
//--- Instance Variables
private String name;
private String roomType;
private int days;
//--- Constructors
public Patient(String n, int d, String rT)
{
name = n;
days = d;
roomType = rT;
}
//--- Methods
// precondition: none
// postcondition: returns the patient name
public String getName()
{
return name;
}
// precondition: none
// postcondition: returns the length of stay in days
public int getDays()
{
return days;
}
// precondition: none
// postcondition: returns the room type ("P", "S", "W")
public String getRoomType()
{
return roomType;
}
// precondition: none
// postcondition: returns the room charge which is dependant upon
// the room type and the length of stay.
public double getRoomCharge()
{
double charge = 0;
if(getRoomType().equalsIgnoreCase("P"))
charge = 225.00*getDays();
if(getRoomType().equalsIgnoreCase("S"))
charge = 165.00*getDays();
if(getRoomType().equalsIgnoreCase("W"))
charge = 95.00*getDays();
return charge;
}
// precondition: none
// postcondition: returns the telephone charge which is dependant upon
// the length of stay
public double getTelephoneCharge()
{
double charge = 1.75*getDays();
return charge;
}
// precondition: none
// postcondition: returns the television charge which is dependant upon
// the length of stay
public double getTelevisionCharge()
{
double charge = 3.50*getDays();
return charge;
}
// precondition: none
// postcondition: returns the total charge which is the sum
// of the room charge, telephone charge, and television charge.
public double getTotalCharge()
{
double charge = getRoomCharge()*getTelephoneCharge()+getTelevisionCharge();
return charge;
}
}
really don't know why it didn't occur to me sooner to do this but whatever live and lern right
You could simply scan a line and then parse it as the integer for Integer values.
so for reading integers instead of
val=scan.nextInt()
you could use
String strVal = scan.nextLine();
try {
val = Integer.parseInt(strVal);
} catch (NumberFormatException e) {
//maybe try again, or break the code ... or proceed as you wish.
}
this is because the nextInt() does not take the "Enter" key into account, and when you press enter after the nextInt() the int is read into the variable expecting nextInt() and the "Return" Key is accepted by the nextLine() which results in an empty line being read into the variable.
In public void mainMenu() you need to add scan.nextLine(); after ans = scan.nextInt(); in order to clear the rest of the input buffer.
ans = scan.nextInt();
scan.nextLine(); // <----- Add this line here
I have this bit of code to return to the beginning of the program if an answer is not expected.
...
else // returns to start for unsatisfactory
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
}
...
however when I enter a different word then go through again and enter an expected word the program outputs two different results
Current Salary: $100.00
Amount of your raise: $4.00
Your new salary: $104.00
Current Salary: $100.00
Amount of your raise: $0.00
Your new salary: $100.00
I tried using an else if statement to possibly eliminate that as a cause but it caused the same thing.
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary {
public static void main (String[] args) {
double currentSalary; // employee's current salary
double raise = 0.0; // amount of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
// Computes raise with if-else
if ((rating.equals("Excellent")) || (rating.equals("excellent"))) {
// calculates raise for excellent
raise = .06 * currentSalary;
}
else if ((rating.equals("Good")) || (rating.equals("good"))) {
// calculates raise for good
raise = .04 * currentSalary;
}
else if ((rating.equals("Poor")) || (rating.equals("poor"))) {
// calculates raise for poor
raise = .015 * currentSalary;
}
else {
// returns to start for unsatisfactory
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
}
newSalary = currentSalary + raise;
// Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary: " + money.format(newSalary));
System.out.println();
}
}
That is because you call main recursively (which is not considered good practice BTW) when you don't get an expected input. After you enter (the 2nd time) an expected input, the remainder of the initial main must still be executed which will then work with a raise of 0.0 as the input was invalid.
A pragmatic solution for your issue could be avoiding the recursive call to main and wrap e.g. the input validation in a loop like so
...
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
while (true) {
rating = scan.next();
if ((rating.equals("Excellent")) || (rating.equals("excellent")))
{
raise = .06 * currentSalary; break;
}
else if ((rating.equals("Good")) || (rating.equals("good")))
{
raise = .04 * currentSalary; break;
}
else if ((rating.equals("Poor")) || (rating.equals("poor")))
{
raise = .015 * currentSalary; break;
}
else
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
}
}
...
You're not returning after you call main (args); so every iteration of your program will continue.
You should add return; after main (args);
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
return;
}
edit: as pointed out by John3136 you shouldn't be calling main (args) recursively either.
That (second) call you make to main() "finishes" and comes back out to the "first" one that was invoked by starting the program.
So the first lot of results are from your explicit call to main(). The second lot is from when that call ends and you are back to where you called from.
Calling main() recursively is not recommended. You should use a while loop inside main(). i.e. Keep asking for input until you know the input is valid, and then actually use it.
You should not call main recursively.you should use do while loop as I update code and it's working fine.
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary {
public static void main (String[] args) {
double currentSalary; // employee's current salary
double raise = 0.0; // amount of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
boolean flag=false; // to check input
Scanner scan = new Scanner(System.in);
do{
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
// Computes raise with if-else
if ((rating.equals("Excellent")) || (rating.equals("excellent"))) // calculates raise for excellent
{
raise = .06 * currentSalary;
flag=true;
}
else if ((rating.equals("Good")) || (rating.equals("good"))) // calculates raise for good
{
raise = .04 * currentSalary;
flag=true;
}
else if ((rating.equals("Poor")) || (rating.equals("poor"))) // calculates raise for poor
{
raise = .015 * currentSalary;
flag=true;
}
else // returns to start for unsatisfactory
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
flag=false;
}
}while(!flag);
newSalary = currentSalary + raise;
// Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary: " + money.format(newSalary));
System.out.println();
}
}
You may want to consider another approach. Either terminate the problem in case the input is invalid or try to repair it. The following example is for the "repair" approach,
public class Salary {
public static void main(String[] args) {
IPM ipm;
if (verify(args)) {
ipm = new IPM(args);
} else {
Scanner scan = new Scanner(System.in);
String[] update;
do {
update = repair(scan);
} while (!verify(update)); // You may want a loop count as well...
ipm = new IPM(update);
}
ipm.print();
}
public static boolean verify(String[] s) {
return IPM.verify(s);
}
public static String[] repair (Scanner s) {
// Request new input and store it in an array of strings.
// This method does not validate the input.
}
}
public class IPM {
double currentSalary;
double raise = 0.0;
double newSalary;
String rating;
IPM(String[] input) {
// Set attributes of IPM.
}
public static boolean verify(String[] s) {
//Determine if the input is valid.
}
public void print() {
// Print IPM object.
}
}
Note that the call to IPM.verify() from salary. This should be a part of the responsibility of IPM since Salary is not require to know anything about main. Also, the class IPM might change and a call to IPM.verify() will not require that all classes which verifies the IPM are changed as well.
i am new to programming, and i was wondering if i could get some help. My program stops running at System.out.println("To calculate interest, we need three values. the first is the percent of interest. The second is the time the interest has to be applied for. The third is the amount of money the interest is being applied on.");. I am open to any suggestion. Also, please point out anything else wrong with this program. Thanks!
import java.util.Scanner;
public class Interest
{
double userInput;
double interest;
double time;
double amount;
double answer;
Scanner myScanner = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("To calculate interest, we need three values. the first is the percent of interest. The second is the time the interest has to be applied for. The third is the amount of money the interest is being applied on.");
}
{
System.out.println("Please enter your percent of interest in a decimal format: ");
userInput = myScanner.nextDouble();
if(myScanner.hasNextDouble())
{
interest = userInput;
}
else
{
System.out.println("Please enter a integer for your percent of interest.");
}
}
{
System.out.println("Please enter the time the interest is applied for: ");
userInput = myScanner.nextDouble();
if(myScanner.hasNextDouble())
{
time = userInput;
}
else
{
System.out.println("Please enter an integer for the time the interest is applied for.");
}
}
{
System.out.println("Please enter your amount of money that the interest is applied to: ");
userInput = myScanner.nextDouble();
if(myScanner.hasNextDouble())
{
amount = userInput;
}
else
{
System.out.println("Please enter an integer for the amount of money that the interest is applied to.");
}
}
{
answer = (amount * interest * time);
}
{
System.out.println("Your interest is $" + answer + ".");
System.out.println("Your total payment is $" + (answer + amount) + ".");
}
}
Get rid of all the extra braces; they're outside your main method.
public static void main(String[] args)
{
System.out.println("To calculate interest, we need three values. the first is the percent of interest. The second is the time the interest has to be applied for. The third is the amount of money the interest is being applied on.");
// } <-- remove
// { <-- remove
System.out.println("Please enter your percent of interest in a decimal format: ");
// -----SKIP-----
// } <-- remove
// { <-- remove
System.out.println("Your interest is $" + answer + ".");
System.out.println("Your total payment is $" + (answer + amount) + ".");
} // leave this here (end of method)
you are writing instance blocks and in main method,you did not make object creation.instance blocks are executed when you create object of class.if you want to execute those instance block you should write YourClass myclass = new YourClass()in your main method and when you run main function,those blocks outside of main()will be executed OR you should write these blocks in main method just like #shmosel's example.
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.
I need to design and implement an application called CinemaPrice to determine how much a person pays to go the the cinema. The program should generate an age from 1 - 100 using the Random class and prompt the user for the full ticket price. Then display the appropriate ticket price using the currency format (an example in your book ). You may want to refer to the example we did together in class to help you with the "if statement". Decide ticket price on the following basis:
1. under 5, free;
2. aged 5 to 12, half price;
3. aged 13 to 54, full price;
4. aged 55, or over, free.
I would really like some help on this I'm new to java and been spending hours on this now I would love to finish it :)
This is what I have so far:
import java.util.Scanner; //Needed for the Scanner class
import java.util.Random;
import java.text.DecimalFormat;
public class CinemaPrice
{
public static void main(String[] args) //all the action happens here!
{ Scanner input = new Scanner (System.in);
int age = 0;
double priceNumber = 0.00;
Random generator = new Random();
age = generator.nextInt(100) + 1;
if ((age <= 5) || (age >=55) {
priceNumber = 0.0;
}else if (age <= 12){
priceNumber = 12.50;
}else {
system.out.println("Sorry, But the age supplied was invalid.");
}
if (priceNumber <= 0.0) {
System.out.println("The person age " + age + " is free!);
}
else {
System.out.println("Price for the person age " + age + "is: $" + priceNumber);
}
} //end of the main method
} // end of the class
I don't know how to prompt and read input from a user though - can you help?
The first issue that I see is that you need to update your conditional statement here as anything from 13 to 54 will be an invalid age...
if ((age <= 5) || (age >=55) {
priceNumber = 0.0;
}else if (age <= 12){
priceNumber = 12.50;
}else if (age < 55){
//whatever this ticket price is
}else {
system.out.println("Sorry, But the age supplied was invalid.");
}
Something like that would work...
You have stated that your real problem is getting data into your program, the following should demonstrate using the Scanner class
public static void main(String[] args) {
System.out.println("Enter an age");
Scanner scan=new Scanner(System.in);
int age=scan.nextInt();
System.out.println("Your age was " + age);
double price=scan.nextDouble();
System.out.println("Your price was " + price);
}
Now thats the basic idea, but if you provide an incorrect input (like a word) you can get an exception, you can however check that the input you're getting is correct and only accept it if its what you want, like this;
public class Main{
public static void main(String[] args) {
System.out.println("Enter an age");
Scanner scan=new Scanner(System.in);
while (!scan.hasNextInt()) { //ask if the scanner has "something we want"
System.out.println("Invalid age");
System.out.println("Enter an age");
scan.next(); //it doesn't have what we want, demand annother
}
int age = scan.nextInt(); //we finally got what we wanted, use it
System.out.println("Your age was " + age);
}
}