I'm attempting to resolve an issue with a
syntax error on token "}" , { expected.
The program should be able to calculate tax on the amount enter.
import javax.swing.JOptionPane;
public class Accounting {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//declare variables
int accountNumber;
int age=0;
int months=0;
double amount=0.0;
double increasedAmount=0.0;
double incomeTax=0.0;
double newAmount=0.0;
char letter;
double rate=0.03;
double interest=0.0;
double tax=0.40;
double income=0.0;
//get input
accountNumber=Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter the account number (Type 999 to exit "));
age=Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the age "));
amount=Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the amount "));
months=Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the number of months "));
letter=(JOptionPane.showInputDialog(null, "--- --- Main Menu --- --- --- " +
"\n A. Seniors Account " + "\n B. Income Tax " + "\n C. Special Accounts " +
"\n Please select a letter from the menu ( Type X to exit the Menu)")).charAt(0);
//call function
interest=amount*rate*months;
income=amount*tax;
increasedAmount=calcSenior(amount, interest);
incomeTax=calcTax(amount, income );
//display results
JOptionPane.showMessageDialog(null, "The increased amount is " + increasedAmount);
JOptionPane.showMessageDialog(null, "The income tax is " + incomeTax);}
public static void displayHeading()
{
JOptionPane.showMessageDialog(null, "############################# ");
JOptionPane.showMessageDialog(null, "Als Accounting Services ");
JOptionPane.showMessageDialog(null, "Your success is our business. ");
JOptionPane.showMessageDialog(null, "############################# ");
}
// code methods
//case 1:
public static double calcSenior (double amt, double intest)
{
double cost;
cost=amt+intest;
return cost;
}
//case 2:
public static double calcTax(double amot, double inc)
{
double cost1;
cost1=amot+inc;
return cost1;
}
//case 3:
public static void makeDeductions (int age, double amount)
{
double newAmount;
if (age > 40)
{
newAmount=amount-100;
JOptionPane.showMessageDialog(null, "Amount " + amount);
}
else
{
JOptionPane.showMessageDialog(null, "No deductions at this time ");
}
}
} - error
while (accountNumber != 999)
{
Accounting.displayHeading();
switch (accountNumber)
{
case 1:
calcSenior();
break;
case 2:
calcTax();
break;
case 3:
makeDeductions();
break;
default: JOptionPane.showMessageDialog(null, "Bye! Have a nice day ");
}//end switch
}
}
}
The problem is, your while loop is out side the body of the class definition...
public class Accounting {
//...
} // End of class..
while...
This is illegal in Java. You must place the while loop within a executional context, such as a method or static initialiser block...
Your code's laid out unusually. You've got a piece of main towards the top and towards the bottom.
Here's the quick (compiling) fix:
Remove the curly brace at the end of JOptionPane.showMessageDialog(null, "The income tax is " + incomeTax);}.
Move the while loop to after that line.
Fix the method calls from within your while loop so that the parameters that they're using are correct.
Admittedly, this says nothing about the correctness of your program, but only to the point that it would be much, much closer to compiling.
At the end of the makeDeductions (int age, double amount) method you have this:
}
} - error
That first } closes the method body, and the following } closes the class body, so that leaves you with a - error outside class body, illegal syntax in Java. Also, there's a while after that, also illegal outside method body (and of course illegal outside class body)
If you delete both of those lines (numbers 100 and 101, copypasting your code) that problem is resolved (though that - error probably does something, even if I can't figure out what, so be careful when deleting it). But there's one more:
In what now would be part of the makeDeductions (int age, double amount) method body you now have references to variable accountNumber which is declared in the main(String[] args) method and thus doesn't exist in this context
You call for calcSenior() when that overload doesn't exist, the only one you have declared is calcSenior (double amt, double intest) (notice the two parameters)
Same for calcTax(), you have only declared calcTax(double amot, double inc)
And yet the same for makeDeductions (), with only makeDeductions (int age, double amount) having been declared. Careful here though, remember that I'm asuming you deleted those likes I specified at the beginning, so this code is INSIDE THE makeDeductions (int age, double amount) BODY, meaning that if you call makeDeductions with int and double parameters, you are in fact calling this very method, which can cause an infinite loop if you don't have a stopping condition to avoid the method to call itself infinitely (causing a stack overflow)
And that's all I could find. I hope this is useful to you :)
Maybe you are using Eclipse as IDE and trying to run code that doesn't compile. Check your Problems view in Eclipse, and fix the compilation errors before executing the application.
Related
I'm to create a banking program. I should be able to deposit, withdrawl, view balance, and then of course exit.
My problem is we have not gone over arrays yet and that is what I'm trying to use. When I initialize the array with [0] as it's only one type of data at a time, i recieve an:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
So my question is how can I be able to do this while modififying the balance until the user exits. I'm a bit stuck...
Any help is appreciated and I apoligize in advance for the messy code.
Thankyou everyone for the help. I did put: double[] balance = new double[1];
But now I am returning to the problem that I can't continue modifying the array with more deposits, and withdrawls. I initializes it back to 0.0.
Could anyone point me in the right direction?
Main class:
public class Project3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Introduction();
Banking obj1 = new Banking();
}
public static void Introduction()
{
//this message tells the user exactly what this program does.
JOptionPane.showMessageDialog(null,
"This is a small conversion program which allows you to do "
+ "\nDeposit "
+ "\nWithdrawl."
+ "\nView Balance."
+ "\nExit",
"Conversion Calculator",
JOptionPane.INFORMATION_MESSAGE);
}
}
Class:
public class Banking
{
double deposit;
double newbalance;
double[] balance = new double[0];
public Banking()
{
Menu();
}
public void Menu()
{
JDialog.setDefaultLookAndFeelDecorated(true);
Object[] selectionValues = { "Deposit", "Withdrawl"};
String initialSelection = "Deposit";
Object selection = JOptionPane.showInputDialog(null, "Would you like to "
+ "do today?",
"Home Banking Selection Screen", JOptionPane.PLAIN_MESSAGE, null, selectionValues, initialSelection);
// If statements used to call the method selected
if (selection == "Deposit")
Deposit();
if (selection == "Withdrawl")
Withdrawl();
}
public void Deposit()
{
balance[0] = Double.parseDouble(JOptionPane.showInputDialog(null,
"Please enter the total number of degrees in Fahrenheit to be Converted into Celcius? and press 'Ok'",
"Deposit",
JOptionPane.PLAIN_MESSAGE));
JOptionPane.showMessageDialog(null,
"You doposited $ " +balance+ "\n You now have $" ,
"The End",
JOptionPane.PLAIN_MESSAGE);
JDialog.setDefaultLookAndFeelDecorated(true);
Object[] selectionValues = { "Continue with more transactions", "Exit"};
String initialSelection = "Deposit";
Object selection = JOptionPane.showInputDialog(null, "Would you like to "
+ "do today?",
"Home Banking Selection Screen", JOptionPane.PLAIN_MESSAGE, null, selectionValues, initialSelection);
// If statements used to call the method selected
if (selection == "Continue witl more transactions")
Menu();
if (selection == "Exit")
Exit();
}
public void Withdrawl()
{
JOptionPane.showMessageDialog(null,
" Will be Withdrawl!", //Message to tell the user the program has ended
"2",
JOptionPane.PLAIN_MESSAGE);
}
public void Exit()
{
JOptionPane.showMessageDialog(null,
" Thank you and have a great day!", //Message to tell the user the program has ended
"The End",
JOptionPane.PLAIN_MESSAGE);
}
}
double[] balance = new double[0]; Does not create an array of 0
's.
For example: Your array does not look like this:
[0,0,0,0,0,0,0,0,0]
Instead your array looks like this:
[ ]
Saying Object obj = new Object[x] creates an array that is of length x. However, even then the items in the array are not initialized. You have to go manually set each one to 0.
You have a double array of size 0:
double[] balance = new double[0];
And then you are accessing it's first (non-existing element):
balance[0] = Double.parseDouble(JOptionPane.showInputDialog(null,
"Please enter the total number of degrees in Fahrenheit to be Converted into Celcius? and press 'Ok'",
"Deposit",
JOptionPane.PLAIN_MESSAGE));
That's why the ArrayIndexOutOfBoundsException: 0 is thrown.
Just use double[] balance = new double[1];
Here is size of array you are going to create ^
Every element will be initialised with 0.0 by default.
UPD: actually, you might want to try adding some checking to ensure that the user you are touching actually exists and the balance is set properly.
You can just initialize your array this way:
double[] balance = {};
At this point the size of the array will be zero.
However, based of your question, I do not think you need and array.
Simply declare balance this way:
double balance = 0.00d;
When you deposit:
balance = balance + depositAmount;
when you withdraw:
balance = balance - withdrawlAmount;
I am new to using java and am having some issues in my java class right now and will be needing help with my specific code. I try to look at others questions on here all the time but it's never exactly what I need. Here are my directions:
Create a Java file called CompoundInterestYourLastName. Write a method called computeBalance() that computes the balance of a bank account with a given initial balance and interest rate, after a given number of years. Assume interest is compounded yearly.
Use a loop to control the iterations through the years in your method.
Your method should return a double value.
In your main method, run the following tests to verify your method is working correctly.
System.out.printf("Your total is $%.2f", computeBalance(1000, .045, 3));
// should return $1141.17
I am using eclipse and my only current error is in the comments. I also want some general tips and let me know if my logic is wrong. It probably is. :D
Here is what I have currently although I have been trying different things:
import java.util.Scanner;
import java.lang.Math;
public class CompoundInterestTidwell {
public static void main(String[] args) {
double compInt = computeBalance(1000, 0.045, 3);
System.out.printf("Your new balance is $%.2f", compInt);
}
// Getting arror for line of code below.
// Error: This method must return a result of type double
public static double computeBalance(int P, double r, int t) {
// Formula for compounding interest
// A = P(1+(r/n))^(n(t))
// The examples to check my math had rate already divided by 100 so I left out r/n.
for(int c = 0; c <= t; c++ ) {
// deleted 'n' from equation because it need to equal 1 anyways.
double compInt = Math.pow(P*(1+r), t);
if (c < t) {
c++;
return compInt;
}
}
}
}
Thanks.
Your function computeBalance doesn't guarantee to return a value, because the only return statement is in an if clause, within a loop (making it two conditions deep).
This is a thing the compiler is warning you about. Basically it scans your code and makes sure that a function declared as double will actually return a valid value of type double and so on.
If you add a return statement at the end of the body in the function (or throw an error) it should compile.
I am not exactly sure what your function does in technical terms, but I've rewritten it so it should return the same value, but should now actually compile.
public static double computeBalance(int P, double r, int t) {
// Formula for compounding interest
// A = P(1+(r/n))^(n(t))
// The examples to check my math had rate already divided by 100 so I left out r/n.
double compInt = 0; // Declare compInt outside the loop.
for(int c = 0; c <= t; c++ ) {
// deleted 'n' from equation because it need to equal 1 anyways.
compInt = Math.pow(P*(1+r), t);
if (c < t) {
c++;
break; // Break instead of return, will immediately
// go to the return statement outside the loop.
}
}
return compInt; // Moved the return statement to outside the loop so
// the function always will return a double.
}
This question already has answers here:
How to get the user input in Java?
(29 answers)
Closed 6 years ago.
So I made a class that is supposed to calculate the number of beers needed to become intoxicated. My class receives User Input for the name of the beer, the alcohol content, and then the user's weight to make the calculation.
Here's my whole Beer class
public class Beer {
private String name;
private double alcoholContent;
//Default apple values (Constructors)
public Beer()
{
this.name = "";
this.alcoholContent = 0.0;
}
//Accessors
public String getName()
{
return this.name;
}
public double getAlcoholContent()
{
return this.alcoholContent;
}
//Mutators
public void setName (String aName)
{
this.name = aName;
}
public void setAlcoholContent (double aAlcoholContent)
{
if (aAlcoholContent < 0 || aAlcoholContent > 1)
{
System.out.println("That is an invalid alcohol content");
return;
}
this.alcoholContent = aAlcoholContent;
}
//Methods
public double Intoxicated (double aWeight)
{
double numberOfDrinks = (0.08 + 0.015) * aWeight / (12 * 7.5 * this.alcoholContent);
return numberOfDrinks;
}
This is specifically my intoxicatedmethod in the class (I think it's right):
public double Intoxicated (double aWeight)
{
double numberOfDrinks = (0.08 + 0.015) * aWeight / (12 * 7.5 * this.alcoholContent);
return numberOfDrinks;
}
This is what the output window is supposed to look like, receiving User Input for the weight and then performing the calculation to see how many beers it would take based on the user's input when previously defining two beers to be considered intoxicated:
What’s the weight of the person consuming said beverages?
185
It would take 3.166 "firstBeerName" beers to become intoxicated.
It would take 1.979 "secondBeerName" beers to become intoxicated.
The intoxicated formula was given to me, I don't know how to properly set up my class testing main method file which calls this class to reflect that output.
You need to write a testing class, that contains a main method. In the main method you can create several Beer-Objects.
By iterating over your Beers, you can get the wanted results.
Look here to get information about how to set up a main method.
Create an Array of Beer-Objects in that method with different alcohol content
Get the user input for the weight and then
Iterate over your Array, call intoxicated() and print the results
You are going to want to create a main method which does the following:
1) Prints the prompt for the beer values (name and % alcohol)
2) Takes in user input for those beer values
3) Prints the prompt for the user's weight
4) Takes in the user input for the weight
5) Calculates and prints the result
For printing prompts, you will most likely want to use System.out.println("Some prompt here!");
For taking input, you will most likely want to use a Scanner. You can search around on this website and others, as well as read the documentation, for how to take input with using that class.
Here is an example of a main method:
public static void main(String[] args) {
Beer blueMoon = new Beer("Blue Moon", 5.4);
Beer hoegaarden = new Beer("Hoegaarden", 4.9);
System.out.println("Enter your weight: ");
Scanner input = new Scanner();
Double weight = input.nextLine();
double value = beer1.Intoxicated(weight);
System.out.println("It would take " + value + " of " + blueMoon.getName() + " to become intoxicated.");
}
I would suggest renaming your Intoxicated method to intoxicated, as method names are generally camelCased in Java.
I am not going to give you the exact code because this seems like homework and I already graduated, but that should be enough to get you started. My advice would be to search around for any specific questions you come up with.
You can write a main method like this:
public static void main(String [ ] args)
{
Beer beer1 = new Beer().
beer1.setName("firstBeerName");
beer1.setAlcoholContent(3.166);
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("What’s the weight of the person consuming said beverages?");
double weight = reader.nextDouble();
double answer = beer1.Intoxicated(weight);
System.out.println("It would take "+answer+" "+beer1.getName()+" beers to become intoxicated.")
// similar for beer2
}
I would encourage you to throw IllegalArgumentException when checking condition in setter:
public void setAlcoholContent(double aAlcoholContent) {
if (aAlcoholContent < 0 || aAlcoholContent > 1) {
throw new IllegalArgumentException("Alcohol content can't be more than 1 or less than 0");
}
this.alcoholContent = aAlcoholContent;
}
And for your question you can test it like this:
public static void main(String[] args) {
List<Beer> beers = new ArrayList<>();
beers.add(new Beer("firstBeerName", 0.04));
beers.add(new Beer("secondBeerName", 0.06));
Scanner reader = new Scanner(System.in);
System.out.println("What’s the weight of the person consuming said beverages?");
double weight = reader.nextDouble();
DecimalFormat decimalFormat = new DecimalFormat("0.000");
for(Beer beer : beers){
System.out.println("It would take " + decimalFormat.format(beer.Intoxicated(weight)) + " " + beer.getName() +" beers to become intoxicated.");
}
}
Also you can use loop for creating new beers, just ask user for amount of beers that he can obtain result for, and then create for loop.
I'm starting to get blind looking at my code and my brain is about to overheat. I'm new when it comes to programming.
public class RecyclingSystem {
public static void main(String[] args) {
System.out.println("Please put in a valid bottle");
Scanner sc = new Scanner(System.in);
while ( sc.nextInt() != -1) {
if (sc.nextInt(char a) = getaBottle);
int bottleAcount++;
} else if { (sc.nextInt(char b) = getbBottle);
int bottleBcount++;
} else if { (sc.nextInt(char c) = getcBottle);
int bottleCcount++;
} else { throw new EmptyStackException();
System.out.println("Bottle not recognized");
}
System.out.println("The total number of bottles is " + totalBottlecount);
System.out.println();
System.out.println("The total amount returned is " + sumOfBottles );
}
sc.close();
}
}}
public class Bottle {
private static final double A_BOTTLE = 1.0;
/**
* #return the aBottle
*/
public static double getaBottle() {
return A_BOTTLE;
}
/**
* #return the bBottle
*/
public static double getbBottle() {
return B_BOTTLE;
}
/**
* #return the cBottle
*/
public static double getcBottle() {
return C_BOTTLE;
}
private static final double B_BOTTLE = 1.5;
private static final double C_BOTTLE = 3.0;
}
public class EmptyStackException extends Exception {
}
public class bottleCount {
int bottleAcount = 0;
int bottleBcount = 0;
int bottleCcount = 0;
int totalBottleCount = bottleAcount + bottleBcount + bottleCcount;
}
I have seperate classes for the getbottle, totalBottlecount and bottlecount variables.
I want to make a user-input based recycling system simulator, if that makes any sense, with 3 different types of bottles, which are assigned different values, a total bottle count and the sum of the values of the 3 bottle types combined.
I get several compiler errors and I have spend HOURS trying to resolve them all, but every time I do, new errors occur and now I get a "coders-block".
I get asked to delete the ++ tokens, the compiler cannot resolve my variables and syntax errors. I would really appreciate some insight, since I'm only ~3weeks into java programming.
UPDATED: Compiler errors exact copy pasta
Multiple markers at this line
- Syntax error, insert ")" to complete Expression
- Duplicate method nextInt(char) in type RecyclingSystem
- Syntax error, insert "}" to complete Block
- Syntax error, insert "AssignmentOperator Expression" to complete Assignment
- Return type for the method is missing
- Syntax error on tokens, delete these tokens
- The left-hand side of an assignment must be a variable
- Syntax error, insert "AssignmentOperator Expression" to complete Expression
- The left-hand side of an assignment must be a variable
- Syntax error, insert ";" to complete BlockStatements
- Syntax error on tokens, delete these tokens
- Syntax error on token ")", { expected after this token
- Syntax error, insert ";" to complete Statement
int bottleAcount++;
In java you need to declare the local variable like
type name = intial value;
then do any operation on that like increament or decrement.
In youe case declar the variable before while loop with zero as intial value like
int bottleAcount = 0;
then inside while increament it by 1, like bottleAcount++;
or
bottleAcount += 1;
So... If this is all the code there are many problems and what can I recommend in the beginning - go back to some basic Java programming course.
Let's look at one of the first lines:
if (sc.nextInt(char a) = getaBottle);
Firstly, it's a condition, and you are assigning the value of a getaBottle to the sc.nextInt(char a).
Secondly, nextInt(char a) looks like method declaring, not like a method call.
Thirdly, getaBottle is never declared before
Fourthly, you have a getaBottle() method in a Bottle class, which you probably want to use instead of getaBottle which is (should) be a variable
...etc., etc.
This code is not even valid Java code. It's hard to help you somehow in that problem, you just need to learn a bit more, which I encourage you to do.
Good luck and in case of any specific question - come and ask!
else if { (sc.nextInt(char b) = getbBottle);
int bottleBcount++;
}
Syntax is totally wrong for if.Also condition is checked using == not = It should be :
else if (sc.nextInt(char b) == getbBottle);
int bottleBcount++;
Also you cant do int bottleBcount++. Its meaningless. Since you already declared bottleBcount in another class, you have to access it using the object of that class. Before that change the declaration in the class from int bottleAcount = 0; to public int bottleAcount = 0; . Do this for all bottles.
Now you can use it as :
public static void main(String[] args) {
System.out.println("Please put in a valid bottle");
bottleCount counter = new bottleCount();
Scanner sc = new Scanner(System.in);
while ( sc.nextInt() != -1) {
if (sc.nextInt(char a) == getaBottle);
counter.bottleAcount++;
} else if (sc.nextInt(char b) == getbBottle);
counter.bottleBcount++;
else if (sc.nextInt(char c) == getcBottle);
counter.bottleCcount++;
else { throw new EmptyStackException();
System.out.println("Bottle not recognized");
}
System.out.println("The total number of bottles is " + totalBottlecount);
System.out.println();
System.out.println("The total amount returned is " + sumOfBottles );
}
sc.close();
}
Also the statement int totalBottleCount = bottleAcount + bottleBcount + bottleCcount; doesnt make sense. It won't work as you wanted it to. You need to write a function to do this addition and then call it. Or if you want this to happen just once ( which I doubt) , you can put it in a constructor.
I suggest you brush up on class and variable declaration concepts before proceeding
You just have problem in this:
else {
throw new EmptyStackException();
System.out.println("Bottle not recognized");
}
Check the proper syntax and error will be resolved.
I have been doing a project for my java class. For the project I have to have the user enter input and calculate their body mass index and body surface area the program is supposed to remain running until the user enters a "q". I cannot get my program to stop running when a "q" is put in it just crashes. Also I am very new to java and programming in general so I would appreciate any help. My code is as follows.
Thanks : )
public static void main(String[] args) {
//Scanner
Scanner stdIn = new Scanner(System.in);
//Variables
final double METERS_TO_CM = 100; // The constant to convert meters to centimeters
final double BSA_CONSTANT = 3600; // The constant to divide by for bsa
double bmi; // Body Mass Index
String weight; // Weight in kilograms
String height; // Height in meters
String classification; // Classifies the user into BMI categories
double bsa; // Body surface area
do {
System.out.print("Welcome to the BMI and BSA Calculator to begin enter weight in kilograms.");
weight = stdIn.next();
System.out.print("Enter height in meters: ");
height = stdIn.next();
double height2 = Double.parseDouble(height);
double weight2 = Double.parseDouble(weight);
bmi = weight2/(height2*height2);
if (bmi < 18.5)
{
classification = "Underweight";
}
else if (bmi < 25)
{
classification = "Normal";
}
else if (bmi < 30)
{
classification = "Overweight";
}
else
{
classification = "Obese";
}
System.out.println("Your classification is: " + classification);
bsa = Math.sqrt(((height2*METERS_TO_CM)*weight2)/BSA_CONSTANT);
System.out.printf("BMI: %.1f\n", bmi);
System.out.printf("BSA: %.2f\n", bsa);
System.out.println("Hit 'q' to quit");
} while (stdIn.nextLine().compareToIgnoreCase("q")==0);
}
}
I would guess that your "q" input is written in weight and therefore you try to parse it to a Double, which throws an unhandled Exception and stops the execution.
You should handle this Exception and make the system break the while loop when triggering it.
You're grabbing the entire line for your while loop condition.
Try just grabbing the next() instead of nextLine().
Also, you're looking at while it DOES equal 0 ... meaning equal. I'd change that to != instead. You want to continue looping while the next token is NOT Q.
Let's make a structural change to make this easier for you to do.
We are going to change it so that your do-while loop always is running, until you explicitly tell it to stop.
Your current while is:
while(stdIn.nextLine().compareToIgnoreCase("q")==0);
Which works ok, but we have a more simple way to do this. Have you heard of the break statement?
I would suggest you use break. This statement will 'break' you out of the while loop; basically it tells the program to stop looping when it is called. This will be a bit easier to follow than your somewhat confusing do-while.
do {
//Your Do code goes here, as before
...
//
//Your newly added break statement will go here.
//This breaks out of the while loop when your inputed 'choice' value is
//equal to the string of "q" (for quit)
if (Choice.equals("q"))){
break;
//When break is called nothing else in the loop will run
}
//Same thing but with the string of "quit"
if (Choice.equals("quit"){
break;
}
}while (true);
//Your new while statement is simply while(true) which will run until break is called
Hopefully that is helpful to you.
Don't actually use a loop. Since it's impractical someone would ever max the call stack out by answering too many questions, just make the whole operation a function. At the end of the function, call itself if the result isn't Q.
its simple use this
while (true)
{
Console.WriteLine("Start processing");
//processing code here
Console.WriteLine("finish processing");
Console.WriteLine("start again? y/n?");
if (Console.ReadLine().Equals("n"))
break;
}