简体   繁体   English

Java中的循环

[英]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. 我需要构建一个包含10个条目的数组,程序会从用户提示,如果第一个条目是9999,我需要编程退出。 I also need to use try/catch for errors. 我还需要使用try / catch来获取错误。 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!!! 以下是我所拥有的,但是当我输入try / catch循环时,我始终无法识别变量'number'。

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. 您需要在程序中稍后访问的变量需要初始化,因为如果无法保证所使用的变量没有可使用的值,Java将不会编译。 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. 由于您在声明number时没有给number一个初始值,但仍然使用try catch块来访问它,因此Java不确定在到达try catch块时number是否将具有值。为什么它当前不起作用。

write firstNumber = Keyboard.nextInt(); firstNumber = Keyboard.nextInt(); in try catch block 在尝试捕获块

and you need to initialize int number; 并且您需要初始化int number; before use 使用前

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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