所以我对Java非常陌生,就在几个小时前刚刚开始。我不知道该怎么做;到目前为止我的代码:
import java.util.Scanner;
public class Class_one{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args){
int[] listArray;
System.out.print("Please enter the number to calculate the factorial for: ");
if (userInput.hasNextInt()){
int numEnter = userInput.nextInt();
final int numEnterC = numEnter;
if (numEnter >= 0){
listArray = new int[numEnterC];
int arrayVal = 0;
while (numEnter >= 0){
listArray [arrayVal] = numEnter;
arrayVal++;
numEnter = numEnter - 1;
if (numEnter == 0){
break;
}
}
while (arrayVal >= -1){
int newArVal = listArray[arrayVal]*listArray[arrayVal - 1];
newArVal = listArray[arrayVal];
arrayVal = arrayVal - 1;
}
//I don't know what's happening in the next line:
String nArVals = Integer.toString(newArVal));
System.out.println(nArVals + " is the result of the factorial operations of " + numEnterC);
}
if (numEnter == 0){
System.out.println("1");
}
if (numEnter <= 0){
System.out.println("Negatives unavailable for factorial.");
}
}
}
}
那么我做错了什么?我不希望你们只是粘贴答案,我想自己弄清楚,所以你能给我一个提示,或者不是直接回答让我自己解决这个问题吗?
这是我收到的错误消息(我正在使用Eclipse):
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
newArVal cannot be resolved to a variable.
Syntax error on token ")", delete this token.
at project_one.Class_one.main(Class_one.java:27)
答案 0 :(得分:3)
您无需创建数组
int numEnter = userInput.nextInt();
int factorial = 1;
for (int i=1; i <= numEnter; i++) factorial *= i;
答案 1 :(得分:0)
我会以递归方式完全不同地实现
public int factorial(int number){
if(number>0){
return number*factorial(number-1);
} else {
return 1;
}
}
我还没有这样做。
答案 2 :(得分:0)
变量newArVals在以下行中引用时不在范围内。
String newArVals = Integer.toString(newArVal));
要使它在范围内,你必须在while循环之外定义newArVal,即
int newArVal =0;
while (arrayVal >= -1){
newArVal = listArray[arrayVal]*listArray[arrayVal - 1];
newArVal = listArray[arrayVal];
arrayVal = arrayVal - 1;
}