Results 1 to 3 of 3
Thread: Variable not initialized?
- 07-15-2011, 05:31 AM #1
Member
- Join Date
- Jul 2011
- Posts
- 36
- Rep Power
- 0
Variable not initialized?
So I just started Java yesterday. I have been reading a book about it. So far I have made this code and run into a problem. It says " The variable itemcost might have not been initialized but it is clearly initialized in the if statement. I really have no idea what to do, and yes, I have searched.
import java.util.Scanner;
public class IDKKKKK
{
public static void main(String args[]) {
Scanner myScanner= new Scanner (System.in);
int PayPerHour;
int HoursADay;
int DaysAWeek;
int PerDay;
int PerWeek;
int PerYear;
int itemcost;
int time;
char reply;
System.out.print("How much are you paid an hour?");
PayPerHour= myScanner.nextInt();
System.out.print("How many hours do you work a day?");
HoursADay= myScanner.nextInt();
System.out.print("How many days a week do you work?");
DaysAWeek= myScanner.nextInt();
PerDay= PayPerHour*HoursADay;
PerWeek= PerDay*DaysAWeek;
PerYear= PerWeek*52;
time= itemcost/PerWeek;
System.out.println("You make ");
System.out.print( PerDay);
System.out.println(" dollars per day.");
System.out.print(" You make ");
System.out.print(PerWeek);
System.out.println(" dollars per week.");
System.out.print(" You Make ");
System.out.print(PerYear);
System.out.println(" dollars per year.");
System.out.println("Is there anything you want to save up for? (Y/N)");
reply= myScanner.next().charAt(0);
if (reply== 'Y' || reply=='y'){
System.out.print ("How much does your item cost?");
itemcost= myScanner.nextInt();
System.out.print("It will take you ");
System.out.print(time );
System.out.print("weeks of work to get enough money to purchase your item");
}
}
}
-
1) If statements are not guaranteed to happen (that's why they're called "if" statements). Your best off initializing the variable to some default value when you first declare it.
2) Regardless, are you sure that you assign something to itemcost before you try to use it? I don't think so. Again, initialize it at declaration, and don't use it until you have assigned something logical to it.
- 07-15-2011, 02:00 PM #3
Member
- Join Date
- Jul 2011
- Posts
- 36
- Rep Power
- 0
Similar Threads
-
Variable not initialized.
By miss_peaches in forum New To JavaReplies: 14Last Post: 04-27-2011, 09:28 AM -
Variables might not have been initialized
By tnixon22 in forum New To JavaReplies: 5Last Post: 01-17-2011, 12:47 AM -
variable name might not have been initialized
By p0rnstar in forum New To JavaReplies: 3Last Post: 01-26-2010, 03:27 PM -
Variable not initialized after while loop
By ejs7597 in forum New To JavaReplies: 6Last Post: 02-28-2009, 05:00 AM -
Not initialized variable
By bbq in forum New To JavaReplies: 2Last Post: 07-04-2007, 09:02 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks