Orphaned Case in Java - java

Orphaned Case Error
The following are the tasks which will be done in the program:-
Accept Deposit from a customer and update the balance.
Display the balance.
Compute and deposit the compound interest.
Permit withdrawal and update the balance.
Check for the minimum balance, impose penalty, if necessary and update the balance
I am getting an "orphaned case" error for
case1: S1.Display();
case1: S2.Display();
Please help. This is the Code:
import java.util.*;
class Account
{
String custname;
double accno;
double bal;
Account(String c, double a, double b)
{custname = c;
accno = a;
bal = b;
}
void Display()
{System.out.println("Account Holder: "+custname);
System.out.println("Account Number "+accno);
System.out.println("Balance : "+bal);
}
void Deposit()
{double dep;
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter the amount your want to deposit:");
dep = sc.nextDouble();
bal = bal + dep;
System.out.println("Updated Details....");
Display();
}
void Withdraw()
{double wth;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the amount you want to withdraw");
wth = sc.NextDouble();
bal = bal - wth;
System.out.println("Updated details....");
Display();
}
}
class SavAccount extends Account
{ String acctype;
SavAccount(String c, double a, double b)
{Super(c, a, b);
acctype = "Savings";
}
void ComInt()
{int months;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the duration of the account in months");
months = sc.NextInt();
double rate, inte;
rate = 0.04;
inte = months *rate * bal;
bal = bal + inte;
System.out.println("Compund Interest : "+inte);
}
void Display()
{System.out.println("Account Holder: "+custname);
System.out.println("Account Number "+accno);
ComInt();
System.out.println("Balance : "+bal);
System.out.println("Account Type: "+acctype);
}
}
class CurAccount extends Account
{String acctype;
CurAccount(String c, double a, double b)
{Super(c, a, b);
acctype = "Current";
}
void Penalty()
{
if(bal<5000.00)
{bal = bal - 100.00;
System.out.println("Fine deducted Rs.100/-");
}
}
void Display()
{System.out.println("Account Holder: "+custname);
System.out.println("Account Number "+accno);
Penalty();
System.out.println("Balance : "+bal);
System.out.println("Account Type: "+acctype);
if(bal<=5000.00)
{System.out.println("Warning!! Please maintain balance above Rs.5000/-");
}
}
}
class Accmain
{public static void main(Strings args[])
{SavAccount S1 = new SavAccount("Aniruddha", 134.00, 15000.00)
;
CurAccount S2 = new CurAccount("Tyrel" , 135.00, 6000.00);
int num = 2;
String c = "y";
int n;
double temp;
double accs[] = new double[10];
accs[0] = S1.accno;
accs[1] = S2.accno;
Scanner sc = new Scanner(System.in);
while (c == "y");
{System.out.println("Please enter your Account number:");
temp = sc.nextDouble();
if(accs[0] == temp)
{System.out.println("Welcome "+ S1.custname);
System.out.println("Account Type: "+ S1.acctype);
System.out.println("1.Display");
System.out.println("2.Withdraw");
System.out.println("3.Deposit");
n = sc.nextInt();
Switch(n)
;
{
case 1 : S1.Display();
case 2 : S1.Withdraw();
case 3 : S1.Deposit();
default :System.out.println("Bad Choice ");
c = "n";
}
}
else if(accs[1] == temp)
{System.out.println("Welcome "+ S2.custname);
System.out.println("Account Type: "+ S2.acctype);
System.out.println("1.Display");
System.out.println("2.Withdraw");
System.out.println("3.Deposit");
n = sc.nextInt()
;
Switch(n);
{
case 1 : S2.Display();
case 2 : S2.Withdraw();
case 3 : S2.Deposit();
default :System.out.println("Bad Choice ");
c = "n";
}
}
}
}
}

Several problems.
1) That extra ; in the end made the switch completed right away on that stamtement.
Switch(n); <--
Apparently all the cases became orphans.
If you remove the colon after Switch(n) you would be fine.
Switch(n)
{
case 1 : S1.Display();
case 2 : S1.Withdraw();
2) After that you have another problem. You need to have break after each case. Otherwise your switch executes all the cases even though the match found. To stop that add break after each case
Switch(n)
{
case 1 : S1.Display(); break;
case 2 : S1.Withdraw();break;
...
3) When you write c == "y" That compare references not equality.
you need to use equals() method to check string equality
read How do I compare strings in Java?
4) That line Super(c, a, b); won't compile as S must be lower-case. Java is case sensitive.

The two problems you're hitting are:
Switch(n) // <-- switch is not spelled with a capital 's'
; // <-- remove the semicolon
{
case 1 : S1.Display();
case 2 : S1.Withdraw();
case 3 : S1.Deposit();
default :System.out.println("Bad Choice ");
c = "n";
}
Since the cases appear without any relation to a switch - you're getting the "Orphaned Case Error". Further, when you're done handling each case you should break; otherwise the code will continue executing the following cases as well!
I would also advise you to use a good IDE and auto-indent the code because the way it is currently indented makes it very difficult to see where an if or else clauses ends.
A good IDE (IntelliJ/Eclipse/Netbeans) will also show you all the compilation errors you have, for example Super(c, a, b) - the 's' should not be capitalized, and etc.

This error usually meas that you are trying to use a case keyword outside of a switch statement.
Switch(n)
;
here after switch(n) remvoe the ;
also use break statement after each case operations. else it will keep executing the next case operations.
other minor issues are mentioned in Sures's answer

case 1:System.out.println("1111111111111111");
some example case 1:System no spaces in statement
example case 1:System.out.println("Display the vales");

Related

My method calcDiscount will not print out

Write a method calcDiscount that accepts two parameters: a double price and a char representing a discount code and returns a double representing the amount of the discount
Compute the amount of the discount given the following table of discount codes:
A 5%
D 10%
N 15%
E 20%
If the discount code is not A, D, N, or E, the discount returned should be 0. Note that you are NOT returning the discounted price, but the actual amount of the discount, so calling calcDiscount with 5.00 and D as arguments should result in an answer of 5.00
I tried the code, and I think its what I need per the instructions, but I cant get the method to print out.
package edu.ilstu;
import java.util.Scanner;
public class ClassOne {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a price");
double price = scan.nextDouble();
System.out.println("Enter a discount code");
char c = scan.next().charAt(0);
}
public static double calcDiscount(double price, char c) {
switch (c) {
case 'A':
double a = (price * .05);
return a;
case 'D':
double d = (price * .10);
return d;
case 'N':
double n = (price * .15);
return n;
case 'E':
double e = (price * .20);
return e;
default:
double z = 0;
return z;
}
System.out.println(ClassOne.calcDiscount());
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a price");
double price = scan.nextDouble();
System.out.println("Enter a discount code");
char c = scan.next().charAt(0);
double discount = calcDiscount(price, c);
System.out.println("Discount: " + discount);
}
You should call the calcDiscount method from your main method. The print statement at the end of the calcDiscount method is incorrect.

How to perform arithmetic operation between the objects written in a file?

In my program, users enter values and those get stored in arrayList. ArryList objects are written into a file. I have used file-i/o, object-i/o stream for writing and readin in file.Now I want to perform addition and subtraction among the objects (int or double). That is withdrawing money from one account should be added with another account, and their value must be subtracted and added with the particular acount's amount. And finally I want that value must be updated so that it can print out and show the current status. How could I do that?
This is the main class:
public class BankApp_Assignment {
//static int numOfAcc = 0;
public static void main(String[] args) {
System.out.println("WELCOME TO OUR BANK!\n\n");
List<BankAccount> bankAccounts = new ArrayList<BankAccount>();
List<BankAccount> bankAccounts2 = new ArrayList<BankAccount>();
ReaderWriter rw=new ReaderWriter();
while (true) {
System.out.println("Choose your option:\n"
+ "1. Create new account\n"
+ "2. Deposit/withdraw\n"
+ "3. View One account\n"
+ "4. Deleting an account\n"
+ "5. View all the accounts\n"
+ "6. Return to menu\n");
System.out.println("*************\n"
+ "************");
option1 = sc.nextInt();
sc.nextLine();
//switch-case starts
switch (option1) {
case 1:
//create account
BankAccount bankAcc = new BankAccount();
System.out.println("Enter Full Name:");
bankAcc.setName(sc.nextLine());
System.out.println("Choose an Account Number:");
bankAcc.setAccNum(sc.nextInt());
System.out.println("Choose the initial amount:");
bankAcc.setInitiateAmount(sc.nextDouble());
//adding those into the arrayList
bankAccounts.add(bankAcc);
rw.writeToFile(bankAccounts);
System.out.println("-------------\n"
+ "-------------");
break;
case 2:
bankAccounts2=(List<BankAccount>)rw.readFromFile();
//First displaying the current accouns info
System.out.println("Name \tAccount No \tInitial Amount");
for (BankAccount bankAccount : bankAccounts2) {
System.out.println(bankAccount);
}
System.out.println("\t\t.........\n"
+ "\t\t.........");
System.out.println("To transfer money within the bank accounts enter 1\n"
+ "To deposit/withdraw money in the same account enter 2");
option2 = sc.nextInt();
sc.nextLine();
//inner switch-case starts
switch (option2) {
case 1:
/*
BankAccount is the class for setter and getter
bankAccounts2 is the arrayList for reading objects from file
*/
bankAccounts2 = (List<BankAccount>) rw.readFromFile();
BankAccount fromAcc = null;
BankAccount toAcc = null;
System.out.println("Enter the account number you want to withdraw from:");
withdraw_accNum = sc.nextInt();
System.out.println("Enter the amount you want to withdraw:");
withdraw_amount = sc.nextDouble();
System.out.println("Enter the account number you want to deposit to:");
deposit_accNum = sc.nextInt();//the deposit amount is alwyas the same as withdraw_amount
//find the matching acc number:withdraw_accNum
for (BankAccount listItemsFirst : bankAccounts2) {
//if the withdraw acc num matches with the given one
if (listItemsFirst.getAccNum() == withdraw_accNum) {
//store it
fromAcc = listItemsFirst;
break;
}
}
//find the matching acc number: deposit_accNum
for (BankAccount listItemsSec : bankAccounts2) {
//if the withdraw acc num matches with the given one
if (listItemsSec.getAccNum() == deposit_accNum) {
//store it
toAcc = listItemsSec;
break;
}
}
//if the withdraw amount is bigger than the current balance
if (withdraw_amount > fromAcc.getInitialAmount()) {
System.out.println("Withdrawing Amount was bigger than the Initial amount.\nChoose the menu again. .");
break;
}
//subtracting and adding the withdrawn amount
fromAcc.setInitiateAmount(fromAcc.getInitialAmount() - withdraw_amount);
toAcc.setInitiateAmount(toAcc.getInitialAmount() + withdraw_amount);
System.out.println("DONE!\t print them out to see the current status.");
System.out.println("");
break;
case 2://deposit/withdraw money in the same accounts
bankAccounts2=(List<BankAccount>)rw.readFromFile();
BankAccount fromAcc_SameAcc = null;
BankAccount toAcc_SameAcc = null;
System.out.println("Enter the account number you want to deposit or withdraw from:");
//read the accNum
depOrWithAccountNum = sc.nextInt();
System.out.println("Enter the amount (To withdraw enter a negative value)");
//read the amount
depOrWithAmount = sc.nextDouble();
//checking the matching account number in arrayList
for (BankAccount listItemsThird : bankAccounts2) {
if (listItemsThird.getAccNum() == depOrWithAccountNum) {
fromAcc_SameAcc = listItemsThird;
break;
}
}
if (depOrWithAmount - 1 < fromAcc_SameAcc.getInitialAmount()) {
System.out.println("Withdraw amount is bigger than the current amount.\nChoose the menu again. .");
break;
}
if (depOrWithAmount < 0) {//the amount is negative
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
} else {
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
}
break;
}
//inner switch-case ends
System.out.println("\n\n");
break;
case 3:
//View One account
bankAccounts2=(List<BankAccount>)rw.readFromFile();
BankAccount viewOneAccountNum = null;
System.out.println("Enter the account number you want to see:");
viewOneAcc = sc.nextInt();
System.out.println("Name\tAccount No\tInitial Amount");
for (BankAccount viewOneAccountProperty : bankAccounts2) {
if (viewOneAccountProperty.getAccNum() == viewOneAcc) {
//viewOneAccountNum=viewOneAccountProperty;
viewOneAccountNum = viewOneAccountProperty;
System.out.println(viewOneAccountNum);
}
System.out.println("");
}
break;
case 4:
bankAccounts2=(List<BankAccount>)rw.readFromFile();
//BankAccount AccToDel = null;
//Deleting an account
Iterator<BankAccount> it = bankAccounts2.iterator();
System.out.println("Enter the account you want to delete:");
deleteAcc = sc.nextInt();
while (it.hasNext()) {
BankAccount next = it.next();
if (next.getAccNum() == deleteAcc) {
it.remove();
}
}
rw.writeToFile(bankAccounts2);
break;
case 5:
//View all the accounts/printing them out
bankAccounts2=(List<BankAccount>)rw.readFromFile();
System.out.println("Name\tAccount No\tInitial Amount");
for (BankAccount bankAccount : bankAccounts2) {
System.out.println(bankAccount);
}
System.out.println("\n\n");
break;
case 6:
//Quit
return;
}
//switch-case ends
}
}
}
ReaderWriter:
public class ReaderWriter{
public void writeToFile(List<BankAccount> accounts){
try {
FileOutputStream fos=new FileOutputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile_assignment.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(accounts);//take the arrayList
oos.flush();
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<BankAccount> readFromFile(){
List<BankAccount>readData=null;
try {
FileInputStream fis=new FileInputStream("C:\\Users\Documents\\NetBeansProjects\\BankFile_assignment.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
//make an arrayList to get those object back
//arrayList
readData=(List<BankAccount>)ois.readObject();
ois.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
//return readData;
return readData;
}
}
BankAccount:
package bankapp_assignment;
import java.io.Serializable;
public class BankAccount implements Serializable{
private String name;
private int accNum;
private double initiateAmount;
//constructor
public BankAccount() {
this.name = null;
this.accNum = 0;
this.initiateAmount = 0;
}
public void setName(String name) {
this.name = name;
}
public void setAccNum(int accNum) {
this.accNum = accNum;
}
public String getName(String name){
return name;
}
public int getAccNum() {
return accNum;
}
public void setInitiateAmount(double initiateAmount) {
this.initiateAmount = initiateAmount;
}
public double getInitialAmount(){
return initiateAmount;
}
#Override
public String toString() {
return name + "\t\t" + accNum + "\t\t" + initiateAmount;
}
}
you should refactor whole main method. If I were you, I would use
main only to lunch program, rest process in other methods. This way you would be able to use class fields all over program, and divide code into many methods.
You should divide main beetween other methods, to at least method
per action, exemple:
case 1:
createAccount();
break;
(...)
public void createAccount(){
code from your swich case 1
}
etc. You can still use swich control, but should replece logic code to another method.
When i run your code, input/output didn't work. Were you able to
save/load file? I had to chage:
File file = new File("//file path");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput oos = new ObjectOutputStream(fos);
Same with input. Then it worked.
Now, we will try to deal with operation on BankAccounts from files. I change a little bit your code from case2/case2: deposit/withdraw, lets look at it:
bankAccounts2 = rw.readFromFile(); // loading list from file
BankAccount edited = new BankAccount(); // creating new object
System.out.println("Enter the account number you want to deposit or withdraw from:");
double input = sc.nextInt(); // you don't need to create new variable every time you take input form user
for(BankAccount account : bankAccounts2){ // every account in list
if(account.getAccNum() == input) edited = account; // if acccNum match, give edited reference to chosen account
}
System.out.println("Enter the amount (To withdraw enter a negative value)");
input = sc.nextDouble();
double result = edited.getInitialAmount() + input; // result of operation
if(result < 0){ // check if there is enough money on account
System.out.println("Withdraw amount is bigger than the current amount.\nChoose the menu again. .");
break;
}else{
edited.setInitiateAmount(result); // if there is, set new value
}
rw.writeToFile(bankAccounts2); // save file
You can implement another operation in similar style. But still, you should consider dividing main into other methods, adding class fields, etc.
EDIT:
For question in comments.
Because you use positive numbers for deposit, and negative numbers for withdraw, the operation on initialAmount will be always the same: initialAmount + input (if negative, is will subtract from amount), so you can treat it like an one case in your code. In your code you use this line twice:
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
so you already could merge both cases into one, to avoid unnecessary repetitions. So only case when action will differ, is when there is not enough money on a account, you check it by:
if (depOrWithAmount - 1 < fromAcc_SameAcc.getInitialAmount())
but i think i will not work, because in withdraw operation depOrWithAmount is in negative numbers, so it will always be smaller than fromAcc_SameAcc.getInitialAmount(). You can use:
if (depOrWithAmount < 1 - fromAcc_SameAcc.getInitialAmount())
(but i think it is not too readable) or:
if (Math.abs(depOrWithAmount) > fromAcc_SameAcc.getInitialAmount()){}
to compare absolute value of input with initialAmout. However i used:
double result = edited.getInitialAmount() + input;
if(result < 0){...}
because it gives me result variable, which I can reuse if there is enough money, to gives new value to initialAmount. And if result is negative, it means that withdraw amount was bigger than initialAmount, so ther is no enough monay to withdraw.
I hope you found something useful in my post.

Cannot find symbol on a printf line

Did a little bit of research on this error and most seem simple. I checked to see if i had some spelling errors and I didnt notice any. Im trying to print a few lines using printf. When i go to compile this code it gives me a "cannot find symbol error". Could it be that the method these lines are in need to be in the method the variables are defined? The error is only being done in my printSales method.This isnt the finished product so i may be short a piece or two. But here is my code any help would be appreciated.
import java.util.Scanner;
public class Sales
{
public static void main( String[] args)
{
Scanner input = new Scanner (System.in);
System.out.print("Please enter a product number.");
double product1 = 0;
double product2 = 0;
double product3 = 0;
double product4 = 0;
double product5 = 0;
double sale;
int userInput = input.nextInt();
while(userInput != 0)
{
if(userInput >= 1 && userInput <= 5)
{
switch(userInput)
{
case 1: System.out.println("");
product1 ++;
sale += 2.98;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
case 2: System.out.println("");
product2 ++;
sale += 4.50;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
case 3: System.out.println("");
product3 ++;
sale += 9.98;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
case 4: System.out.println("");
product4 ++;
sale += 4.49;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
case 5:System.out.println("");
product5 ++;
sale += 6.87;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
}//end switch
} //end if
else if (userInput != 0)
bSystem.out.println("ERROR: Incorrect Product Number, Please Try Again");
System.out.print("");
userInput = input.nextInt();
}//end while
} //end main
public void printSales()
{
System.out.println();
System.out.printf("Product 1: $%.2f\n", product1);
System.out.printf("Product 2: $%.2f\n", product2);
System.out.printf("Product 3: $%.2f\n", product3);
System.out.printf("Product 4: $%.2f\n", product4);
System.out.printf("Product 5: $%.2f\n", product5);
} //end printSales
} //end class
This is a problem with the scope of your variables. You cannot refer to variables from one method in another method. Try redefining printSales:
public void printSales(int product1, int product2, int product3, int product4, int product5)
{
System.out.println();
System.out.printf("Product 1: $%.2f\n", product1);
System.out.printf("Product 2: $%.2f\n", product2);
System.out.printf("Product 3: $%.2f\n", product3);
System.out.printf("Product 4: $%.2f\n", product4);
System.out.printf("Product 5: $%.2f\n", product5);
} //end printSales
and then of course you will have to change how you call printSales (which I see you are not calling now, but perhaps you will call it in the future):
printSales(product1, product2, product3, product4, product5);
Be sure that product1, product2, etc are all in the same "scope"-- you can't reach into another method, or into an if{} or for{} or while{} block to reference variables.
Four problems...
1
sale might not be initialised...
You declare the sale variable as...
double sale;
As a local variable, it has no default value, so doing something like sale += 2.98 has undefined results.
Simple initialize the variable to a default/starting value...
double sale = 0d;
2
package bSystem does not existbSystem.out.println("ERROR: Incorrect Product Number, Please Try Again");
Typo, it should be System.out.println ;)
3
error: cannot find symbol
System.out.printf("Product 1: $%.2f\n", product1);
The values product1, product2, product3, product4 and product5 have no meaning in printSales as they've only been declared as local variables within main.
Normally, I would suggest making these instance variables, but because you're running within a static context of main, this won't work. Instead, modify the printSales method to take parameters...
public void printSales(double product1, double product2, double product3, double product4, double product5) {
...
}
4
You should be getting a number of warnings about 'unreachable statement, this caused by the fact that youbreakout of theswitch` statement, but attempt to execute code after it...
case 1:
System.out.println("");
product1++;
sale += 2.98;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
^--- These can't be executed, because of the break before it...
Instead, try moving the code before the break statement....
case 1:
System.out.println("");
product1++;
sale += 2.98;
System.out.print("How many were sold?");
userInput = input.nextInt();
break;
You might like to take a look at the Variables trail and Defining Methods for some more details
The variables "double product1/2/3..." are local variables, i.e. their scope and life-cycle are restricted inside the main method - you cannot reach them from printSales().
To solve the problem and be able to modify/call the variables, make them as fields instead. That is, place them inside the context of the class and not a method.
public class Sales
{
//variables moved into the context of the class, i.e. you can reach them from
//all methods of this class. Furhermore, they have to be static in order to be
//accessed from a static method.
private static double product1 = 0;
private static double product2 = 0;
private static double product3 = 0;
private static double product4 = 0;
private static double product5 = 0;
private static double sale;
public static void main( String[] args)
{
Scanner input = new Scanner (System.in);
System.out.print("Please enter a product number.");
//rest of main method but without vairables
}

Inheritance Error in java

This is super class of all,Employee class.
import java.util.Scanner;
import java.util.Calendar;
import java.util.*;
class Employee {
Scanner in = new Scanner(System.in);
Calendar cal = Calendar.getInstance();
String name;
String number;
int month;
int week;
double pay;
void load() {
System.out.println("Enter name of employee");
name = in.nextLine();
System.out.println("Enter social security number");
number = in.nextLine();
System.out.println("Enter employee's birthday month(1-12)");
month = in.nextInt();
System.out.println("Enter employee's birthday week(1-4)");
week = in.nextInt();
}
public String toString() {
return "employee : " + name + " social security number : " + number
+ " paycheck : $" + pay;
}
void getBonus() {
int mont = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
if (month == mont + 1 && week == (day / 7) + 1)
pay = pay + 100;
}
}
This is subclass of employee .
import java.util.Scanner;
class Hourly extends Employee {
Scanner in = new Scanner(System.in);
double pay;
int hpay;
int hours;
void load() {
System.out.println("Enter hourly pay");
hpay = in.nextInt();
System.out.println("Enter no. of hours worked last week");
hours = in.nextInt();
}
double getEarnings() {
if (hours > 40)
pay = 1.5 * (hours - 40) * hpay + hpay * 40;
else
pay = hpay * hours;
return pay;
}
}
There are 2 more subclasses like these and finally i have test file.
import java.util.Scanner;
class driver {
public static void main(String args[]) {
int i;
Scanner in = new Scanner(System.in);
System.out.println("Enter no. of employees");
int a = in.nextInt();
for (i = 1; i <= a; i++) {
System.out
.println("Enter type : Hourly(1),Salaried(2),Salaried plus commision(3)");
int b = in.nextInt();
if (b == 1) {
Hourly h = new Hourly();
h.super.load();// error cannot find symbol h
h.load();
h.getEarnings();
}
if (b == 2) {
Salaried s = new Salaried();
s.load();
s.getEarnings();
}
if (b == 3) {
Salariedpluscommision sp = new Salariedpluscommision();
sp.super();// error that super should be in first line but then
// where can i define sp
sp.super.load();// cannot find symbol sp
sp.load();
sp.getEarnings();
}
}
}
}
I have got 3 errors in these codes and as i am beginner i don't know how can i solve these errors.
My program takes the employee's details from user and calculate paycheck of that employee.
Also,I am confused in how can i print all employee's paychecks at last after user have completed giving input of all employee's details.Can i do these with an array ?
But first,i have to remove these errors and also suggest my which topics are weak which i should focus more.
Thank you in advance
You appear to be a bit confused about the keyword super.
In the code
Salariedpluscommision sp=new Salariedpluscommision();
sp.super();//error that super should be in first line but then where can i define sp
sp.super.load();//cannot find symbol sp
sp.load();
sp.getEarnings();
the compiler is telling you that super cannot be used where you're using it.
Most likely you just don't need it at all in the driver code and the code
Salariedpluscommision sp=new Salariedpluscommision();
sp.load();
sp.getEarnings();
will do what you thought you needed these calls for.
Similarly, in the earlier code, you can likely just delete the line
h.super.load();// error cannot find symbol h
As it's coded however, you might need to call some superclass methods from your subclasses, which is what the keyword is for.
In Hourly and likely the other subclasses, you probably want to call the Employee load method within the subclass load method:
void load(){
super.load();
System.out.println("Enter hourly pay");
hpay = in.nextInt();
System.out.println("Enter no. of hours worked last week");
hours = in.nextInt();
}
which appears to be what you were trying for with some of the non-compiling code in driver.
Several suggestions:
Make Employee an abstract class and add public abstract getEarnings(); method
Simplify your Driver routine to use switch / case rather than multiple if statements
Create an ArrayList to collect a list of all employees
Use the "type" of employee to create the right kind ... use the same variable name though
After creating the "right kind" of employee, load it and get the earnings
.... (print out the earnings?
Just create objects .. don't use "super
Consider the following for Driver:
import java.util.ArrayList;
import java.util.Scanner;
class driver {
public static void main(String args[]) {
ArrayList<Employee> employees = new ArrayList<Employee>();
Employee emp;
double earnings;
int i;
Scanner in = new Scanner(System.in);
System.out.println("Enter no. of employees");
int a = in.nextInt();
for (i = 1; i <= a; i++) {
System.out.println("Enter type : Hourly(1),Salaried(2),Salaried plus commision(3)");
int b = in.nextInt();
emp = null;
switch (b) {
case 1:
emp = new Hourly();
break;
case 2:
emp = new Salaried();
break;
case 3:
emp = new Salariedpluscommision();
break;
default:
System.out.println("You entered an invalid employee type.");
break;
}
if (emp != null) {
emp.load();
earnings = emp.getEarnings();
employees.add(emp);
System.out.println("Earnings are: " + earnings + "for " + emp.getName());
}

Java is not reading a variable I am passing to it after the user modifies it

I have a really long problem. I am creating a bank account and setting the balance to 0. If the user chooses to withdraw or deposit money to the account, the balance never changes. I choose to show the balance and it still says 0. This is probably a no brainer but I am spent right now. Here is my long code(The switch statement is in my main class and the methods are in an object class):
public class MyProgram2{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner (System.in);
String menu, outputString, poo;
int option = 1;
int id = 0;
double balance = 0, amount = 0;
Account acc = new Account();
menu ="\n\t1 Create Account and ID" +
"\n\t2 Check balance" +
"\n\t3 Withdraw" +
"\n\t4 Deposit" +
"\n\t5 Get account ID" +
"\n\t6 Display Account Info" +
"\n\t0 Quit\n\n\n";
System.out.println(menu);
System.out.println("\tEnter your selection: ");
option = scan.nextInt();
while (option != 0) {
switch (option) {
case 1: //Create an account and set ID
System.out.print("Enter Your Account ID to create account:\t");
id = input.nextInt();
System.out.println("Account created!");
break;
case 2: //check balance
acc.checkBalance(balance);
break;
case 3: //withdraw money
acc.withdraw(balance, amount);
break;
case 4: //deposit money
acc.deposit(balance, amount);
break;
case 5: //get account id
acc.getID(id);
break;
case 7: //display account info
System.out.print("option 7");
break;
default: outputString = "\nInvalid Selection\n";
System.out.println(outputString);
break;
}
System.out.println(menu);
System.out.print("\tEnter your selection: ");
option = scan.nextInt();
}
And these are the methods I am calling:
public class Account{
Scanner input = new Scanner (System.in);
public Account(){
}
public void getID(int id){
System.out.println("Your account ID is:\t" + id);
}
public void checkBalance(double balance){
System.out.println("Your balance is:\t$" + balance);
}
public double withdraw(double amount, double balance){
System.out.println("How much do you want to withdraw?:\t$");
amount = input.nextDouble();
balance -= amount;
return balance;
}
public double deposit(double amount, double balance){
System.out.println("How much do you want to deposit?:\t");
amount = input.nextDouble();
balance += amount;
return balance;
}
public void getAccountInfo(int id, double balance){
}
}
The variable double balance cannot be passed as a reference. It does a copy so when you try to manipulate it, it won't affect the original that you pass as an argument. You need to update the value using the return value that you have in the function.
In order to make it work, you should do:
case 4: //deposit money
// note here that you need to update the balance variable using the return value that
// you put in the function
balance = acc.deposit(balance, amount);
break;
Note: Your design separating the balance from the Account class is not ideal per #Psyrus's answer. You should keep the balance as part of the Account class. The reason being that balance is part of the account and if your program grows to handle multiple accounts (just for the sake of examples), separating the variable balance from the account would create maintenance headache (imagine that with two instances of Account, you will have balance1 and balance2 variables (or whatever you will call it) in MyProgram2, the main application). While I gave the cause of your problem in regards of variable passing, you should refactor your code to follow #Psyrus suggestion.
You have your whole Account class set up but without the actual balance variable inside it. Move that variable from your program to your class and it should work. Upon looking further, you have kind of jumbled up bits between the two so do this:
public class MyProgram2{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner (System.in);
String menu, outputString, poo;
int option = 1;
int id = 0;
Account acc = new Account();
menu ="\n\t1 Create Account and ID" +
"\n\t2 Check balance" +
"\n\t3 Withdraw" +
"\n\t4 Deposit" +
"\n\t5 Get account ID" +
"\n\t6 Display Account Info" +
"\n\t0 Quit\n\n\n";
do {
System.out.println(menu);
System.out.println("\tEnter your selection: ");
option = scan.nextInt();
switch (option) {
case 1: //Create an account and set ID
System.out.print("Enter Your Account ID to create account:\t");
id = input.nextInt();
System.out.println("Account created!");
break;
case 2: //check balance
acc.checkBalance();
break;
case 3: //withdraw money
acc.withdraw();
break;
case 4: //deposit money
acc.deposit();
break;
case 5: //get account id
acc.getID(id);
break;
case 7: //display account info
System.out.print("option 7");
break;
default: outputString = "\nInvalid Selection\n";
System.out.println(outputString);
break;
}
} while (option != 0);
}
}
public class Account{
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner (System.in); double balance = 0;
public Account(){
}
public void getID(id){
System.out.println("Your account ID is:\t" + id);
}
public void checkBalance(){
System.out.println("Your balance is:\t$" + balance);
}
public double withdraw(){
System.out.println("How much do you want to withdraw?:\t$");
double amount = input.nextDouble();
balance -= amount;
}
public double deposit(){
System.out.println("How much do you want to deposit?:\t");
double amount = input.nextDouble();
balance += amount;
return balance;
}
public void getAccountInfo(int id, double balance){
}
}
That is one way of doing it, but like I say, your design is a bit of a cross between classes. You should try to keep all properties for an object within that class and create functions for that class to obtain / modify the properties. Printing to the user should be contained in the class responsible for giving the user the interface.
Edit: Oops forgot the while at the end of the do while loop...
You just need to modify the instance you created like this:
public double deposit(){
System.out.println("How much do you want to deposit?:\t");
this.amount = input.nextDouble();
this.balance += amount;
return balance;
}
The this keyword refers to the object that is calling this method in this case acc, so this.amount will modify the amount for that instance.
In your current code, you are just modifying the local variables.
You also need to update your Account class to have the amount and balance attributes:
public class Account{
Scanner input = new Scanner (System.in);
double balance = 0, amount = 0;

Categories

Resources