-2
我有這個Java代碼。這是一個簡單的小東西,我試圖通過除以已佔用房間的總數除以房間總數來獲得酒店的入住率。然而,當我嘗試編譯我得到的代碼時:在Java變量被陳述但被遺忘?
C:\Users\Jerome\Documents\Computer Concepts and Programming\Lab04\JRGlab04Num07\JRGlab04Num07.java:62: error: variable totalORooms might not have been initialized
totalORooms += numORooms;
^
C:\Users\Jerome\Documents\Computer Concepts and Programming\Lab04\JRGlab04Num07\JRGlab04Num07.java:63: error: variable totalRooms might not have been initialized
totalRooms += numRooms;
^
C:\Users\Jerome\Documents\Computer Concepts and Programming\Lab04\JRGlab04Num07\JRGlab04Num07.java:68: error: variable totalORooms might not have been initialized
ORate = totalORooms/totalRooms;
^
C:\Users\Jerome\Documents\Computer Concepts and Programming\Lab04\JRGlab04Num07\JRGlab04Num07.java:68: error: variable totalRooms might not have been initialized
ORate = totalORooms/totalRooms;
^
4 errors
Tool completed with exit code 1
所以爲什麼它會忘記我已經說過的變量。
import java.util.Scanner; //Needed for Inputting
import java.text.DecimalFormat;//Needed for Rounding
/**
The pourpose of this lab is:
To calculate the occupancy rate of a hotel
by JEROME GERO Lab 04 Number 07
*/
public class JRGlab04Num07
{//Begin Class
public static void main(String[] args)
{//Begin Main Method
//Variables and introduction
double totalFloors, floor, numRooms, numORooms;
double totalRooms;
double totalORooms;
double ORate;
System.out.println("Welcome to the Hotel Occupancy Calculator.\nPlease enter the number of floors we will be dealing with:");
Scanner keyboard = new Scanner(System.in);
DecimalFormat formatter = new DecimalFormat("#0.00");
totalFloors = keyboard.nextInt();
floor = 0;
while(totalFloors < 1)
{
System.out.println("No, lets try that again.");
totalFloors = keyboard.nextInt();
}
System.out.println("Okay");
while(totalFloors > 0)
{
++floor;
System.out.println("Now enter the number of rooms on floor " + floor);
numRooms = keyboard.nextDouble();
while(numRooms < 10){
System.out.println("The Number of rooms nust be greater than 10.\nPlease enter the number of rooms.");
numRooms = keyboard.nextDouble();
}
System.out.println("Now enter the number of occupied rooms on that floor:");
numORooms = keyboard.nextDouble();
while(numORooms > numRooms){
System.out.println("No, the Number of Occupied rooms can not be more than the number of rooms on this floor.\n" +
"Please enter that again.");
numORooms = keyboard.nextDouble();
}
totalORooms += numORooms;
totalRooms += numRooms;
--totalFloors;
}
ORate = totalORooms/totalRooms;
System.out.println(ORate);
}//End Main Method
}//End Class
你爲什麼要爲float值做一個nextInt()?它應該是'nextDouble()'。 –
哎呦!我的錯。但是這似乎並沒有影響到它。 –
編譯器告訴你,你的變量從來沒有被初始化 - 它們從來沒有被賦予初始值。 'double totalORooms'只是聲明存在這樣一個變量;它並沒有給它一個初始值。 (編譯器不知道你想要的初始值是:0?NaN?Infinity?-Infinity?) – yshavit