简体   繁体   中英

Loops in Loops in Loops in Java

I need to build an array with 10 entries that the program prompts from the user, if the first entry is 9999, i need to program to quit. I also need to use try/catch for errors. Below is what I have but I can't get the variable 'number' to be recognized throughout when I input the try/catch loop... HELP!!!

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.");
 }

it works properly until I put the try/catch in.

Change,

int number;

to

int number = 0;

The variable that you are accessing later in the program needs to be initialized because Java will not compile if there's no guarantee that the variable you're using does not have a value to be worked with. Since you did not give number an initial value when you declared it, yet still use a try catch block to access it, Java won't know for sure whether number will have a value by the time it reaches the try catch block, which is why it's not currently working.

write firstNumber = Keyboard.nextInt(); in try catch block

and you need to initialize int number; before use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM