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.
Related
How do i pass a specific content of an index of an arraylist to a method? (i'm not sure of the correct terms)
This is what i'm trying to achieve:
Get user input for the amount to withdraw from the first account, then print the balance. Repeat
the same for deposit.
This is my class code:
import java.util.Date;
public class Account2 {
private int id = 0;
private double balance = 0;
private static double annualInterestRate = 0;
private Date dateCreated;
public Account2() {
id = 0;
balance = 0;
}
public Account2(int id, double balance) {
this.id = id;
this.balance = balance;
}
// getters and setters (omitted for brevity)
public double withdraw(int amount) {
return balance - amount;
}
public double deposit(int amount) {
return balance + amount;
}
}
This is the Test class:
import java.util.ArrayList;
import java.util.Scanner;
public class TestAccount2 {
public static void main(String[] args) {
//Account2 acc = new Account2();
Account2.setannualInterestRate(4.5);
//Creates an ArrayList of 3 Account objects
ArrayList<Account2> list = new ArrayList<Account2>();
for(int i=1; i<4; i++) {
//USE ARRAYLIST SYNTAX
list.add(new Account2(i+100, i*10000 ));
}
//print all the content of ArrayList
for(Account2 auto : list) {
System.out.println(temp);
}
System.out.println("Enter the amount you'd like to withdraw: ");
Scanner input = new Scanner(System.in);
double amount = amount.nextDouble;
// Get user input for the amount to withdraw from the first account, then print the balance.
// Repeat the same for deposit
}
}
This is where i'm stuck:
System.out.println("Enter the amount you'd like to withdraw: ");
Scanner input = new Scanner(System.in);
double amount = amount.nextDouble;
// Get user input for the amount to withdraw from the first account, then print the balance.
// Repeat the same for deposit
This is the method i'm trying to pass the index of arraylist into:
public double withdraw(int amount) {
return balance - amount;
}
thank u.
You need to invoke those methods specifying the instance of the account you want to alter. For example, if you want to withdraw from the first account of the ArrayList, you'll write something like:
list.get(0).withdraw(amount);
You can do the same for the deposit method.
The code I wrote compiles well, but there are certain values that do not calculate. The rate and hours value, tuition and .08 do not calculate. Maybe my code is wrong or something. I am still new to java so i am trying my best. Here is my code:
import java.io.*;
import java.text.DecimalFormat;
import java.util.Scanner;
public class Tuition
{
static double fees;
static double rate;
static double tuition;
private static Scanner sc;
public static void main(String[] args) throws IOException
{
//declare variables
int hours;
//call methods
displayWelcome();
hours = getHours();
rate = getRate(hours);
tuition = calcTuition(hours, rate);
fees = calcFees(tuition);
}
public static void displayWelcome()
{
//welcome statement
System.out.println("Welcome to school that offers distance learning courses");
}
public static int getHours()
{
//declare method variables
int hours = 0;
//a user must enter a string value
System.out.println("Enter total number of hours");
sc = new Scanner(System.in);
try
{
hours = sc.nextInt();
}
catch(NumberFormatException e)
{
System.out.print("Incorrect number");
}
return hours;
}
public static double getRate(int hours)
{
if (hours > 15)
{
System.out.println("rate per credit hour is 44.50");
}
else
{
System.out.println("rate per credit hour is 50.00");
}
return rate;
}
public static double calcTuition(int hours, double rate)
{
tuition =(double)rate * hours;
System.out.print("tuition is" + (tuition));
return tuition;
}
public static double calcFees(double tuition)
{
fees =(double)tuition * .08;
System.out.print("fees are" + (fees));
return fees;
}
public static void displayToatal(double total)
{
DecimalFormat twoDigits = new DecimalFormat("$#,000.00");
System.out.println("the total value is"+ twoDigits.format(tuition + fees));
}
}
In calcTuition()
tuition =(double)rate * hours;
should be
tuition =rate * (double)hours;
: )
You aren't setting the rate. You need a line of code that looks like "rate = x;". You only have println's in the getRate method, but you don't actually set the variable to equal anything.
I am having some issues with the following syntax.
I am currently learning Java and have been going through a past exam paper to help build my knowledge of Java.
Here is the question:
Write a class Account that has instance variables for the account number and current balance of the account. Implement a constructor and methods getAccountNumber(), getBalance(), debit(double amount) and credit(double amount). In your implementations of debit and credit, check that the specified amount is positive and that an overdraft would not be caused in the debit method. Return false in these cases. Otherwise, update the balance.
I have attempted to do this HOWEVER, I have not implemented the boolean functions for debit and credit methods. I just wanted to build the program first and attempt to get it working. I was going to look at this after as I was not sure how to return true or false whilst also trying to return an amount from the said methods.
Please forgive any errors in my code as I am still learning Java.
I can run my code, but when I enter deposit it does not seem to work correctly and I would appreciate any pointers here please.
Here is my code:
import java.util.*;
public class Account {
private int accountNumber;
private static double currentBalance;
private static double debit;
// ***** CONSTRUCTOR *****//
public Account(double currentBalance, int accountNumber) {
accountNumber = 12345;
currentBalance = 10000.00;
}
public int getAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
return accountNumber;
}
public double getcurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
return currentBalance;
}
public static double debit(double currentBalance, double amount) {
currentBalance -= amount;
return currentBalance;
}
public static double credit(double currentBalance, double amount) {
currentBalance += amount;
return currentBalance;
}
public static void main(String [] args){
String withdraw = "Withdraw";
String deposit = "Deposit";
double amount;
Scanner in = new Scanner(System.in);
System.out.println("Are you withdrawing or depositing? ");
String userInput = in.nextLine();
if(userInput == withdraw)
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
if(amount > currentBalance)
System.out.println("You have exceeded your amount.");
debit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
if (userInput == deposit)
System.out.println("Enter amount to deposit: ");
amount = in.nextDouble();
credit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
}
Again please forgive any errors in my code. I am still learning its syntax.
In the if-statement if(userInput == withdraw) you are attempting to compare String objects.
In Java to compare String objects the equals method is used instead of the comparison operator ==
if(userInput.equals(withdraw))
There are several instances in the code that compares String objects using == change these to use equals.
Also when using conditional blocks it is best to surround the block with braces {}
if(true){
}
You don't use brackets so only the first line after your if-statement gets executed. Also, String's should be compared using .equals(otherString). Like this:
if(userInput.equals(withdraw))
System.out.println("Enter amount to withdraw: "); //Only executed if userInput == withdraw
amount = in.nextDouble(); //Always executed
if(userInput.equals(withdraw)) {
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
//All executed
}
Do this:
if(userInput.equals(withdraw)) {
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
if(amount > currentBalance)
System.out.println("You have exceeded your amount.");
debit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
if (userInput.equals(deposit)) {
System.out.println("Enter amount to deposit: ");
amount = in.nextDouble();
credit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
Note that if your amount to withdraw exceeds your current balance, you will get a 'warning message' but your withdrawal will continue. Thus you'll end up with a negative sum of money. If you don't want to do this, you have to change it accordingly. But, this way it shows how the use of brackets (or not using them) has different effects.
if (userInput == deposit)
should be
if (userInput.equals(deposit))
Same for withdrawal.
On these methods:
public static double debit(double currentBalance, double amount) {
currentBalance -= amount;
return currentBalance;
}
public static double credit(double currentBalance, double amount) {
currentBalance += amount;
return currentBalance;
}
The inputs to the functions really shouldn't include the current balance, the object already knows what the current balance is (its being held in the objects currentBalance field, which as has been pointed out shouldn't be static).
Imagine a real cash machine that behaved like this:
Whats my current balance:
£100
CreditAccount("I promise my current balance is £1 Million, it really is", £10):
Balance:£1,000,010
Edit: Include code to behave like this
import java.util.*;
public class Account {
private int accountNumber;
private double currentBalance; //balance kept track of internally
// ***** CONSTRUCTOR *****//
public Account(int accountNumber, double currentBalance) {
this.accountNumber = accountNumber;
this.currentBalance = currentBalance;
}
public int getAccountNumber() {
return accountNumber;
}
public double getcurrentBalance() {
return currentBalance;
}
public boolean debit(double amount) {
//we just refer to the objects fields and they are changed
if (currentBalance<amount){
return false; //transaction rejected
}else{
currentBalance -= amount;
return true;
//transaction approaved and occured
}
//Note how I directly change currentBalance, there is no need to have it as either an input or an output
}
public void credit( double amount) {
//credits will always go through, no need for return boolean
currentBalance += amount;
//Note how I directly change currentBalance, there is no need to have it as either an input or an output
}
public static void main(String [] args){
Account acc=new Account(1234,1000);
acc.credit(100);
System.out.println("Current ballance is " + acc.getcurrentBalance());
boolean success=acc.debit(900); //there is enough funds, will succeed
System.out.println("Current ballance is " + acc.getcurrentBalance());
System.out.println("Transaction succeeded: " + success);
success=acc.debit(900); //will fail as not enough funds
System.out.println("Current ballance is " + acc.getcurrentBalance());
System.out.println("Transaction succeeded: " + success);
}
}
I've not bothered using the typed input because you seem to have the hang of that
Without '{' and '}' the first line after an if statement only gets executed as part of that statement. Also, your if (userInput == deposit) block isn't correctly indented, it shouldn't be under the if (userInput == withdraw). And string comparisons should be done using userInput.equals(withdraw)
For the debit and credit methods:
public static boolean debit(double currentBalance, double amount) {
currentBalance -= amount;
if<currentBalance < 0){
return false
}
return true;
}
public static boolean credit(double currentBalance, double amount) {
currentBalance += amount;
if<currentBalance > 0){
return false
}
return true;
}
Now I think I have the boolean values mixed up. The description is a little bit unclear on what to return for each method.
Use equals() method instead == which compares the equality of Objetcs rather values
import java.util.*;
public class Account{
private int accountNumber;
private static double currentBalance;
private static double debit;
// ***** CONSTRUCTOR *****//
public Account(double currentBalance, int accountNumber) {
accountNumber = 12345;
currentBalance = 10000.00;
}
public int getAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
return accountNumber;
}
public double getcurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
return currentBalance;
}
public static double debit(double currentBalance, double amount) {
currentBalance -= amount;
return currentBalance;
}
public static double credit(double currentBalance, double amount) {
currentBalance += amount;
return currentBalance;
}
public static void main(String [] args){
String withdraw = "Withdraw";
String deposit = "Deposit";
double amount;
Scanner in = new Scanner(System.in);
System.out.println("Are you withdrawing or depositing? ");
String userInput = in.nextLine();
if(userInput.equals(withdraw))
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
if(amount > currentBalance)
System.out.println("You have exceeded your amount.");
debit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
if (userInput .equals(deposit))
System.out.println("Enter amount to deposit: ");
amount = in.nextDouble();
credit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
}
For my Java class, we need to make a bank account that has the methods of withdrawing, depositing money, and displaying current balance. In the Tester class, I want to make it ask for the name, the balance, then allow you to choose 1, 2, or 3. Then it repeats the option you choose until you say type "n". The problem is that running this code causes it to say after you deposit money "You deposited (amount of money deposited) in the account (name of account). Your new balance is (this)." The part where it says "this" is the exact same of the amount of money deposited. In other words, it doesn't add it, it just makes the new balance the same as the deposit, regardless of how much was in before. Any help? Thanks.
import java.io.*;
import java.util.*;
public class BankAccount
{
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
public void deposit(double d)
{
balance += d;
}
public void withdraw(double w)
{
balance -= w;
}
public String nickname()
{
System.out.print("Enter a new name: ");
Scanner kbIn = new Scanner(System.in);
String n = kbIn.nextLine();
return n;
}
double balance;
String name;
}
And the tester class:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbInLine = new Scanner(System.in);
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = kbInLine.nextLine();
System.out.print("Please enter balance: $");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(balance, name);
String proceed = "y";
while(proceed.equalsIgnoreCase("y"))
{
System.out.println("\nPlease pick a number. Would you like to...\n\t 1. Deposit\n\t 2. Withdraw\n\t 3. Print Balance\n");
int choice = kbIn.nextInt();
switch(choice)
{
case 1:
System.out.print("How much would you like to deposit?\n\t$");
double deposit = kbIn.nextDouble();
myAccount.deposit(deposit);
System.out.println("You have deposited $" + deposit + " into the account of " + name + ". The new balance is: " + myAccount.balance);
break;
case 2:
System.out.print("How much would you like to withdraw?\n\t$");
double withdraw = kbIn.nextDouble();
if(myAccount.balance - withdraw > 0)
{
myAccount.withdraw(withdraw);
System.out.println("You have withdrawn $" + withdraw + " from the account of " + name + ". The new balance is: " + myAccount.balance);
}
else
{
System.out.println("Sorry, you have insufficient funds for this operation. Your existing balance is $" + myAccount.balance);
}
break;
case 3:
System.out.print("The balance in the account of " + name + " is $" + myAccount.balance);
break;
}
System.out.print("\nWould you like to do another transaction? (Y/N)");
proceed = kbIn.next();
}
System.out.println("\nThank you for banking with us. Have a good day!");
}
}
What's really wierd is that I did a project before this one (it's actually a simplified version) where it deposits and then withdraws a predetermined, coded amount, then outputs the new bank balance, and it does it fine. But the code for BankBalance is the same. Here's the code for those.
BankAccount class is:
public class BankAccount
{
public BankAccount(String nm, double amt) // Constructor
{
name = nm;
balance = amt;
}
public void deposit(double d) // Sets up deposit object as balance += d
{
balance += d;
}
public void withdraw(double w) // Sets up withdraw object as balance -= w
{
balance -= w;
}
public double balance;
public String name;
}
And the Tester class is:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name:");
String name = kbIn.nextLine();
System.out.print("Enter the balance:");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(name, balance);
myAccount.deposit(505.22);
System.out.println(myAccount.balance);
myAccount.withdraw(100.00);
System.out.println("The " + myAccount.name + " account balance is, $" + myAccount.balance);
}
}
You're not actually initialising your balance member variable here:
public BankAccount(double b, String n)
{
double balance = b;
This creates a new local variable called balance, to which you assign the value of b. The member variable balance will remain 0 (the default) after this constructor is run.
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
--->
public BankAccount(double b, String n)
{
this.balance = b;
this.name = n;
}
Or you can declare balance as static (data class field), and the methods that use this variable as static too.
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).