"Exception in thread "main" java.lang.Error - java

I don't know why it says I have an error but this is the exact error message "Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at org.com1027.cw1.rc00182.Salary.main(Salary.java:8)"
Here is the code:
package org.com1027.cw1.rc00182;
public class Salary {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public double salary; //this is the field I have created within the Salary class with type double
public Salary() { //this is the default constructor
}
public double getsalary() { //Here is the getter for salary class with a return
return salary;
}
public double setsalary() { //Here is setter for the salary class with a return
return salary;
}
public int calculateTax()
{
int salary = 16475; //here I am stating the salary using an integer because it is number related
int taxSalary = 7035; //here I am declaring the result so I can use it later
int personalAllowance = 9440; //here I am declaring the personal allowance is equal to 9440
int taxThreshold = 32010; //this is the tax threshold value I have put in for later use when continuing the if statement
int lowerTax = 20; //this is the lower tax and because the value holds a decimal I have used a type double. this will come to use when continuing the if statement calculating the tax
int higherTax = 40; //this is the higher tax and again used a type double due to the use of a number holding a decimal
// above are the 6 variables I have created for the if statement below
if (salary > personalAllowance){ //here I am saying if the salary is more than 9440 (personal allowance) then..
taxSalary = salary-personalAllowance; //this is saying the salary (16475) minus personal allowance gives the result (7035) which is the taxable salary
taxSalary = 0;
}
if (taxSalary < taxThreshold) {
taxSalary = taxSalary * lowerTax;
}
else {
taxSalary = (taxSalary - taxThreshold) * higherTax + taxThreshold;
}
}
Also says I have an error on the brace right at the bottom saying I need to put another one in there but I cant find where it is missing from.

Is your setSalary() supposed not to do anything or is there additional code, which you forgot to include?
In general a setter should be as follows, though obviously you could make it return a value or a boolean:
public void setsalary(double salary) { // setSalary would have been more readable
this.salary = salary;
}
EDIT: As others pointed out, you are missing a class bracket. I have provided a possible location for it.
else {
taxSalary = (taxSalary - taxThreshold) * higherTax + taxThreshold;
}
return taxSalary; // <--- missing a return statement here
}
} // <--- Missing a class closing bracket here.

Your code contains bugs. You forced the compiler to compile it. However it cannot. So when you try to run it. It will stop and say that the compiled Java file is not valid. I'm not going to search for your errors in the code. Use an IDE like Eclipse, it will tell you where your errors are and what the problem is.

Related

Java method taking 0 arguments and returning a double using if else statements with strings

I am trying to write a method which does not take any arguments and then returns a double variable. It is a postcode identifier so when a cost code is entered certain post codes need to return a double.
In my example below i need post codes that start with either "GH6 TXX" or "NC4 LXX". (X stands for any random character or digit) to return 50.0.
If any other postcode is entered then return 100.0.
However i am not getting any results back and just finding errors. I'm sure i have gone massive wrong somewhere as im not great with If Else statements within methods. Any help or knowledge on this would be great!
public class multiPostcodeRange {
//Declaring Variables
String pcode;
public multiPostcodeRange()
{
pcode = "XXX XXX";
}
public void multiPostcodeRange()
{
if (pcode("GH6 TXX", "NC4 LXX")) {
return 100.0; }
else {
return 50.0;}
} }
public class MultiPostcodeRange {
private String pcode;
public MultiPostcodeRange() {
pcode = "XXX XXX";
}
public double multiPostcodeRange() {
if (pcode.equals("GH6 TXX") || pcode.equals("NC4 LXX")) {
return 100.0;
}
else {
return 50.0;
}
}
}
To return double from a function you need to define a return type for the function.
public double multiPostcodeRange
You created a class with his methods (which btw you shouldn't name as the class, but give them unique names).
Then you have to create a new instance object of that class and call the method on a main function.
For example, at the end of your code:
`public static void main(String args[]){
multiPostcodeRange Obj = new
multiPostcodeRange();
Obj.meth1();
Obj.meth2();}`
NB remember to give those methods unique names!
Also change 2nd method body and type as AndyMan's answer

Make the variable not overwrite to null and check if the codes are correct

I'm new to Java and I have created a class which is based on the question from this exercise.
I've tried my best to follow it and I think the reason why my variables are 0 or null is that I didn't write anything in the constructor. The question didn't say anything about what to write in the constructor.
I'm printing everything out because I want to see the result, but all I get from getCardNumber is null, getBalance is 0, coffee is 0. redeemFreeCoffee and isFreeCoffeeAvailable does work, simply because there are no variables that override them.
Here's the full question:
a. Each loyalty card stores the card number, current balance (the number of points) and the number of coffees on the card. Implement a
constructor with the card number (of type String) as its argument and
method getCardNumber() and getBalance().
b. Implement a method collectRewards(double amount, int coffees) that takes the amount spent (in pounds) and the number of coffees
bought and increases the balance (by one point for every pound spent)
as well as the number of coffees on the card.
c. Implement a method isFreeCoffeeAvailable() that checks whether a free coffee is available, that is, whether the number of coffees on
the card is greater than or equal to 9.
d. Implement a method redeemFreeCoffee() that first checks whether a free coffee is available. If this is the case then it reduces the
number of coffees by 9 and returns true, otherwise false.
I've tried changing the variables from private to public but I still get the same result.
I've even tried putting my main in a different class but the result is still the same.
public String cardNumber;
public int balance;
public int coffee;
public double amount;
public String getCardNumber () {
return cardNumber;
}
public int getBalance () {
return balance;
}
public double collectRewards(double amount, int coffees) {
if (amount > 0) {
coffee++;
balance++;
}
return amount;
}
public int isFreeCoffeeAvailable(){
if (coffee >= 9) {
return coffee;
}
return coffee;
}
public boolean redeemFreeCoffee() {
if (coffee > 9) {
coffee-=9;
return true;
}
else {
return false;
}
}
public LoyaltyCard (String cardNumber){
}
public static void main (String[] args) {
String cardNumber = "0987654321";
LoyaltyCard LoyaltyCardOne = new LoyaltyCard(cardNumber);
System.out.printf("%s%n%s%n%s%n%s%n%s",LoyaltyCardOne.getCardNumber(),LoyaltyCardOne.getBalance(),LoyaltyCardOne.collectRewards(6.0,5),LoyaltyCardOne.redeemFreeCoffee(),LoyaltyCardOne.isFreeCoffeeAvailable());
}
I'd like to see the result for getCardNumber(), getBalance() and the amount of coffee.
all I get from getCardNumber is null
You never initialized it
public LoyaltyCard (String cardNumber){
this.cardNumber = cardNumber;
}
because there are no variables that override them.
I think you might be confused about what "override" means, but that isn't the problem.
getBalance is 0, coffee is 0
You're calling those before you ever "collect rewards"
You will need to collect before printing the invidiual values, and read the logic again - increase by one point for every pound spent. So, focus on changing this block to fix that.
if (amount > 0) {
coffee++;
balance++;
}
Note that the instructions don't say the collectRewards returns anything. Also coffee should be increased by the input parameter, maybe than just 1.
Otherwise, you would need to call collectRewards at least 9 times before the redeem and isAvailable methods would work.
And once those are, you could do this, rather than rewrite coffee > 9
if (this.isFreeCoffeeAvailable()) {
} else {
}
Note: isFreeCoffeeAvailable should probably return coffee > 9; rather than return the amount
In Java all non-local variables are initialized to 0, or null. So far in the code you don't set variables to your desired values. You can either create a constructor which takes values, e,g:
LoyaltyCard(int balance, int coffee, double amount) {
this.balance = balance;
this.coffee = coffee;
// ... and other fields
or create setters for each field:
public setBalance(int balance) {
this.balance = balance;
}

How to use a user defined exceptions in java inside another method

I want to create a set method to insert maximum temperature for a specific place and I want that temperature to be of type Double,the method will check if the entered number is >= to 100 or <= to 100
if yes then it will be inserted in the maximum temperature field..
else I have to throw a user defined exception that will tell me that the number I entered is out of the supposed limits!
I wrote the Exception and the method this way:
public class OutOfSensibleLimits extends Exception
{
private Double max;
public OutOfSensibleLimits(Double max)
{
this.max = max;
}
public Double getMax()
{
return max;
}
public String toString()
{
return "The maximum Tempreture you entered: '" + maxTemp +
"' is out of sensible limits.";
}
}
public void setMaxTemp(Double max){
if ( max >= -100 || max <= 100)
{
maxTemp = max;
}
else throw new OutOfSensibleLimits();
}
and it gives me an error, what am I doing wrong?
Problems:
This is not how exceptions work -- you need to call the appropriate super constructor with the appropriate String if you want it to show a String, and
You're not calling your own exception's constructor properly. You've written it to accept a Double, and you're not passing in a Double (you're passing in nothing).
the toString method is unnecessary and confusing since it will never be called and the String will never be seen.
You state, "and it gives me an error,...", but don't show us any error message. I'm guessing that the compiler is complaining that you're not calling your class's constructor correctly, but please don't leave us guessing -- show the complete unabridged error message.
Your setMaxTemp uses the wrong boolean operator: if ( max >= -100 || max <= 100). This is always true. You want to use && instead.
Suggestions:
Yes, pass in a double the constructor
And then use that double to create an appropriate error/exception message that is passed into the super's constructor.
Get rid of your exception class's fields and toString() method.
Most important, I urge you to first read the Exception tutorial before trying anything else.
Also simplify as you're making things overly complex. Your Exception class could easily be nothing more than a constructor and that's it.
Make sure that the method that might throw the exception declares that it throws this exception.
For example:
public class TestSensibleLimits {
private Double maxTemp;
public void setMaxTemp(double max) throws OutOfSensibleLimits {
if (max >= -100 && max <= 100) { // use && not ||
maxTemp = max;
} else
throw new OutOfSensibleLimits(max);
}
public Double getMaxTemp() {
return maxTemp;
}
public static void main(String[] args) {
TestSensibleLimits test = new TestSensibleLimits();
try {
test.setMaxTemp(200);
} catch (OutOfSensibleLimits e) {
e.printStackTrace();
}
}
}
#SuppressWarnings("serial")
public class OutOfSensibleLimits extends Exception {
private static final String FORMAT = "The maximum Temperature you "
+ "entered: %.2f is out of sensible limits.";
public OutOfSensibleLimits(Double max) {
super(String.format(FORMAT, max));
}
}

Java, "Variable name" cannot be resolved to a variable

I use Eclipse using Java, I get this error:
"Variable name" cannot be resolved to a variable.
With this Java program:
public class SalCal {
private int hoursWorked;
public SalCal(String name, int hours, double hoursRate) {
nameEmployee = name;
hoursWorked = hours;
ratePrHour = hoursRate;
}
public void setHoursWorked() {
hoursWorked = hours; //ERROR HERE, hours cannot be resolved to a type
}
public double calculateSalary() {
if (hoursWorked <= 40) {
totalSalary = ratePrHour * (double) hoursWorked;
}
if (hoursWorked > 40) {
salaryAfter40 = hoursWorked - 40;
totalSalary = (ratePrHour * 40)
+ (ratePrHour * 1.5 * salaryAfter40);
}
return totalSalary;
}
}
What causes this error message?
If you look at the scope of the variable 'hoursWorked' you will see that it is a member of the class (declared as private int)
The two variables you are having trouble with are passed as parameters to the constructor.
The error message is because 'hours' is out of scope in the setter.
public void setHoursWorked(){
hoursWorked = hours;
}
You haven't defined hours inside that method. hours is not passed in as a parameter, it's not declared as a variable, and it's not being used as a class member, so you get that error.
I've noticed bizarre behavior with Eclipse version 4.2.1 delivering me this error:
String cannot be resolved to a variable
With this Java code:
if (true)
String my_variable = "somevalue";
System.out.println("foobar");
You would think this code is very straight forward, the conditional is true, we set my_variable to somevalue. And it should print foobar. Right?
Wrong, you get the above mentioned compile time error. Eclipse is trying to prevent you from making a mistake by assuming that both statements are within the if statement.
If you put braces around the conditional block like this:
if (true){
String my_variable = "somevalue"; }
System.out.println("foobar");
Then it compiles and runs fine. Apparently poorly bracketed conditionals are fair game for generating compile time errors now.

Help with method logic in Java, hw

I have a Loan class that in its printPayment method, it prints the amortization table of a loan for a hw assignment. We are also to implement a print first payment method, and a print last payment method. Since my calculation is done in the printPayment method, I didn't know how I could get the value in the first or last iteration of the loop and print that amount out.
One way I can think of is to write a new method that might return that value, but I wasn't sure if there was a better way. Here is my code:
public abstract class Loan
{
public void setClient(Person client)
{
this.client = client;
}
public Person getClient()
{
return client;
}
public void setLoanId()
{
loanId = nextId;
nextId++;
}
public int getLoanId()
{
return loanId;
}
public void setInterestRate(double interestRate)
{
this.interestRate = interestRate;
}
public double getInterestRate()
{
return interestRate;
}
public void setLoanLength(int loanLength)
{
this.loanLength = loanLength;
}
public int getLoanLength()
{
return loanLength;
}
public void setLoanAmount(double loanAmount)
{
this.loanAmount = loanAmount;
}
public double getLoanAmount()
{
return loanAmount;
}
public void printPayments()
{
double monthlyInterest;
double monthlyPrincipalPaid;
double newPrincipal;
int paymentNumber = 1;
double monthlyInterestRate = interestRate / 1200;
double monthlyPayment = loanAmount * (monthlyInterestRate) /
(1 - Math.pow((1 + monthlyInterestRate),( -1 * loanLength)));
System.out.println("Payment Number | Interest | Principal | Loan Balance");
// amortization table
while (loanAmount >= 0) {
monthlyInterest = loanAmount * monthlyInterestRate;
monthlyPrincipalPaid = monthlyPayment - monthlyInterest;
newPrincipal = loanAmount - monthlyPrincipalPaid;
loanAmount = newPrincipal;
System.out.printf("%d, %.2f, %.2f, %.2f", paymentNumber++, monthlyInterest, monthlyPrincipalPaid, loanAmount);
}
}
/*
//method to print first payment
public double getFirstPayment()
{
}
method to print last payment
public double getLastPayment()
{
}*/
private Person client;
private int loanId;
private double interestRate;
private int loanLength;
private double loanAmount;
private static int nextId = 1;
}
Thanks!
You've already identified that the printPayments(), printFirstPayment() and printLastPayment() methods have common logic. You generally want to minimize duplication of such code and the two common ways to do this are:
Implement all but one of the methods in terms of one of them; or
Implement all the methods in terms of a private method.
So, for example:
public void printPayments() {
for (Payment : getPayments()) {
printPayment(payment);
}
}
public void printFirstPayment() {
printPayment(getPayments().get(0));
}
public void printLastPayment() {
List<Payment> payments = getPayments();
printPayment(payments.get(payments.size()-1));
}
private void printPayment(Payment payment) {
...
}
private List<Payment> getPayments() {
...
}
Now this is homework so you may not have come across the syntax List<Payment> yet. If not, it's generics. There are other ways to do this: using a non-generic Collection or using arrays for example.
The points I wanted to illustrate here is that:
The logic for creating the payments and displaying them has been separated;
A single method getPayments() does the calculations and returns a List of Payment objects. Payment is a new object in this mock up;
All three methods are implemented in terms of getPayments() and printPayment().
So I hope this leads you in the right direction. The concept here I guess is functional composition, composing your functions in terms of other functions and making your internal functions granular enough to be grouped together usefully.
Your printPayments function is awfully big. It is generally better to make each function "do one thing and one thing well", and to make functions relatively short. I would recommend that you separate your computation logic from your printing logic; provide functions for computing these various payments, and have your print function merely print the result of invoking those computation functions.
If you are worried about redundancy (that is some of the later computations depend on earlier computations which you might have previously performed), then you can use dynamic programming, which basically means that you accumulate previous results in an array or matrix so that they can be reused in subsequent computations. You could compute the entire amortization table as a 2-dimensional array, in which case you could lookup the earlier payments that you computed simply by looking them up in that array.
Maybe you should have a method that returns an array/set/list/resultset/datacontainer (add more buzzwords to confuse you - its your homework after all ;)) which you can use in the other methods.
if when you describe what a method does, you use the word 'and', chances are the method is doing too much. each method should do one thing, so printing is one thing, and calculating is another .. so two methods.

Categories

Resources