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
}
Related
I am a beginner at Java coding. Just started an online class less than 4 weeks ago. Im currently working on a project where I need to
traverse a logical decision to determine the need of a customer. Simulate a gas station that has 4 stations...
After piecing together what I know so far, I came up with the code below. It does have some yellow errors and when I run in Eclipse I only get the print out:
welcome to gas station, choose station number 1, 2 or 3.
Can I get some help on what to do from here please?
public static void main(String[] args) {
int stations;
keyboard2 = new Scanner(System.in);
System.out.print("Welcome to Gas Station \n");
System.out.println("Choose Station Number: \n");
System.out.println("1, 2, or 3 \n");
stations = keyboard2.nextInt(2);
switch (stations) {
case 1:
System.out.println("You entered Station 1.");
break;
case 2:
System.out.println("You entered Station 2.");
break;
case 3:
System.out.println("You entered Station 3.");
break;
default:
System.out.println("Error: Invalid Number");
}
}
private Scanner keyboard;
{
System.out.print("Choose your fuel type:\n");
System.out.println("Press 1 for Unleaded\n");
System.out.println("Press 2 for Unleaded Plus\n");
System.out.println("Press 3 for Unleaded Premium\n");
int gastype;
gastype = keyboard.nextInt(2);
switch (gastype) {
case 1:
System.out.println("You Chose Unleaded.");
break;
case 2:
System.out.println("You Chose Unleaded Plus.");
break;
case 3:
System.out.println("You Chose Unleaded Premium.");
break;
default:
System.out.println("Error: Invalid Number");
}
}
private Scanner keyboard1;
{
System.out.print("Enter gallon amount"
+ "Max amount 30 gallons)");
int numberGallons;
numberGallons = keyboard.nextInt(9);
}
double totalPayment = 0.0;
double numberGallons = 0;
double Unleaded = 0;
double UnleadedPlus = 0;
double UnleadedPremium = 0;
double tax = 0;
private static Scanner keyboard2;
{
Unleaded = 2.50;
UnleadedPlus = 3.00;
UnleadedPremium = 3.50;
tax = 3.5;
totalPayment = numberGallons + Unleaded * tax;
System.out.println("total gas amount: " + numberGallons
+ "\ntotal payment:" + Unleaded * tax + "\nthank you");
}
You seem to be missing knowledge about the structure of a class and need more practice at indenting / paying attention to bracket, if I remove parts of your code with placeholders, and indent things correctly (which can be simulated by "folding" those sections of code in your IDE, and auto formatting).
public static void main(String[] args)
{//Start main method
int stations;
keyboard2 = new Scanner(System.in);
System.out.print("Welcome to Gas Station \n");
System.out.println("Choose Station Number: \n");
System.out.println("1, 2, or 3 \n");
stations = keyboard2.nextInt(2);
switch (stations)
{
case 1:
System.out.println("You entered Station 1.");
break;
case 2:
System.out.println("You entered Station 2.");
break;
case 3:
System.out.println("You entered Station 3.");
break;
default:
System.out.println("Error: Invalid Number");
}//End Switch
}//End Main Method
private Scanner keyboard;
{
//Snip 1
}
private Scanner keyboard1;
{
//Snip 1
}
//Marker 2
double totalPayment = 0.0;
double numberGallons = 0;
double Unleaded = 0;
double UnleadedPlus = 0;
double UnleadedPremium = 0;
double tax = 0;
private static Scanner keyboard2;
{
//Snip 1
}
}//Class End
The sections I've commented with //Snip 1 are outside your main method, java is interpreting these as class initializers.
(see https://www.dummies.com/programming/java/what-is-an-initializer-in-java/)
These are NOT running with your main method, and not actually running at all, as they arn't static class initializers.
private Scanner keyboard;
private Scanner keyboard1;
and the other fields below //Marker 2 are being defined in the class instance scope.
You main method, like all main entry points, is static, there is no classes yet initialized, so anything in the class instance scope is not running, and no class initializers have been run.
To fix this, simply delete the //End Main Method bracket, create another at the very end of your class, and everything will be included in the main method again. I recommend auto formatting your code at this point.
Eclipse will complain about the fields, which will now be turned into local variables as they will be defined in the scope of the main method, so you can fix that by removing the access modifier 'private' in front of keyboard, keyboard1. In fact, you can use the same keyboard variable as a local variable for each time you use it, even without making it a field in the class.
Hope this helps.
Edit: It appears you may have been attempting to split this into multiple methods, and getting them confused with fields. If so, you need to read up on how to declare methods, just specifying {} after a field isn't enough.
In this case Snip 1 would be marking where you attempted to create new methods.
you would need to specify them as
private static void keyboard1()
{
Scanner keyboard1 = new Scanner(System.in);
//Snip1
};
in this case, private void keyboard1() has NO relation to Scanner keyboard1 and can be named whatever is convenient. You would then need to go on to calling this method in your main method. As it is static, you are safe to do so, but if you need multiple gas stations, you would need to make them non static, and initialize an instance.
If you get stuck passing variables between methods, you can either 1. declare them as fields in the class (noting that they will have to be static, since you are accessing them in the static main method, without instantiating a class.) Or pass them as arguments to the method.
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");
I made a program to calculate total price based on user's input. It is working fine, but i would like to know how to cut the code but to have the same output.
Especially on IF ELSE statement, I would like to know how not to repeat myself in those blocks. Is there any other way I can write ouputs after IF ELSE blocks, or they have to be individually inside of those blocks? Thanks.
Here is the code
import java.util.Scanner;
import java.text.*;
public class GasCalc
{
public static void main(String[] args)`enter code here`
{
double gasPrice,carGallons,fullTank,totalPrice;
Scanner input=new Scanner(System.in);
System.out.print("Do you want to calculate full tank (y/n) ");
String askMe=input.next();
if
(askMe.equalsIgnoreCase("y"))
{
DecimalFormat num=new DecimalFormat("$,###.00");
System.out.print("What is the price of 1 gallon of gas ? ");
gasPrice=input.nextDouble();
System.out.print("How many gallons does your vehicle accept ? ");
fullTank=input.nextDouble();
totalPrice=gasPrice*fullTank;
System.out.println("You will pay "+num.format(totalPrice)+" for the full tank of gas");
}
else
if(askMe.equalsIgnoreCase("n"))
{
DecimalFormat num=new DecimalFormat("$,###.00");
System.out.print("How many gallons do you need ? ");
carGallons=input.nextDouble();
System.out.print("What is the price of 1 gallon of gas ? ");
gasPrice=input.nextDouble();
totalPrice=gasPrice*carGallons;
System.out.println("You will pay "+num.format(totalPrice)+" for "+carGallons+" gallons of gas");
}
}
}
If I understand your question correctly - you don't want to repeat the same code in the 'if' and the 'else' parts of an if statement.
The way you would do this is to the same as anywhere else: extract the common code as a function/method which is called from both places.
You can move the last two statements outside, that way your calculation and printing can be done outside the if-else block.
You can rename fullTank and carGallons to gallons, so both variables have the same name, that way the last two statements can be used outside if-else.
totalPrice=gasPrice*gallons;
System.out.println("You will pay "+num.format(totalPrice)+" for the full tank of gas");
Use a method and factorize the local variable num, used in both if and else :
public class GasCalc {
private static double readDouble(Scanner in, String msg) {
System.out.print(msg);
return in.nextDouble();
}
private static String readString(Scanner in, String msg) {
System.out.print(msg);
return in.next();
}
public static void main(String[] args) {
double gasPrice, carGallons, fullTank, totalPrice;
Scanner input = new Scanner(System.in);
String askMe = readString(input,"Do you want to calculate full tank (y/n) ");
DecimalFormat num = new DecimalFormat("$,###.00");
if (askMe.equalsIgnoreCase("y")) {
gasPrice = readDouble(input,"What is the price of 1 gallon of gas ? ");
fullTank = readDouble(input,"How many gallons does your vehicle accept ? ");
totalPrice = gasPrice * fullTank;
System.out.println("You will pay " + num.format(totalPrice) + " for the full tank of gas");
} else if (askMe.equalsIgnoreCase("n")) {
carGallons = readDouble(input,"How many gallons do you need ? ");
gasPrice = readDouble(input,"What is the price of 1 gallon of gas ? ");
totalPrice = gasPrice * carGallons;
System.out.println("You will pay " + num.format(totalPrice) + " for " + carGallons + " gallons of gas");
}
}
}
You could actually factorize even more but it would make little sense to create another method for such a specific treatment. If you are using JDK 8 and understand the lambda expressions, go for it.
This is for an assignment in my class. It is to make an automatic ordering system. I'm still new to Java so everything doesn't necessarily click just yet. I think most things work for the most part but the main thing I am having trouble with is making the loop itself and making an exit for it.
import java.util.Scanner;
public class Metal {
public static void main (String[] args) {
double PRICE1 = 5.00;
double PRICE2 = 7.00;
double PRICE3 = 3.50;
double PRICE4 = 0.75;
double TAX = 0.05;
System.out.println ("Metal Down Your Mouth Menu");
System.out.println ();
System.out.println ();
System.out.println ();
System.out.println ("1. Black Sabbath Burgers (Hamburgers With Black Buns) " + PRICE1);
System.out.println ("2. Rack of Lamb of God (Rack of Lamb) " + PRICE2);
System.out.println ("3. Texas Hippie Collar Greens (Collar Greens) " + PRICE3);
System.out.println ("4. Pepsi " + PRICE4);
System.out.println ("Press any other button to stop ordering.");
Scanner userInput = new Scanner(System.in);
int itemnumber = 0;
while (itemnumber < 1 || itemnumber > 4) {
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
}
System.out.print ("How many?");
int amount = userInput.nextInt();
double subtotal = 0;
double total = 0;
double price = 0;
double taxes = 0;
String name = "";
switch (itemnumber){
case 1: name = "Black Sabbath Burgers"; price = PRICE1; break;
case 2: name = "Rack of Lamb of God"; price = PRICE2; break;
case 3: name = "Texas Hippie Collar Greens"; price = PRICE3; break;
case 4: name = "Pepsi"; price = PRICE4; break;
}
subtotal = price * amount;
total = subtotal + total;
System.out.print("Price for items: " + subtotal);
System.out.print("Price Total: " + total);
}
This is my first time posting on this site, but I think I found your problem. There are two large errors, indicated by the arrows:
while (itemnumber >= 1 || <-- itemnumber <= 4) {
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
} <--
1) This should be a '&&' not a '||'. You want it to be within the range. Right now the number it reads has to be greater than or equal to 1 OR less than or equal to 4, which is all integers.
2) You close your loop prematurely. What your code does right now (after the && switch) is it takes numbers 1-4 and keeps repeating the "Enter the item number...." line until you put a number not in the range, then it continues.
The fix: there are a few ways to fix this. My fix would be thus, and the explanation will come after:
import java.util.Scanner;
public class Metal {
public static void main (String[] args) {
double PRICE1 = 5.00;
double PRICE2 = 7.00;
double PRICE3 = 3.50;
double PRICE4 = 0.75;
double TAX = 0.05;
System.out.println ("Metal Down Your Mouth Menu");
System.out.println ();
System.out.println ();
System.out.println ();
System.out.println ("1. Black Sabbath Burgers (Hamburgers With Black Buns) " + PRICE1);
System.out.println ("2. Rack of Lamb of God (Rack of Lamb) " + PRICE2);
System.out.println ("3. Texas Hippie Collar Greens (Collar Greens) " + PRICE3);
System.out.println ("4. Pepsi " + PRICE4);
System.out.println ("Press any other button to stop ordering.");
Scanner userInput = new Scanner(System.in);
int itemnumber = 0;
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
double total = 0;
while (itemnumber >= 1 && itemnumber <= 4) {
System.out.print ("How many?");
int amount = userInput.nextInt();
double subtotal = 0;
double price = 0;
double taxes = 0;
String name = "";
switch (itemnumber)
{
case 1: name = "Black Sabbath Burgers"; price = PRICE1; break;
case 2: name = "Rack of Lamb of God"; price = PRICE2; break;
case 3: name = "Texas Hippie Collar Greens"; price = PRICE3; break;
case 4: name = "Pepsi"; price = PRICE4; break;
}
subtotal = price * amount;
total = subtotal + total;
System.out.print("Price for items: " + subtotal);
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
}
System.out.print("Price Total: " + total);
}
}
Explanation: In essence, you had like 90% of it. I moved the mentioned '}' to the end here:
itemnumber = userInput.nextInt();
} <--
That way, it loops over this code until the user ends.
Additionally, your loop does not need much fixing. It can be used with the && fix. However, you have to put that top line before the loop.
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
And then you put the same line at the end of the loop to reset itemnumber. What your loop does is if itemnumber is between 1 and 4, it executes the following code. Otherwise, it stops. By checking before you enter the loop, you set itemnumber so that way the loop has something to check. And you put the next input at the end of the loop so that way your program finishes totaling its first execution before moving on to the next.
Additionally, you should move the variable 'total' out of the loop as seen above. If you keep looping over it and resetting it to 0, your total will output 0 every time. Best to keep the creation of total out of the loop, and its modification inside the loop.
Small tip, use System.out.println(); instead of System.out.print(); it puts the outputs on its own line. Looks a little nicer.
I think that covers it. If you want more explanation, I'd be more than happy to give it to you. Java is pretty fun once you get used to it. It just takes time. :D
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;