BiohazzardXIII
BiohazzardXIII

Reputation: 25

Java Methods and return statement

I am trying to test a class i'm working on. I want to run a print statement that takes a monthly salary for an employee multiply it by 12 to give me the annual salary then adds 10%. I have gotten everything to work except for the last part

Here is my code so far (This is just partial code)

constructors

 public double findSal(){
    return this.monthlySalary * 12;
}

public double giveRaise(){
    return this.monthlySalary * 12 * 0.10;
}

System.out.printf("The yearly salary for " +employee1.getfirstName()+" " + employee1.getlastName()+" " + "With a 10% raise is: $" +employee1.giveRaise()+ "\n");
System.out.printf("The yearly salary for " +employee2.getfirstName()+" " + employee2.getlastName()+" " + "With a 10% raise is: $" +employee2.giveRaise()+ "\n");

This is the error I am getting when I run

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'r' at java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2691) at java.util.Formatter$FormatSpecifier.(Formatter.java:2720) at java.util.Formatter.parse(Formatter.java:2560) at java.util.Formatter.format(Formatter.java:2501) at java.io.PrintStream.format(PrintStream.java:970) at java.io.PrintStream.printf(PrintStream.java:871) at labex4oop.employeeTest.main(employeeTest.java:35) Java Result: 1

Upvotes: 0

Views: 187

Answers (3)

dhke
dhke

Reputation: 15388

System.out.printf("With [...] a 10% raise [...]");
                                  ^ // your problem is here

printf() is for formatted output. Placeholders in the format string are introduced via %. 10% raise in your code is interpreted as a %r formatting specifier. Since you neither have any arguments to format nor is %r a valid printf format specifier, you get the error message telling you that your format string is wrong.

To include a literal % you must use %%. Or stop using printf() at all because you are not using its capabilities:

System.out.println("The yearly salary for " 
   + employee2.getfirstName()
   + " " + employee2.getlastName()
   + " with a 10% raise is: $" 
   + employee2.giveRaise() + "\n"
);

Upvotes: 1

Hiren
Hiren

Reputation: 51

This should give you the correct answer. I have tried it.public double giveRaise(){ return this.monthlySalary * 12 * 1.10; }

Upvotes: 0

collapsar
collapsar

Reputation: 17238

Your code suffers from a minor oversight:

Public double giveRaise(){
    return this.monthlySalary * 12.0 * 1.10; // was 0.10
}

You also need to convert from double When printing the values and you have to escape the percent sign in your literals (since you use printf where % has placeholder semantics):

System.out.printf("The yearly salary for " +employee2.getfirstName()+" " + employee2.getlastName()+" " + "With a 10%% raise is: $" +String.valueOf(employee2.giveRaise())+ "\n");

Upvotes: 1

Related Questions