Reputation: 1
I'm writing a program for the "University Book Store" for a class. And I feel like everything should be working, but for publishingPrice and markup, I'm getting a "Variable not initialized" error. Yet I gave them both values. What am I doing wrong? I'm using Netbeans.
import java.util.Scanner;
public class ProgrammingProject {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//Set my variables for the program
double publisherPrice;
double newBook;
double usedBook;
double usedBookDiscount;
double rentalBook;
double rentalBookDiscount;
double markup;
int booksOrdered;
String bookName;
System.out.println("Enter the Book Title: ");
bookName = keyboard.next();
System.out.println("Enter the Amount of Books Ordered: ");
booksOrdered = keyboard.nextInt();
//Set the conditions for markup
if (booksOrdered < 20) {
markup = .40;
}
if (booksOrdered >= 20 && booksOrdered < 50){
markup = .35;
}
if (booksOrdered >= 50 && booksOrdered < 100){
markup = .30;
}
if (booksOrdered >=100){
markup = .25;
}
//Set calculations for program to use
usedBookDiscount = .75;
rentalBookDiscount = .40;
newBook = (publisherPrice + markup);
usedBook = ((newBook * usedBookDiscount) - usedBookDiscount);
rentalBook = ((newBook * rentalBookDiscount - rentalBookDiscount));
System.out.println(bookName + publisherPrice + newBook + usedBook + rentalBook);
}
}
Upvotes: 0
Views: 609
Reputation: 1500675
You only assign a value to markup
within if
statements. The compiler doesn't keep track of what's feasible, and whether you've covered all cases... so the variable still isn't definitely assigned as far as the compiler is concerned.
The simplest fix is to use else
instead:
if (booksOrdered < 20) {
markup = .40;
} else if (booksOrdered < 50) {
markup = .35;
} else if (booksOrdered < 100) {
markup = .30;
} else {
markup = .25;
}
Because the final else
is unconditional, the compiler will spot that every path through this code assigns a value to markup
.
That's enough for markup
- but you haven't specified anything that will assign a value to publisherPrice
. Was that meant to be set via more user input? Note that it would be easier to spot all of this if you assign values to your variables at the point of declaration, rather than declaring everything at the start of the method and then assigning values.
For example, instead of this:
String bookName;
System.out.println("Enter the Book Title: ");
bookName = keyboard.next();
... you can have:
System.out.println("Enter the Book Title: ");
String bookName = keyboard.next();
As another side note, you shouldn't generally use double
for financial amounts - consider using BigDecimal
instead.
Upvotes: 2
Reputation: 1349
All of your variables must be initialized with values before you can perform arithmetic on them.
Upvotes: 1