循环中的循环环Java

问题描述:

我需要建立一个数组,包含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;) –

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

,你需要使用

更改前初始化int number;

int number; 

int number = 0; 

您稍后在程序中访问的变量需要进行初始化,因为如果不能保证您使用的变量没有要使用的值,Java将无法编译。由于您在声明时没有给出初始值number,但仍然使用try catch块来访问它,因此Java不会确定number在到达try catch块时是否有值为什么它目前没有工作。