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'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 have had a good look in books and the internet but cannot find a solution to my specific problem.Im really worried as time is running out.
I am writing code for an account. Each transaction, if it is add or withdraw is an object. Information such as the add amount, withdraw amount, transaction number,balance and total spending in a particular category is an object. Each object is stored in an arrayList. There is also code for logging in because this will eventually be an app. It requires the user to input their student number(last 4 digits).
The code runs ok and it serializes on termination. Upon running the code i can see it has de serialized the file as there is a list of objects in the arrayList printed.
My problem is that the values such as student number and balance are 0 when the code runs.Also the transaction number does not increment. It does increment while the code runs but stops upon termination, starting at 1 when the code is run again.
I expected all values to be the same when de serailized as those in the last object in the arrayList before serialization.
I dont expect anyone to post the answer but if someone could point me in the right direction i could try to work it out myself.
Best regards
Richard
PS. transaction number is the first in the object, balance in the middle and student number the four digits at the end. I have added the main class and serialization class, if anyone wants to see the login, transaction or other classes i can post these too.
`
/**
* Created by Richard on 16/07/2014.
*/
public class AccountTest implements Serializable {
public static Scanner keyboard = new Scanner(System.in);
//Declare an ArrayList called 'transactions' which will hold instances of AccountInfo.
public static ArrayList transactions = new ArrayList<AccountInfo>();
//Declare and initiate variables relating to the AccountTest class.
private static int transactionNum = 0;
private static double depositAmount = 0;
public static double withdrawAmount = 0;
private static double currentBalance = 0;
// A method which prompts the user to either withdraw, add funds or quit,
//this method also updates the balance and transaction number.
public static void addOrSpend() {
do {//A do while loop to ensure that the method repeatedly asks the user for input.
System.out.println("Enter a 1 to deposit, 2 to withdraw, 3 to terminate:");
int choice = keyboard.nextInt();
if (choice == 1) {//The deposit choice that also sets transaction no. and the balance.
System.out.println("Enter an amount to deposit ");
depositAmount = keyboard.nextInt();
transactionNum = transactionNum + 1;
withdrawAmount = 0;
currentBalance = currentBalance + depositAmount;
//System.out.println("You entered: " + depositAmount);
}//if
if (choice == 2) {//The withdraw choice that also sets transaction num, balance and calls chooseCategory method.
System.out.println("Enter an amount to withdraw ");
withdrawAmount = keyboard.nextInt();
transactionNum = transactionNum + 1;
depositAmount = 0;
currentBalance = currentBalance - withdrawAmount;
AccountCategory.chooseCategory();
}//if
if (choice == 3) {//User option to quit the program.
AccountSerialize.serialize();
System.out.println("App terminated...");
System.exit(1);
}//if
AccountInfo acc = new AccountInfo();//creates an object of the AccountInfo class
//Setters for the various methods in the AccountInfo class,
// these initiate variables for instances of the class.
acc.setTransactionNum(transactionNum);
acc.setDepositAmount(depositAmount);
acc.setWithdrawAmount(withdrawAmount);
acc.setCurrentBalance(currentBalance);
acc.setAccommodation(AccountCategory.accommodation);
acc.setTransport(AccountCategory.transport);
acc.setUtilities(AccountCategory.utilities);
acc.setEntertainment(AccountCategory.entertainment);
acc.setEssentials(AccountCategory.essentials);
acc.setStudentNo(AccountLogin.studentNo);
transactions.add(acc);//Adds each new 'acc' object to the ArrayList 'transaction'.
//System.out.println("List:" + transactions);Unused print statement which shows contents of ArrayList for testing.
Formatter x = new Formatter();//Series of formatted print statements which allow the information to be displayed in tabular format with headings.
System.out.println(String.format("%-20s %-20s %-20s %-20s ", "Transaction No.", "Deposit amount", "Withdraw amount", "Current balance"));
System.out.println(String.format("%-20s %-20s %-20s %-20s", transactionNum, depositAmount, withdrawAmount, currentBalance));
System.out.println(String.format("%-20s %-20s %-20s %-20s %-20s ", "Accommodation", "Transport", "Utilities", "Entertainment", "Essentials"));
System.out.println(String.format("%-20s %-20s %-20s %-20s %-20s", AccountCategory.accommodation, AccountCategory.transport, AccountCategory.utilities,
AccountCategory.entertainment, AccountCategory.essentials));
} while (transactions.size() >= 0);//End of do while statement that repeatedly prompts the user.
}
//Main method from where the program starts and user logs in. Starts with request for user to login.
// This then allows the user to continue with the program.
public static void main(String args[]) {
AccountSerialize.deSerialize();
System.out.println("Testing to see if student num is saved, login is..." +AccountLogin.studentNo );
System.out.println("Testing to see if balance is saved, balance is..." +currentBalance );
if (AccountLogin.studentNo == 0)
{
AccountLogin.numberSave();
}
else
{
AccountLogin.login();
}
}//main
}//class AccountTest
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Richard on 24/07/2014.
*/
public class AccountSerialize {
public static String filename = "budgetApp.bin";
public static String tmp;
public static void serialize() {
try {
FileOutputStream fos = new FileOutputStream("budgetApp.bin");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(AccountTest.transactions);
oos.close();
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Done writing");
}//serialize()
public static void deSerialize(){
try
{
FileInputStream fis = new FileInputStream("budgetApp.bin");
ObjectInputStream ois = new ObjectInputStream(fis);
AccountTest.transactions = (ArrayList) ois.readObject();
ois.close();
fis.close();
}catch(IOException ioe){
ioe.printStackTrace();
return;
}catch(ClassNotFoundException c){
System.out.println("Class not found");
c.printStackTrace();
return;
}
for( Object tmp:AccountTest.transactions){
System.out.println(tmp);
}
}//deSerialize()
}//class
import java.util.Scanner;
/**
* Created by Richard on 22/07/2014.
*/
public class AccountCategory {
static Scanner keyboard = new Scanner(System.in);
//Declare and initiate variable to be used in this class.
public static double accommodation = 0;
public static double transport = 0;
public static double utilities = 0;
public static double entertainment = 0;
public static double essentials = 0;
//A method which prints a set of spending category choices and asks the user to choose.
//Also updates each category variable with the total amount spent in that category
public static void chooseCategory() {
System.out.println("Please choose a category of spending, enter corresponding number");
System.out.println("1:\tAccommodation \n2:\tTransport \n3:\tUtilities \n4:\tEntertainment " +
"\n5:\tEssentials ");
double choice = keyboard.nextInt();//User input.
if (choice == 1) {
accommodation = accommodation + AccountTest.withdrawAmount;
}//if
if (choice == 2) {
transport = transport + AccountTest.withdrawAmount;
}//if
if (choice == 3) {
utilities = utilities + AccountTest.withdrawAmount;
}//if
if (choice == 4) {
entertainment = entertainment + AccountTest.withdrawAmount;
}//if
if (choice == 5) {
essentials = essentials + AccountTest.withdrawAmount;
}//if
}//chooseCategory
}//Class AccountCategory
import java.io.Serializable;
import java.util.Scanner;
/**
* Created by Richard on 16/07/2014.
*/
public class AccountInfo implements Serializable {
//Declare variables for types of transaction, balance and categories of spending.
public int studentNo;
public int transactionNum;
public double depositAmount;
public double withdrawAmount;
public double currentBalance;
public double accommodation;
public double transport;
public double utilities;
public double entertainment;
public double essentials;
//Series of mutator methods which take and validate the user input from the Test class, setting new variable values
//for objects of this AccountInfo class.
public void setStudentNo(int studentNo) {
this.studentNo = studentNo;
}
public void setTransactionNum(int transactionNum) {
this.transactionNum = transactionNum;
}
public void setDepositAmount(double depositAmount) {
this.depositAmount = depositAmount;
}
public void setWithdrawAmount(double withdrawAmount) {
this.withdrawAmount = withdrawAmount;
}
public void setCurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
}
public void setAccommodation(double accommodation) {
this.accommodation = accommodation;
}
public void setTransport(double transport) {
this.transport = transport;
}
public void setUtilities(double utilities) {
this.utilities = utilities;
}
public void setEntertainment(double entertainment) {
this.entertainment = entertainment;
}
public void setEssentials(double essentials) {
this.essentials = essentials;
}
//A toString method to ensure printed information is user readable
public String toString() {
return "AccountInfo[" + transactionNum + "," + depositAmount + "," + withdrawAmount + "," + currentBalance + "," +
accommodation + "," + transport + "," + utilities + "," + entertainment + "," + essentials + ","+studentNo+"]";
}//toString
}//class AccountInfo
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Created by Richard on 20/07/2014.
*/
public class AccountLogin {
public static Scanner keyboard = new Scanner(System.in);
//Declare and initiate variables.
public static int studentNo=0;
public static int login=0;
public static void login() {
if (studentNo > 0 && Integer.toString(studentNo).length() == 4)//Validation test.
{
System.out.println("Log in with last four digits of your student number:");
login = keyboard.nextInt();//User input.
}//if
if(login==studentNo){
AccountTest.addOrSpend();//If validated
}//if
else{
enterNoAgain();
}//else
}//login()
//This method checks to see if the user has already entered and saved their details, if not the user is prompted to do so.
//If the user has already entered their details
public static void numberSave() {
if (studentNo == 0) {//Checks to see if student number has already been entered.
System.out.println("Enter and save the last four digits of your student number, use this to login to the Budgeting app:");
studentNo = keyboard.nextInt();//User input.
if (studentNo > 0 && Integer.toString(studentNo).length() == 4) {//Checks that user input meets requirements.
System.out.println("You are now logged in:");
AccountTest.addOrSpend();//Program starts at this point once user input is validated.
}//if
else {//If user input does not meet criteria, the following method is called.
enterNoAgain();
}//else
}//if
}//numberSave()
// This method takes over if the user has not input valid data.
// The user is instructed to do so and is given a further 2 opportunities before the program exits
public static void enterNoAgain() {
System.out.println("Invalid input: Use 4 numbers only, try again");//Prompt.
studentNo = keyboard.nextInt();//User input.
if (studentNo > 0 && Integer.toString(studentNo).length() == 4) {//Validation test.
AccountTest.addOrSpend();//If validated
}//if
else {
System.out.println("Last attempt, input last four digits of your student number");//Prompt.
studentNo = keyboard.nextInt();//User input.
if (studentNo > 0 && Integer.toString(studentNo).length() == 4) {//Validation test.
AccountTest.addOrSpend();//If validated
}//if
else {
AccountSerialize.serialize();//Save to file
System.out.println("You failed to login");
System.out.println("App terminated...");
System.exit(1);//Program exits due to invalid user input.
}//else
}//else
}//enterNoAgain()
}//class AccountLogin
`
AccountTest
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,50.0,0.0,50.0,0.0,0.0,0.0,0.0,0.0,3333]
AccountInfo[1,50.0,0.0,50.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,6666]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[2,0.0,50.0,950.0,50.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,500.0,0.0,500.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[2,0.0,50.0,950.0,0.0,0.0,50.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[2,0.0,50.0,950.0,50.0,0.0,0.0,0.0,0.0,1234]
Testing to see if student num is saved, login is...0
Testing to see if balance is saved, balance is...0.0
Enter and save the last four digits of your student number, use this to login to the Budgeting app:
1234
You are now logged in:
Enter a 1 to deposit, 2 to withdraw, 3 to terminate:
1
Enter an amount to deposit
1000
Transaction No. Deposit amount Withdraw amount Current balance
1 1000.0 0.0 1000.0
Accommodation Transport Utilities Entertainment Essentials
0.0 0.0 0.0 0.0 0.0
Enter a 1 to deposit, 2 to withdraw, 3 to terminate:
2
Enter an amount to withdraw
50
Please choose a category of spending, enter corresponding number
1: Accommodation
2: Transport
3: Utilities
4: Entertainment
5: Essentials
1
Transaction No. Deposit amount Withdraw amount Current balance
2 0.0 50.0 950.0
Accommodation Transport Utilities Entertainment Essentials
50.0 0.0 0.0 0.0 0.0
Enter a 1 to deposit, 2 to withdraw, 3 to terminate:
3
Done writing
App terminated...
Process finished with exit code 1
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
}
}
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.