2016-04-21 163 views
0

我需要建立一個數組,包含10個條目,程序提示用戶,如果第一個條目是9999,我需要編程退出。我還需要使用try/catch來獲取錯誤。下面是我所擁有的,但是當我輸入try/catch循環時,我無法得到變量'number'以被識別...... HELP !!!循環中的循環環Java

public static void main(String[] args) { 
int nextIndex = 1; 
int[] numberFun; 
numberFun = new int [10]; //creates the array with 10 entries 
Scanner Keyboard = new Scanner (System.in); 
int entry = 0; 
//I'm trying to get the first entry to determine if it equals 9999 with this section 
int firstNumber=0; 
System.out.println ("Please enter a number"); 
firstNumber = Keyboard.nextInt(); 
numberFun[0] = firstNumber; 
if (firstNumber != 9999) 
       { 
        while (entry < 9) //this loop is supposed to obtain the other 9 entries for the array from the user 
        { 
        int number; 
        System.out.println ("Please enter a number"); 
         try // this is supposed to provide an error if the user enters something that is not a number 
         { 
         number = Keyboard.nextInt(); 
         } 
         catch (Exception ex) 
         { 
         //display error message here 
         } 
        numberFun[nextIndex] = number; 
        ++nextIndex; 
        ++entry; 
        } 
       } 
else 
{ 
    System.err.println("Command Accepted. Exiting Program."); 
} 

它正常工作,直到我把try/catch語句英寸

+0

您可能只需要初始化int(例如int number = 0;) –

回答

0

firstNumber = Keyboard.nextInt();在try catch塊

,你需要使用

1

更改前初始化int number;

int number; 

int number = 0; 

您稍後在程序中訪問的變量需要進行初始化,因爲如果不能保證您使用的變量沒有要使用的值,Java將無法編譯。由於您在聲明時沒有給出初始值number,但仍然使用try catch塊來訪問它,因此Java不會確定number在到達try catch塊時是否有值爲什麼它目前沒有工作。