[英]Loops in Loops in Loops in Java
我需要构建一个包含10个条目的数组,程序会从用户提示,如果第一个条目是9999,我需要编程退出。 我还需要使用try / catch来获取错误。 以下是我所拥有的,但是当我输入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.");
}
它可以正常工作,直到我尝试/捕获为止。
更改,
int number;
至
int number = 0;
您需要在程序中稍后访问的变量需要初始化,因为如果无法保证所使用的变量没有可使用的值,Java将不会编译。 由于您在声明number
时没有给number
一个初始值,但仍然使用try catch块来访问它,因此Java不确定在到达try catch块时number
是否将具有值。为什么它当前不起作用。
写firstNumber = Keyboard.nextInt();
在尝试捕获块
并且您需要初始化int number;
使用前
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.