// I am new to Java and was practicing some questions on netbeans. I get compilation error on public class bank_acc ( ide is suggesting me to change the name of my whole program to bank_acc but as far as I know the program name is same as the class name which has the main function ). When I change it I get error on class prog2. Either way it's not working out. Please help.
package prog2;
import java.util.Scanner;
public class bank_acc{
String name;
double acc_no;
String acc_type;
double bal;
Scanner s = new Scanner(System.in);
void bank_acc(){
System.out.println("Enter basic values");
name = s.nextLine();
acc_no = s.nextInt();
acc_type = s.nextLine();
bal = 1000;
}
// function to deposit money in acc.
void deposit(){
System.out.println("Enter the amount to be deposited");
double amt=s.nextDouble();
bal+=amt;
}
// function to withdraw amt after checking it.
void wac(){
System.out.println("Current balance = "+bal);
System.out.println("Enter amount to be withdrawn");
Double wdraw_amt=s.nextDouble();
bal-=wdraw_amt;
}
void display(){
System.out.println("Welcome to THE BANK !");
System.out.println("Your name is: "+name);
System.out.println("Account Balance: "+bal);
}
}
public class Prog2{
public static void main(String[] args) {
// TODO code application logic here
bank_acc a = new bank_acc();
a.deposit();
a.wac();
a.display();
System.out.println("Thank you. Keep working!");
}
}
You can have only one top level public either class or interface in any java compilation unit ( .java source file ).
Related
I have been trying to build a simple java application which simulates bank deposits and withdrawals.
I tried to use the JOptionPane to show an error if the user tries to withdraw more than the bank account balance. But the JOptionPane does not display the message and the code does not proceed to the next line.
My Bank class which contains the main application
import java.util.Scanner;
public class Bank {
public static void main(String[] args)
{
//Define an object of type Scanner to get the input
Scanner inp = new Scanner(System.in);
String name; //Local variable to get the name
double bal; //Local variable to get the balance
//Getting the inputs from the user
System.out.println("Enter the name: ");
name = inp.nextLine();
System.out.println("Enter the balance: ");
bal = inp.nextDouble();
Account a1 = new Account(name, bal); //Creating Account object a1
inp.nextLine();
/**The above command is to remove the newline character after
inp.nextDouble() since it is not consumed by it and this affects
the string input in the following lines*/
System.out.println("Enter the name: ");
name = inp.nextLine();
System.out.println("Enter the balance: ");
bal = inp.nextDouble();
Account a2 = new Account(name, bal); //Creating Account object a2
//Displaying the input details
a1.dispDetails();
a2.dispDetails();
/**For this app we just withdraw money from a1 and deposit in a2 */
System.out.println("Enter the amount to be withdrawn from a1");
double w_d = inp.nextDouble();
a1.withdraw(w_d);
a1.dispDetails();
System.out.println("Enter the amount to be deposited in a2: ");
double deposit = inp.nextDouble();
a2.credit(deposit);
a2.dispDetails();
System.out.println( "Number of accounts created is "+Account.getCount());
}
}
My Account class in which the JOptionPane is not working
import javax.swing.*;
public class Account {
/** Declaration of the class variables*/
private final String name; //store the name of the account holder
private double balance;//store the balance
private final int acc_num; //since account number is not changed, set as final
static int count = 0; //to keep track of the number of accounts
JFrame f = new JFrame();
public Account(String n,double bal)
{
count++;
this.name = n;
//generating a random account number based on count
this.acc_num = count*599*254715;
this.balance = bal;
}
/** static function to access the static variable*/
static int getCount()
{
return count;
}
/** To deduct amount on withdrawal Raises a warning if there is
insufficient balance*/
public void withdraw (double amt)
{
if(amt < balance)
balance -= amt;
else
{
JOptionPane.showMessageDialog(f, "Insufficient Balance");//not working
}
}
//credit an amount to the account
public void credit (double amt)
{
balance += amt;
}
//display the details of the account
public void dispDetails()
{
System.out.println("Name: "+name+"\nAccount number: "+acc_num);
System.out.println("Balance= "+balance+"\n");
}
}
It does not get any input or stop running after the JOptionPane line.
Please help. Thanks
I think it has something to do with the AWT-Thread and how the shutdown happens (it needs at least one active window it seems). I fixed it by creating an invisible JFrame which somehow doesn't let the AWT-Threads end. Just put this as the first statements in your main:
JFrame f = new JFrame();
f.setVisible(true);
SwingUtilities.invokeLater(() -> f.setVisible(false));
and your JOptionPane will work.
In order to understand Classes/Inheritance, I was writing java program to calculate bmi and I have 2 classes in my program one is to take the inputs and other class to display output. However, I am not able to see my captured inputs from the output window rather I am seeing null/blanks
Please find the program, and help me/guide me with correct code.
Package programspractice;
import java.util.Scanner;
class bmipatino
{
static Scanner sc=new Scanner(System.in);
String name;
int age;
double height;
double weight;
static void patinfos()
{
System.out.println("Enter the name of the Patient ");
String name=sc.nextLine();
System.out.println("Enter the age of patient ");
int age=sc.nextInt();
System.out.println("Enter the Height of patient");
double height=sc.nextDouble();
System.out.println("Enter Weight of the patient");
double weight =sc.nextDouble();
}
}
public class BmiUsingMethods extends bmipatino
{
void vitals()
{
System.out.println("Patients name is "+super.name);
System.out.println("Patients Age is "+super.age);
System.out.println("Patients Height is "+super.height);
System.out.println("Patients Weight is "+super.weight);
}
public static void main(String[] args)
{
BmiUsingMethods ref = new BmiUsingMethods();
ref.patinfos();
ref.vitals();
}
}
You have multiple problems in your code. Your patinfos() is static, so the values are not bound to a specific instance of the class.
You redefine name, age, etc in this static method, and they shadow the instance variables.
So if you remove the static keyword and local variable declarations, this will work:
void patinfos()
{
System.out.println("Enter the name of the Patient ");
name=sc.nextLine();
System.out.println("Enter the age of patient ");
age=sc.nextInt();
System.out.println("Enter the Height of patient");
height=sc.nextDouble();
System.out.println("Enter Weight of the patient");
weight =sc.nextDouble();
}
I am working on a project for school. at this point i'm just going over board, I would like to run the class bookstoreCreditPersonal if none of the following conditions are true, but I cant get it to work. any suggestions?
import java.util.Scanner;
public class bookstoreCreditPersonal {
public static void main(Object o) {
String studentNamePers;
String userType;
double studentGPAPers;
double bookstoreCreditPers;
Scanner input = new Scanner(System.in);
System.out.print("Please enter 'S' if you are the student, 'T' if you are the teacher, or 'P' if you are the Parent: ");
userType = input.nextLine();
if (userType.equals("S")) {
System.out.println("Greetings student...");
Scanner Sinput = new Scanner(System.in);
System.out.println("Please enter your(The students) first and last name :");
studentNamePers = input.nextLine();
Scanner SSinput = new Scanner(System.in);
System.out.println("Please enter your(The student's) GPA :");
studentGPAPers = input.nextDouble();
bookstoreCreditPers = studentGPAPers * 10;
System.out.println(studentNamePers + ", your GPA is " + studentGPAPers + ", and you have an available bookstore credit of $" + bookstoreCreditPers);
} else if (userType.equals("T")) {
System.out.println("Teacher");
} else if (userType.equals("P")) {
System.out.println("Parent");
} else {
System.out.println("Lets try that again, one character, in capital form only please.");
//created a class that reruns this class
runClassBSCP.call(null);
}
}
}
Here is the class runClassBSCP:
public class runClassBSCP {
public void call() {
bookstoreCreditPersonal.main(null);
}
}
You need to instantiate/create an object of the class. Then you can call the desired method with the object.
runClassBSCP bscp = new runClassBSCP();
bscp.call();
Also, your class names should always start with an uppercase letter: RunClassBSCP, rather than `runClassBSCP'. For more info, check out Code Conventions for the Java Programming Language.
This question already has answers here:
Syntax error on token(s), misplaced construct(s) Code Help Needed
(2 answers)
Closed 9 years ago.
I am using eclipse to look at my code and the most common error that comes up is "Syntax error on token(s), misplaced construct(s)" I'm not sure what I am doing wrong, but I am fairly new to Java.
My code is supposed to withdraw an indicated (user-input) amount from a bank account, I started off with $10,000 and set up the program so that if the withdrawal amount is less than 0 or greater than $10,000 it will trigger an assertion error.
class ThreadsUnitProject2 {
public static void main(Sting args [])
// Field member
private int balance;
public void BankAccount()
{
balance = 10000;
}
public int withdraw(int amount)
{
// Subtract requested amount from balance
balance-=amount;
// Return requested amount
return amount;
}
public int getBalance()
{
return balance;
}
import java.util.Scanner;
class BankAccountTester extends BankAccount
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
BankAccount myAccount = new BankAccount();
System.out.println("Balance = " + myAccount.getBalance());
System.out.print("Enter amount to be withdrawn: ");
int amount = scan.nextInt();
assert (amount >= 0 && amount <= myAccount.getBalance()):"You can't withdraw that amount!";
myAccount.withdraw(amount);
System.out.println("Balance = " + myAccount.getBalance());
}
Thank you for all of your help!
rename your class "ThreadsUnitProject2" to BankAccount and remove main() method from that and make BankAccountTester class public and finally remove void from BankAccount constructor
After seeing so many issues in your code I decided I should just fix it and let you try to learn from the solution seen below.
This should be the first Class file.
public class BankAccount {
private int balance;
public BankAccount() { //constructor
balance = 10000;
}
public int withdraw(int amount) {
balance -= amount;
return amount;
}
public int getBalance() {
return balance;
}
}
This should be your second Class file. This one will contain your main method which will test your BankAccount class.
import java.util.Scanner;
public class BankAccountTester {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
BankAccount myAccount = new BankAccount();
System.out.println("Balance = " + myAccount.getBalance());
System.out.print ("Enter amount to be withdrawn: ");
int amount = scan.nextInt();
assert (amount >= 0 && amount <= myAccount.getBalance()) : "You can't withdraw that amount!";
myAccount.withdraw(amount);
System.out.println("NewBalance = " + myAccount.getBalance());
}
}
Please read and review this link to proper coding conventions.
package developer;
import java.util.*;
import java.lang.Math.*;
public class Developer
{
static Scanner console = new Scanner(System.in);
String workType; // This will be either an app, or game
String name;
int pay;
int weekPay;
int hrsWorked;
double tax;
public Developer()
{
name = "Ciaran";
}
Developer(String appType, String coderName)
{
workType = appType;
name = coderName;
}// End developer
Developer(String appType, int pay) // Class to choose the pay rate depending on if it is a game or app
{
System.out.println("Are you coding an app or a game? ");
appType = console.next();
if(appType == "app")
{
pay = 20;
}
if(appType == "game")
{
pay = 30;
}
else
{
System.out.println("Please enter either 'app' or 'game' ");
}
}// End developer
Developer(int hrsWorked, double tax, int weekPay, int pay) // Class to choose the tax bracket which the developer is in
{
System.out.println("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
weekPay = hrsWorked * pay;
if(weekPay >= 865)
{
tax = 0.4;
}
else
{
tax = 0.21;
}
}// End developer
Developer(int weekPay, int tax) // Gets the pay after tax
{
weekPay = weekPay * tax;
}// End developer
public void display()
{
System.out.println("This display method works");
System.out.println("User: " + name);
}
public static void main(String[] args)
{
Developer myDev = new Developer();
myDev.display();
} // End main
}// End public class developer
I am trying to get this program to ask the user what their name is; if they are developing a game or app and the amount of hours worked on it. With all this information I want to calculate how much the dev earns including tax. I cannot seem to get the display() method to ask the user the questions though and I have no idea what to do. I am hoping somebody out there can help me.
System.in will read input from the command line. You should wrap it with a java.util.Scanner and nextLine like this:
Scanner scanner = new Scanner(System.in);
String user_input = scanner.nextLine();
Be sure to check
scanner.hasNextLine()
before continuing or you'll get an error.
There are few things that could be done differently in your code, so let's break it down:
1.No need to make console static type, you can use:
private Scanner console = new Scanner(System.in);
2.weekPay is of type int, but your tax is double, if you don't want weekPay to be cast to integer, change it to:
double weekPay;
3.Later on, you are calculating weekPay after tax, so let's introduce a variable for that:
double weekPayAfterTax;
4.All these Developer() methods are constructors, and I think you are slightly confused here. Of course, you can have many constructors, but for us, let's keep only the no-params constructor:
public Developer() {
name = "Ciaran";
//you could initialise all the other variables here as well,
//I'll leave it as an exercise for you :)
}
5.Let's create a method that will ask all the questions and set respective variables:
void setData() {
//let's get the name
System.out.print("What's your name: ");
name = console.nextLine();
System.out.print("Are you coding an app or a game? ");
//since we want the user to enter 'app' or 'game'
//we need to loop until we got these
//we can do this by creating endless while loop,
//which we will end when we have correct input
while (true) {
workType = console.next();
if (workType.equals("app")) {
pay = 20.0;
//stop the loop
break;
}
else if (workType.equals("game")) {
pay = 30.0;
//stop the loop
break;
}
else {
System.out.print("Please enter either 'app' or 'game': ");
//back to top
}
}
//ok, we're out the loop, let's get number of hours
System.out.print("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
//calculate weekPay
weekPay = hrsWorked * pay;
if(weekPay >= 865) {
tax = 0.4;
}
else {
tax = 0.21;
}
//calculate pay after tax
weekPayAfterTax = weekPay - weekPay * tax;
}
6.Let's update our display() method to show all the info:
public void display() {
System.out.println("This display method works");
System.out.println("User: " + name);
System.out.println("Work type: " + workType);
System.out.println("Pay: " + pay);
System.out.println("Week pay: " + weekPay);
System.out.println("Week pay after tax: " + weekPayAfterTax);
}
7.In your main method, you can finally create an instance of Developer class and get the data:
public static void main(String[] args) {
Developer myDev = new Developer();
myDev.setData();
myDev.display();
}
The code above can be improved (such as checking if user entered number where it's expected), and your problem can of course be done differently, but here's the start.
Please check out some tutorials to learn the basics, such as this one, or this one. Most of all, experiment and don't let others put you down for not understanding something.