gpt4 book ai didi

java - Java 中的循环中的循环

转载 作者:行者123 更新时间:2023-12-01 10:01:46 25 4
gpt4 key购买 nike

我需要构建一个包含程序从用户提示的 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.");
}

在我放入 try/catch 之前它会正常工作。

最佳答案

改变,

int number;

int number = 0;

您稍后在程序中访问的变量需要初始化,因为如果不能保证您正在使用的变量没有要使用的值,Java 将无法编译。由于您在声明 number 时没有为其指定初始值,但仍使用 try catch block 来访问它,因此 Java 无法确定 number 是否会具有当它到达 try catch block 时,它会返回一个值,这就是它当前不起作用的原因。

关于java - Java 中的循环中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36759476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com