Reached end of file while parsing ERROR? [duplicate] - java

This question already has answers here:
Reached end of file while parsing compilation error
(3 answers)
Closed 3 years ago.
I am getting an error BankInterest(line 93): reached end of file while parsing, anyone know why i am getting this? Here is my code below so you can determine what the problem may be.
Thank you in advance.
import java.nio.file.*;
import java.util.*;
import java.io;
public class BankInterest {
public static void main(String[] args) throws IOException {
/* TASK 1: Declare variables */
String accountType;
double principal;
double rate;
double balance;
int year;
/* Check if the expected command line is provided */
if (args.length < 1) {
/* Display the Usage */
System.out.println("Usage: java BankInterest interestRateFileName");
/* Programs quits with an error code */
System.exit(-1);
}
/* TASK 2: Read interest rates from a file */
try {
Scanner x = new Scanner(Paths.get("commbank.txt"));
System.out.println(x.nextDouble());
} catch (IOException e) {
/* TASK 3: Take user input - Which Account */
Scanner keyboard = new Scanner(System.in);
System.out.println("Which Account: ");
System.out.println("1 - Savings");
System.out.println("2 - Term Deposits");
String line = keyboard.nextLine();
if (line.equals("1")) {
accountType = "Savings";
} else if (line.equals("2")) {
accountType = "Term Deposits";
}
/* TASK 4: Take user input - Principal and Period */
Scanner input = new Scanner(System.in);
System.out.println("Principal: ");
principal = keyboard.nextDouble();
System.out.println("Years: ");
year = keyboard.nextInt();
/* TASK 5: Calculate balance for the chosen account type */
if (accountType == "Savings") {
balance = principal * Math.pow((1 + rate / 100), year);
} else if (accountType == "Term Deposits") {
balance = (principal * rate * time) / 100;
}
/* TASK 6: Display results */
if (accountType == "Savings") {
System.out.println("");
System.out.println("The Compound Interest is: " + balance);enter code here
} else if (accountType == "Term Deposits") {
System.out.println("");
System.out.println("The Simple Interest is: " + balance);
} else {
System.out.println("");
System.out.println("Error! Account is not recognized.");
}
}

You're missing two more closing braces at the end of the file.
One to close your main
And the other to close off your class.
Also, you should use equals() when comparing accountType as Satya mentioned in the comment.

Related

how to make an error message when input is a string instead of an int

beginner here. As mentioned before my question is: how do you output an error when the input is a string instead of an int? I'm trying to created a program that outputs a workers raise in salary, and I wanted to implement a function that displays an error when the user entered something other than a number for their salary. here's my code:
package calculating.salary;
import java.util.Scanner;
public class CalculatingSalary {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please input yearly salary:");
int salary = in.nextInt();
//this is where I would implement the error message
System.out.println("Please input how many years worked:");
boolean running = true;
while (running){
String years = in.nextLine();
if (years.equals ("1")|| years.equals("one")){
System.out.println("Your salary is now $"+(salary + salary*0.02));
break;
}
if (years.equals("2")||years.equals("two")){
System.out.println("Your salary is now $"+(salary + salary*0.03));
break;
}
if (years.equals("3")||years.equals("three")){
System.out.println("Your salary is now $"+(salary + salary*0.04));
break;
}
if (years.equals("4")||years.equals("four")){
System.out.println("Your salary is now $"+(salary + salary*0.05));
break;
}
if (years.equals("5")||years.equals("five")){
System.out.println("Your salary is now $"+(salary + salary*0.06));
break;
}
else {
System.out.println("Please type in a number from 1 through 5");
}
}
}
}
String salary = in.nextLine();
int salaryValue;
try {
salaryValue = Integer.parseInt(salary);
} catch (NumberFormatException e) {
System.out.println("You didn't enter a valid integer.");
}
This will store the user's input in a String instead of an int, then manage the conversion separately. If the conversion fails, an exception is thrown, which causes the message to be printed.

Java -if else displays multiple outputs

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.

Need a way to ensure user enters the correct amount, as well as ensuring the user doesn't enter a string [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 7 years ago.
The code here worked until I needed to ensure the user didn't cause an exception by entering a string instead of an integer or double. I basically need to make sure the user enters enough to be greater than or equal to the price, so that the program can return the correct amount of change.
public static double findChange()
{
System.out.println("\nPlease insert: " + price + " (enter payment amount)");
while (payment < price)
{
try {
payment = kb.nextDouble();
//takes input until user has entered the needed amount
} catch (Exception e)
{
System.out.println("Error: Please enter valid currency");
}
price = price - payment;
price = (price * 100) / 100;
System.out.println("Please insert:" + price);
if (payment <= price)
stringError = false;
}
}
change = payment - price;
change = Math.round(change * 100);
change = change / 100;
System.out.println("\nChange Given: $" + change);
//determines amount of change to give user and formats to cents
return change;
}
Change
catch (Exception e)
{
System.out.println("Error: Please enter valid currency");
}
to
catch (Exception e)
{
System.out.println("Error: Please enter valid currency");
continue;
}
This way, if the user inputs a non double value, the error message will be shown and he will be asked to re-enter a value (The continue; instruction skips the current iteration & passes on to the next one).
try {
payment = kb.nextDouble();
//takes input until user has entered the needed amount
} catch (Exception e)
{
System.out.println("Error: Please enter valid currency");
}
price = price - payment;
When an exception occurs, this will cause troubles, since payment has no value (or not the right one).
put your catch statement later in the while block
Try the following:
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
findChanges();
}
private static double findChanges()
{
string xPrice;
string xPayment;
double price = 0d;
double payment = 0d;
double change = 0d;
Console.WriteLine("Please insert price and payment amout");
Console.WriteLine("Price ?");
xPrice = Console.ReadLine();
bool PriceIsNumber = double.TryParse(xPrice, out price);
Console.WriteLine("Payment ?");
xPayment = Console.ReadLine();
bool PaymentIsNumber = double.TryParse(xPayment, out payment);
if (PriceIsNumber == true && PaymentIsNumber == true)
{
if (payment > price)
{
try
{
// price = price - payment;
// price = (price * 100) / 100;
change = payment - price;
// change = Math.Round(change * 100);
// change = change / 100;
Console.WriteLine("Change = " + change.ToString());
}
catch (Exception e)
{
// supress or process e
}
}
}
else
{
Console.WriteLine("Please enter valid currency");
}
Console.Read();
return change;
}
}
}

Serialization difficulty

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

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