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
Related
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())
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.
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.
I have to write a ATM program for my computer science class. It works for the most part, apart from a couple logic problems within the programs itself. So far, from what I can tell, my ATM will deposit the correct amount of money that I tell it to however, when I withdraw money, it does not always withdraw the correct amount if I purposefully make an error (such as trying to take out an amount that is not a multiple of 20). I am also running into an issue where if I try to take out more money then is actually in the account, it will become a negative value, which I do not want to be allowed. I want it not to subtract the value that causes it to become negative and for it to prompt the user until a value less then or equivalent to the balance is able to be taken out. I am rather new to coding so please excuse my rather messy code. My error is probably around the else if statement where option == 3. Here is my code:
import java.io.*;
import java.util.*;
public class aTMLauncher
{
public static int options=0;
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
aTMTester atm = new aTMTester();
System.out.println("Login: \n(case sensitive)");
System.out.print("Username > ");
String usernameInput=input.nextLine();
int count=4;
while (!usernameInput.equals(aTMTester.getUsername()))
{
System.out.println("\nIncorrect input. Please try again. You have " + (count-1) + " trys remaining attempts.");
System.out.println("Login: \n(case sensitive)");
System.out.print("Username > ");
count--;
if(count==0)
{
System.out.println("No remain attempts, system will now exit");
System.exit(0);
}
usernameInput = input.nextLine();
}
System.out.print("Pin > ");
int PINInput=input.nextInt();
int count1=4;
while (PINInput<aTMTester.getPIN() || PINInput>aTMTester.getPIN())
{
System.out.println("\nIncorrect input. Please try again. You have " + (count1-1) + " trys remaining");
System.out.print("Pin > ");
count1--;
PINInput=input.nextInt();
if(count1==0)
{
System.out.println("No remain attempts, system will now exit");
System.exit(0);
}
}
System.out.println("\nWelcome, " + aTMTester.getUsername() +"!");
while(PINInput==2468)
{
atm.main();
options = input.nextInt();
if (options==4)
{
atm.logout();
}
else if(options==2)
{
System.out.println("How much money would you like to deposit?");
System.out.print("$ ");
atm.deposit = input.nextInt();
atm.balance+=atm.deposit;
System.out.println("Your new balance is $" + atm.balance +"0");
}
else if(options==3)
{
System.out.println("How much money will you be withdrawing? \n(Only amounts divisible by 20 are accepted) \n$");
atm.withdraw= input.nextInt();
atm.balance-=atm.withdraw;
if(atm.withdraw%20==0.0)
{
System.out.println("You took out " +atm.withdraw);
System.out.println("Your new balance is $" + atm.balance);
}
while(atm.withdraw%20>0)
{
System.out.println("Invalid withdraw amount. Please retry.");
System.out.println("\nHow much money will you be withdrawing? \n(Only amounts divisible by 20 are accepted)");
atm.withdraw= input.nextInt();
System.out.println("You took out " +atm.withdraw);
System.out.println("Your new balance is $" + atm.balance);
}
if(!(atm.balance>0.0))
{
System.out.println("You are not allowed to take out more then you have in your account \n Please retry");
atm.withdraw= input.nextInt();
}
}
else if(options==1)
{
System.out.println("Your account balance is $"+atm.balance+"0");
}
}
}
}
public class aTMTester
{
private static final String username = "David";
private static final int PIN = 2468;
public static int deposit, withdraw;
public static double balance=0.00;
private String menu;
/*
* Default constructor
*/
public aTMTester()
{
}
public static String getUsername()
{
return username;
}
public static int getPIN()
{
return PIN;
}
public static void main()
{
System.out.println("\n+++++++++++Account: "+ username +"+++++++++++");
System.out.println("1. Check Account Balance");
System.out.println("2. Deposit Checks");
System.out.println("3. Withdraw Money");
System.out.println("4. Logout");
System.out.print("\nWhat would you like to do next?\n");
}
public static void logout()
{
System.out.println("Thanks for usinging the David Vachlon Inc. ATM. We hope you expierence was fast and simple! Have a great day.");
System.exit(0);
}
public static double getBalance()
{
return balance;
}
public static void deposit()
{
balance+=deposit;
}
public static void withdraw()
{
balance-=withdraw;
}
}
You should do atm.balance -= atm.withdraw; after all checks was successfully passed. For instance, you may restructure your code as follows:
boolean ok = false;
while (!ok) {
System.out.println("\nHow much money will you be withdrawing? \n(Only amounts divisible by 20 are accepted)");
atm.withdraw = input.nextInt();
if (atm.withdraw % 20 != 0) {
System.out.println("Invalid withdraw amount. Please retry.");
} else if (atm.balance < atm.withdraw) {
System.out.println("You are not allowed to take out more then you have in your account \n Please retry");
} else if (atm.withdraw < 0) {
// Probably you should not allow to withdraw a negative amount of money
} else {
ok = true;
}
}
atm.balance -= atm.withdraw;
System.out.println("You took out " + atm.withdraw);
System.out.println("Your new balance is $" + atm.balance);
This is my code. The program won't give me the last print line "Thank you for using the Basic user Interface program."
public class nameClass {
public static void main(String[] args) {
String input;
String name;
int age;
double mileage;
displayApplicationInformation();
displayDivider("Start Program");
TerminateApplication();
// process name
displayDivider("Get Name");
name = getInput("name");
System.out.println("Your name is: " + name);
// Process age
displayDivider("Get Age");
input = getInput("Your age");
age = Integer.parseInt(input);
System.out.println("Your age is: " + age);
// Process Mileage
displayDivider("Get Mileage");
input = getInput("Your MPG");
mileage = Double.parseDouble(input);
System.out.println("Your car MPG is: " + mileage);
}// end of main
public static void displayApplicationInformation()
{
System.out.println("Welcome to the Basic User Interface Program");
}// end of displayApplicaionInformation
public static void displayDivider(String outputTitle) {
System.out.println("*********" + outputTitle + "********");
}// end of displayDvider
public static String getInput(String inputType)
{
String input = "";
input = JOptionPane.showInputDialog("Enter the " + inputType);
return input;
}
public static void TerminateApplication()
{
System.out.println("Thank you for using the Basic User Interface program");
return;
}
}// end of MainClass
You have to actually call the method TerminateApplication;
System.out.println("Your car MPG is: " + mileage);
TerminateApplication();
Simple, call TerminateApplication.
You are doing it on the 9th line of main().
Here, check this out:
displayDivider("Get Mileage");
input = getInput("Your MPG");
mileage = Double.parseDouble(input);
System.out.println("Your car MPG is: " + mileage);
//add this...
TerminateApplication();
Hope this helps!