我无法弄清楚输入参数的错误是什么,编译错误消息没有多大帮助。
import java.util.ArrayList;
/**
* Created by cheun on 11/8/2017.
*/
public class Problem2_ProductsOfAllIntsExceptAtIndex {
static int pointer;
static int[] arr;
static int[] temp_arr;
static int input;
public static int[] myFunction(int[] arg) {
// write the body of your function here
for (int i = 0; i <= arg.length; i++) {
pointer = i;
temp_arr = arg;
temp_arr[i] = 1; // or should put it null
for (int j = 0; i <= arr.length; i++) {
input *= temp_arr[j];
}
arr[pointer] = input;
}
return arr;
}
public static void main(String[] args) {
Problem2_ProductsOfAllIntsExceptAtIndex solution = new Problem2_ProductsOfAllIntsExceptAtIndex();
// line 32 FAULTY LINE BELOW
System.out.println(myFunction([0, 1, 2, 3]));
// line 32 FAULTY LINE ABOVE
}
}
d:\ java_workspace \ InterviewQuestions \ com.cake.interviews \ SRC \ Problem2_ProductsOfAllIntsExceptAtIndex.java 错误:(32,39)java:非法启动表达式 错误:(32,40)java: &#39;)&#39;预期错误:(32,41)java:&#39;;&#39;预期 错误:(32,43)java:不是声明 错误:(32,44)java:&#39;;&#39;预期
答案 0 :(得分:1)
你的计划中出现了一些错误。我强烈建议学习Java语言的基础知识。互联网上有很多免费资源。这是您可以开始的Java Tutorials网站。 here你可以用Java直接转到数组。
说过以下可能是你想要实现的目标:
public class Problem2_ProductsOfAllIntsExceptAtIndex {
public static int[] myFunction(int[] arg) {
// making all variables global (=> static) doesn't make sense in this case
int input = 1;
int[] temp_arr;
int[] arr ;
arr = new int[arg.length];
for (int i = 0; i < arg.length; i++) {
temp_arr = Arrays.copyOf(arg, arg.length); // clone the original array; otherwise you overwrite the original one
temp_arr[i] = 1; // or should put it null
for (int j = 0; j < temp_arr.length; j++) {
input *= temp_arr[j];
}
arr[i] = input;
input = 1; // reset
}
return arr;
}
public static void main(String[] args) {
int [] arr = myFunction(new int[] { 0, 1, 2, 3 });
System.out.println(Arrays.toString(arr));
}
}
答案 1 :(得分:0)
1.arr未实例化 - &gt;空指针异常
2.如果您想输入带数字的数组,请使用:
System.out.println(myFunction(new int[]{0, 1, 2, 3}));
或者您可以将我的功能定义更改为 myFunction(int ... arg)并给出由昏迷
分隔的参数示例:
public class Problem2_ProductsOfAllIntsExceptAtIndex {
static int pointer;
static int[] arr= new int[4];
static int[] temp_arr;
static int input;
public static int[] myFunction(int[] arg) {
// write the body of your function here
for (int i = 0; i <= arg.length; i++) {
pointer = i;
temp_arr = arg;
temp_arr[i] = 1; // or should put it null
for (int j = 0; i <= arr.length; i++) {
input *= temp_arr[j];
}
arr[pointer] = input;
}
return arr;
}
public static void main(String[] args) {
Problem2_ProductsOfAllIntsExceptAtIndex solution = new Problem2_ProductsOfAllIntsExceptAtIndex();
// line 32 FAULTY LINE BELOW
System.out.println(Arrays.toString(myFunction(new int[]{0, 1, 2, 3})));
// line 32 FAULTY LINE ABOVE
}
}