This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 1 year ago.
I have been working on a project, and I'm encountering a mistake which I can't seem to solve. I encounter an error "non-static variable initBalance cannot be referenced from a static context". I've researched what this is about, but I don't understand what it means.
Here is my code:
import java.util.Scanner;
public class ATM {
Scanner kbd = new Scanner(System.in);
int initBalance = 0;
public static void main(String[] args) {
System.out.print("\n---------------------ATM----------------\n1. Withdraw\n2. Deposit\n3. Transfer\n4. Check balance\n5. EXIT");
System.out.print("\nChoose operation: ");
int option = kbd.nextInt();
while (option<5) {
if(option==1)
withdraw();
else
if(option==2)
deposit();
else
if(option==3)
transfer();
else
if(option==4)
balanceCheck();
}
}
public static void withdraw() {
System.out.print("Enter amount to be withdrawn: ");
int withdrawBalance = kbd.nextInt();
if (withdrawBalance > initBalance) {
System.out.print("Collect your money.");
initBalance = initBalance - withdrawBalance;
System.out.print("Chceck balance? 1. Yes 2. No : ");
int balanceOption = kbd.nextInt();
if (balanceOption==1) {
System.out.print("Remaining balance: " + initBalance);
}
}
else {
System.out.print("Insufficient Balance");
}
}
public static void deposit() {
System.out.print("Enter amount you want to deposit: ");
int depositBalance = kbd.nextInt();
initBalance = initBalance + depositBalance;
System.out.print("Chceck balance? 1. Yes 2. No : ");
int balanceOption = kbd.nextInt();
if (balanceOption==1)
System.out.print("Remaining balance: " + initBalance);
else
if(balanceOption==2)
System.out.print("\nThank you for using this ATM!");
else
System.out.print("Number not in the option.");
}
public static void transfer() {
System.out.print("Enter Account number: ");
int accNum = kbd.nextInt();
System.out.print("Enter amount to be transferred: ");
int moneySent = kbd.nextInt();
if(moneySent > initBalance) {
System.out.print("Transfer Success!");
initBalance = initBalance - moneySent;
System.out.print("Chceck balance? 1. Yes 2. No : ");
int balanceOption = kbd.nextInt();
if (balanceOption==1)
System.out.print("Remaining balance: " + initBalance);
else
if(balanceOption==2)
System.out.print("\nThank you for using this ATM!");
else
System.out.print("Number not in the option.");
}
else {
System.out.print("Insufficient Balance");
}
}
public static void balanceCheck() {
System.out.print("Remaining balance: " + initBalance);
}
}
Static methods (in your case: withdraw, deposit, transfer, balanceCheck) cannot use not static variable (in your case: initBalance).
In order to use the non static variable you must create an object somewhere ( ATM anATM = new ATM()) and to use the static methods you do not create the object you just do for example: ATM.withdraw())
Related
I have a small acount in which to deposit, withdrawl, view balance, and exit. Everything runs perfectly however I would like the balance to ajust according to what method I do (withdrawal, deposit, etc.) I started with joptionpane but had the same problem and thought I should just start over. Anyone point me in the right direction?
Main file:
import java.util.Scanner;
public class Bank1
{
public static void main(String[] args)
{
HomeBank obj1 = new HomeBank();
Scanner keyboard = new Scanner(System.in);
String option;
char object;
System.out.println("This is your home banking account" + "\n");
do
{
System.out.println("What would you like to do today?"+ "\n" +
"\nSelect the following: " +
"\n'B' To View Balance." +
"\n'D' To Deposit" +
"\n'W' To Withdrawal" +
"\n'E' To Exit");
System.out.print("Your selection: ");
option = keyboard.next().toUpperCase();
object = option.charAt(0);
System.out.print("\n");
System.out.println("you entered: " +object+ "\n");
if(object =='D')
obj1.deposit();
else if(object =='W')
obj1.withdrawal();
else if(object =='B')
obj1.balance();
else
System.out.println("**Invalid input**" +
"\n Please try again");
} while(object !='E');
System.out.println("The End");
}
}
Class:
import java.util.InputMismatchException;
import java.util.Scanner;
public class HomeBank
{
private double withdrawal, deposit, balance;
public HomeBank()
{
balance = 100;
withdrawal = 50;
deposit = 150;
}
public HomeBank(double bal, double with, double de)
{
balance = bal;
withdrawal = with;
deposit = de;
}
public static void balance()
{
double balance = 250.00d;
System.out.println("You have $" + balance+"dollars");
}
public static void deposit()
{
Scanner keyboard = new Scanner(System.in);
double deposit = 0.00d;
double balance = 250.00d;
boolean goodput =true;
do
{
try
{
System.out.print("How much would you like to deposit today? :");
deposit = keyboard.nextDouble();
if(deposit > 0.00)
{
System.out.println("you entered $" +deposit+" dollars");
System.out.println("you now have $" + (deposit + balance)+" dollars");
goodput = false;
}
else
{
System.out.println("\n**Error**\nYou cannot deposit a "
+ "negative amount\n");
System.out.println("Please try again\n");
goodput = true;
}
}
catch (InputMismatchException x)
{
System.out.println("I'm sorry but that is an invalid input" +
"\nYou will be redirected to the main menu shortly..."+
"\n");
goodput = false;
}
} while (goodput == true);
}
public static void withdrawal()
{
Scanner keyboard = new Scanner(System.in);
double withdrawal = 0.00d;
double balance = 250.00d;
boolean goodput = true;
do
{
try
{
System.out.println("How much would you like to withdrawal?");
withdrawal = keyboard.nextDouble();
if (withdrawal < 0 || withdrawal > balance)
{
System.out.println("You have either entered a negative number"
+ "or trying to withdrawal more than is in your account");
System.out.println("You cannot withdrawal more than $"+balance);
System.out.println("Please try again");
goodput = true;
}
else
{
System.out.println("You now have $" +(balance-withdrawal)+ "dollars");
System.out.println("Thank you for choosing HomeBank\n"
+ "\nYou will be redirected to the main menu\n");
goodput =false;
}
}
catch (InputMismatchException x)
{
System.out.println("I'm sorry but that is an invalid input" +
"\nYou will be redirected to the main menu shortly..."+
"\n");
goodput = false;
}
} while (goodput == true);
}
}
The issue is how you are updating the values. In your methods, you have something that goes like the following:
double deposit = 0.00d;
double balance = 250.00d;
In there, notice how you are putting the double keyword before the variable. By doing that, you are telling Java to create a new variable named deposit and balance in the local scope.
If you want to modify the fields named deposit and balance, you would definitely have to remove the double keyword before them, and optionally put this. in front of the variable. It would look something like the following:
deposit = 0.00d;
balance = 250.00d;
Or
this.deposit = 0.00d;
this.balance = 250.00d;
You would replace all instances of the variables withdraw, balance, and deposit like that, but only the declaration.
The reason you don't need to specify the type is because you already define it in the field declaration. Therefore when you again define it in the method, you are saying to create a new variable with that name and type in the current scope.
Edit:
As Suyash Limaye said, you will have to remove the static keywords from the methods. Having the static keywords prevents the methods from being able to access the non-static fields, which will cause conflicts.
import java.io.*;
public class Test
{
private final String Name;
private final int AccNo;
private String AccTyp;
private double Bal;
private double BalNew;
private int c=0;
private final int x=0;
private int t;
InputStreamReader isr = new InputStreamReader (System.in);
BufferedReader br = new BufferedReader (isr);
Test()throws IOException
{
System.out.println("Enter Name:");
Name = br.readLine();
System.out.println("Enter Account Number:");
AccNo = Integer.parseInt(br.readLine());
t = AccNo;
{
while(t>0)
{
c++;
t = t/10;
}
}
if(c!=10)
{
System.out.println("Invalid Account Number!");
System.exit(0);
}
else
{
System.out.println("Enter Account Type (Recurring, Savings, Current, Fixed):");
AccTyp = br.readLine();
if(AccTyp.equals("Recurring") || AccTyp.equals("Savings") || AccTyp.equals("Current") || AccTyp.equals("Fixed"))
{
System.out.println("Enter Balance:");
Bal = Double.parseDouble(br.readLine());
}
else
{
System.out.println("Invalid Account Type!");
System.exit(0);
}
}
}
public void display()
{
System.out.println("Depositor's Name: " +Name);
System.out.println("Account No.: " +AccNo);
System.out.println("Account Type: " +AccTyp);
System.out.println("Balance: " +Bal);
}
public void calculation()throws IOException
{
System.out.println("Enter amount to withdraw:");
double n = Double.parseDouble(br.readLine());
if(n>Bal)
{
System.out.println("Not Enough Balance!");
System.exit(0);
}
else
{
BalNew = Bal-n;
}
}
public void New()
{
System.out.println("New Balance is: " +BalNew);
System.out.println("Thank you for your Transaction!");
System.out.println("Please Visit Again!");
}
public static void main(String args[])throws IOException
{`enter code here`
Test obj = new Test();
obj.display();
obj.calculation();
obj.New();
}
}
There is some error showing on my BlueJ.
I ran your code in eclipse and it worked fine.
Here's the output
Enter Name:
xyz
Enter Account Number:
1234567891
Enter Account Type (Recurring, Savings, Current, Fixed):
Recurring
Enter Balance:
30000
Depositor's Name: xyz
Account No.: 1234567891
Account Type: Recurring
Balance: 30000.0
Enter amount to withdraw:
10000
New Balance is: 20000.0
Thank you for your Transaction!
Please Visit Again!
I ran your code in BlueJ the error was that, in the main function, the line enter code here is a useless line. Therefore if we remove the line the program runs absolutely fine :).
i ran my code in Net Beans and it gives so many errors.
1> in the above program, you typed:
private final int AccNo;
then you said:
AccNo = Integer.parseInt(br.readLine());
After declaring a variable "final", you cannot initialise it after it has been declared. So don't declare it a final.
Thats the only thing i got. Will inform you if there are any more errors
I am writing some code to help teach me how code in java and I have been using arrays. I have an error that I can't work out why it is occurring.
The Code:
import java.util.Scanner;
public class pubQuizArray {
private static Scanner kb = new Scanner (System.in);
static String[] questions;
static String[][] answers;
static char[] realAnswers;
static char ans;
static char yn;
static int questionNum;
static int questionNumArray;
static int numQ;
static int score = 0;
public static void writeQuiz()
{
getQNum();
getQ();
}
public static void getQNum()
{
System.out.println("How many Questions?");
numQ = kb.nextInt();
questions = new String[numQ];
}
public static void getAns()
{
questionNumArray = questionNum - 1;
answers = new String[numQ][];
System.out.println("What are the answers?");
System.out.println("a: ");
answers[questionNumArray][0] = kb.nextLine();
System.out.println("b: ");
answers[questionNumArray][1] = kb.nextLine();
System.out.println("c: ");
answers[questionNumArray][2] = kb.nextLine();
System.out.println("d: ");
answers[questionNumArray][4] = kb.nextLine();
realAnswers = new char[numQ];
System.out.println("What is the correct Answer?");
realAnswers[questionNum] = kb.next().charAt(0);
}
public static void getQ()
{
questionNum = 0;
System.out.println("What is the First Question?");
questions[questionNum] = kb.nextLine();
getAns();
questionNum ++;
while(questionNum < numQ)
{
System.out.println("What is the next Question?");
questions[questionNum] = kb.nextLine();
getAns();
questionNum ++;
}
}
public static void askQ()
{
questionNum = 0;
while(questionNum < numQ)
{
System.out.println("Q1: " + questions[questionNum]);
System.out.println("a: " + answers[questionNum][0]);
System.out.println("b: " + answers[questionNum][1]);
System.out.println("c: " + answers[questionNum][2]);
System.out.println("d: " + answers[questionNum][3]);
ans = kb.next().charAt(0);
if(ans == realAnswers[questionNum])
{
System.out.println("That was correct");
score ++;
}
}
}
public static void menu()
{
System.out.println("Would you like to write a new Quiz? y/n");
yn = kb.next().charAt(0);
while(yn == 'y')
{
writeQuiz();
System.out.println("Would you like to play the Quiz? y/n");
yn = kb.next().charAt(0);
while(yn == 'y')
{
askQ();
System.out.println("Would you like to play again? y/n");
yn = kb.next().charAt(0);
}
}
}
public static void main(String[] args)
{
menu();
}
}
The error is this:
Would you like to write a new Quiz? y/n
y
How many Questions?
10
What is the First Question?
What are the answers?
a:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at pubQuizArray.getAns(pubQuizArray.java:34)
at pubQuizArray.getQ(pubQuizArray.java:56)
at pubQuizArray.writeQuiz(pubQuizArray.java:17)
Thanks in advance for any help that you can give. Please bear in mind that this is just a trial program and that I am still learning java.
OK I have another problem this time it says:
Would you like to write a new Quiz? y/n
y
How many Questions?
1
What is the First Question?
and
What are the answers?
a: a
Exception in thread "main" java.lang.NullPointerException
at pubQuizArray.getAns(pubQuizArray.java:34)
at pubQuizArray.getQ(pubQuizArray.java:57)
at pubQuizArray.writeQuiz(pubQuizArray.java:17)
at pubQuizArray.menu(pubQuizArray.java:96)
at pubQuizArray.main(pubQuizArray.java:110)
and i've updated the other previous code.
At this point, inside getAns()
questionNumArray = questionNum - 1;
answers = new String[numQ][];
System.out.println("What are the answers?");
System.out.println("a: ");
answers[questionNumArray][0] = kb.nextLine();
questionNumArray contains the value -1 which is an invalid index for an array.
It comes from
public static void getQ()
{
questionNum = 0; // set to 0
System.out.println("What is the First Question?");
questions[questionNum] = kb.nextLine();
getAns(); // still 0
questionNum ++; // too late
...
}
Edit
The NPE you are getting boils down to
System.out.println("a: ");
answers[questionNumArray][0] = kb.nextLine();
you haven't initialized answers[questionNumArray] so it is null. Do the following first
answers[questionNumArray] = new String[someSize]; // someSize should probably be 5 looking at your code
I made a program that accepts numbers from the user.
Sample of my program:
int strength, health, luck;
JOptionPane.showMessageDialog(null,"Welcome to Yertle's Quest");
String name = JOptionPane.showInputDialog("Enter the name of your character");
Scanner in = new Scanner(System.in);
System.out.println("Enter strength (1-10): ");
strength = in.nextInt();
System.out.println("Enter health (1-10): ");
health = in.nextInt();
System.out.println("Enter luck (1-10): ");
luck = in.nextInt();
My problem is this:
The user is only able to give 15 points. If he puts more than 10 points to each stats (strength,health,luck), the default value will be assign to each stats -which is 5. And if the total points on each stats(strength,health,luck) is more than 15, the default value will be assigned to each stats.
Given I understand the question correctly:
if ( luck + health + strength > 15) {
luck = 5;
health = 5;
strength = 5;
}
if (luck > 10) { luck = 5; }
// same for the other attributes
if(strength > 10)
{
defaultToFive(strength);
}
if(health > 10)
{
defaultToFive(health);
}
if(luck > 10)
{
defaultToFive(luck);
}
if((strength + health + luck) > 15)
{
defaultToFive(strength);
defaultToFive(health);
defaultToFive(luck);
}
private void defaultToFive(int stat)
{
stat=5;
}
Use simple if statements:
import java.util.Scanner;
public class CheckLuck {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);int strength,health,luck;
System.out.println("Enter strength (1-10): ");
strength = in.nextInt();
if(strength>10) /* chech for each value, should not be >10 */
strength=5;
System.out.println("Enter health (1-10): ");
health = in.nextInt();
if(health>10)
health=5;
System.out.println("Enter luck (1-10): ");
luck = in.nextInt();
if(luck>10)
luck=5;
if(strength+health+luck>15) /* If sum is >15 assign 5 to each value */
strength=health=luck=5;
}
}
UPDATE : USING public void decide()
(sorry if this sounds funny)
import java.util.Scanner;
public class TestDecide {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);int strength,health,luck;
System.out.println("Enter strength (1-10): ");
strength = in.nextInt();
if(strength>10)
strength=5;
System.out.println("Enter health (1-10): ");
health = in.nextInt();
if(health>10)
health=5;
System.out.println("Enter luck (1-10): ");
luck = in.nextInt();
if(luck>10)
luck=5;
if(strength+health+luck>15)
{
strength=health=luck=5;
decide();
}
else
{
System.out.println("Congrats!!!!!!!!!!!! for your scores");
}
}
public static void decide()
{
System.out.println("You have given your character too many points! Default values have been assigned: Character, strength: 5, health: 5, luck: 5");
}
}
Currently I am writing a program for an introductory Java class. I have two pieces to my puzzle. Hopefully this is a relatively simple to answer question.
Firstly, here is what I am trying to use as my main program:
import java.util.Scanner;
public class TheATMGame
{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double newBalance = 0;
double monthlyInterest = 0;
int answer = 0;
int i=1;
while (i < 100) {
System.out.print ("Please enter your ID: ");
answer = input.nextInt();
System.out.println(" ");
if (answer >=0 && answer<10)
TheATMGame.runGame (answer);
else
System.out.println("Sorry, this ID is invalid.");
}
}
public static void runGame(int id) {
double amount = 0;
int continueOn = 0;
while (continueOn < 4) {
ATMGame myATM = new ATMGame();
Scanner input = new Scanner(System.in);
System.out.println ("---Main menu--- ");
System.out.println ("1: Check balance ");
System.out.println ("2: Withdraw ");
System.out.println ("3: Deposit ");
System.out.println ("4: exit ");
int answer = input.nextInt();
if (answer == 1)
System.out.println("your balance is: " + myATM.getBalance (id));
else if (answer == 2){
System.out.println("Enter an amount to withdraw: ");
amount = input.nextInt();
myATM.withdraw(amount, id);
}
else if (answer == 3)
{
System.out.println("Enter an amount to deposit: ");
amount = input.nextInt();
myATM.deposit(amount, id);
}
else if (answer == 4)
continueOn = 4;
else if (answer > 4)
System.out.println ("Please review the main menu. " +
"Your selection must be between 1-4.");
}
}
//ATM class (balance, annualInterestRate2, id2)
//ATM myATM = new ATM (20000, 4.5, 1122 );
//newBalance = myATM.withdraw(2500);
//newBalance = myATM.deposit(3000);
//monthlyInterest = myATM.getMonthlyInterestRate();
//System.out.println("Your current balance is: " + newBalance);
//System.out.println ("Your monthly interest rate is: " + monthlyInterest);
}
Now here are all of the classes I want to impliment into that program:
import java.util.Date;
public class ATMGame {
private double annualInterestRate = 0;
private double balance = 0;
private int id = 11;
private int[] ids = {0,1,2,3,4,5,6,7,8,9};
private int[] balances = {100,100,100,100,100,100,100,100,100,100};
public Date dateCreated;
public ATMGame() {
}
public ATMGame (double balance2, double annualInterestRate2, int id2) {
balance = balance2;
annualInterestRate = annualInterestRate2;
id = id2;
dateCreated.getTime();
}
public double getMonthlyInterestRate() {
double monthlyInterest = annualInterestRate/12;
return monthlyInterest;
}
public double withdraw(double amountWithdrawn, int id) { //This method withdraws money from the account
double newBalance = balances[id] - amountWithdrawn;
System.out.println("Your withdrawel has processed. New balance: " + newBalance);
balances[id] = (int) newBalance;
return newBalance ;
}
public double deposit(double amountDeposited, int id) { //This method deposits money in the account
double newBalance = balances[id] + amountDeposited;
System.out.println("Your deposit has processed. New Balance is: " + newBalance);
balances[id] = (int) newBalance;
return newBalance ;
}
public double getBalance(int id) {
double myBalance = balances[id];
balance = myBalance;
return myBalance ;
}
}
When I try to run the first program it says "No Main classes found."
As you can see I have written the line " public void Main() ..." to take care of this, but eveidently it does not work. What am I doing wrong?
Replacing "public void Main() {" with "public static void main(String[] args) {" still returns the error: "No Main classes found." :/
http://img21.imageshack.us/img21/9016/asdfsdfasdfg.jpg
I was able to fix it by changing Main.java to TheATMGame.java and then running from ATMGame.java.
You should use:
public static void main(String[] args)
Instead of Main because the JVM calls this method first. It is a convention.
You've just misdefined main. Should be:
public static void main(String[] args) {
....
}
You're going to run into some other problems with your code, though. From a quick glance...
Your main() is a function, as well as runGame() - one shouldn't be defined within the other.
You cannot name your two classes the same thing - call the main() class something different than ATMGame.
Not sure where you're going with ATM class (balance, annualInterestRate2, id2), but it's not valid Java.
Your method signature must be:
public static void main(String[] args) {
...
}
That's the convention you have to follow. Anything else won't work.
In your class ATMGame, replace the following:
public void Main() {
with:
public static void main(String[] args) {
Additionally, since this method has to be static, you'll need to change the following:
if (answer >=0 && answer<10)
runGame (answer);
else
with:
if (answer >=0 && answer<10)
ATMGame.runGame (answer);
else
Then finally, you need to change the method signature of rungame to also be static. Change it from:
public void runGame(int id) {
to:
public static void runGame(int id) {
The names of your public classes should match the file names. This is not the case in your screenshot. Also make sure that everything compiles correctly and then retry (using a public static void main(String[] args) { ... } method).