【发布时间】:2014-08-22 21:10:04
【问题描述】:
我的程序是输入 10 个数字并将它们相加,然后显示结果。然后我将较小的数字除以较大的数字并显示结果。用户不能输入字符或零。
我是新手,已经为此工作了 DAYS。我没有看到我的错误。
现在我的问题是变量 i 未被识别。
我引入了一个异常 (try..catch),但它无法读取。我试着把东西搬过来(我是新来的,我在猜测,看看有什么作用..)我做错了什么,可能是一些愚蠢的小事。我需要一些帮助和新鲜的眼睛。
当用户输入 9999 时,我还需要结束程序。知道那会去哪里吗?因为我快要泪流满面了。
public static void main(String[] args) throws NumberFormatException {
Scanner in = new Scanner(System.in);
Scanner input = new Scanner(System.in);
double[ ] digit = new double[11];
int sum = 0;
//Declare an array
System.out.print("Please Enter Ten Numbers:");
System.out.println();
try{
for (int i = 1; i < digit.length; i++)
System.out.print("Numbers " + i + ": ");
digit[i] = (double)in.nextInt(); //Array Not recognized here
sum += (int)digit[i];//Or recognized here
// Input the data into array from the user.
if(digit[i]==0.0)//None of these are recognized either, what did I do?
{
System.out.println("You can't enter zero. Try again");
--i; //nope
in.nextLine();//dispose of wrong number
}
}catch (NumberFormatException e){
System.out.println("You Can Only Enter Numbers!");
--i; //nope, not recognizing here either
in.nextLine();//dispose of wrong input
}
System.out.println("Total Values in Array:"+ sum);
// Calculate the sum and print the total
System.out.println();
System.out.println("Would you like to divide the values?");
System.out.println("Yes or No to Exit the Program");
String a = input.next();
if(a.equalsIgnoreCase("yes")){
double [] divisionResult = new double[digit.length / 2];
//Division array declared
for (int i = 1; i < digit.length; i += 2)
//These are all good and recognized. No problem with the division part
{
double result = digit[i];
if (result > digit[i + 1])
result = result / digit[i + 1];
else {
result = digit[i + 1] / result;
}
divisionResult [i / 2] = result;
System.out.println(result);
}
}
else if(a.equalsIgnoreCase("no")){
System.exit(0);
}
}
}
}
【问题讨论】:
-
我们需要一个比“变量 i 未被识别”更好的描述。您需要复制/粘贴您收到的确切错误消息。
-
(请注意您在
for语句之后缺少{。(如果您对缩进更加小心,可能会更容易找到其他一些类似的错误。) ) -
这是我的问题。我将括号放在 for 循环周围,然后我的 try..catch 无法识别对方
-
仔细匹配您的
{和}字符。使用缩进来帮助你。您应该为您传递的每个{缩进 4 个额外的空格,并在传递匹配的}时少缩进 4 个空格。
标签: java arrays exception try-catch