好吧,所以我应该以此作为我的代码的开头:
public static int addOdds(int[] input){}
这将返回总和。
我已经用预加载的数组完成了添加赔率部分。 这很简单,但令我感到困惑的是如何让它将数组作为用户的输入。
我从 java.utils 知道 Scanner,但我不确定如何让它与我的代码一起运行以使其采用数组(如果可以的话)。
我考虑过使用:
public string void main(String [] args){}
并用它调用 Scanner,并使用 Integer.parseint(),但我不认为这可以解析数组。
然后调用来自扫描仪的输入数组并将其传递给 addOdds 方法。
例如,代码必须将 {2,3,7,8,4,1} 作为输入。
先谢谢了,我有点困惑。
如果有帮助,这里是一个示例查询; inputTwo 与问题无关:
public class Proj2Tester {
public static void main(String[] args){
int[] inputOne = {4,8,9,12,7};
int[] inputTwo = {41,38,19,112,705};
System.out.println("Problem 1 is correct on test input = " + (16 == Problem1.addOdds(inputOne)));
System.out.println("Problem 2 is correct on test input = " + (686== Problem2.getRange(inputTwo)));
}
按照 T.J. 的建议,我尝试了以下操作:
公共(public)课问题1 { 公共(public)静态无效主(字符串参数[]){
System.out.println("Your array is: "+input);
}
}
public static int addOdds(int[] input){
int[] input = new int[args.length]; //Begin T.J.'s segment
int n = 0;
for (String arg : args) {
input[n++] = Integer.parseInt(arg);
int sum =0; //Initializing sum as 0;
for(int i =0; i < inputOne.length; i++){
if(inputOne[i] % 2 !=0){
;
sum = sum + inputOne[i];
break;
}
if(inputOne[i] % 2 == 0){
i++;
break;
}
}
return sum; // placeholder for my answer, not zero should be returned
}
最佳答案
至少有两个选择:
让用户将数组条目指定为单独的命令行参数,例如:
java YourClass 2 3 7 8 4 1
...然后将
args
中的条目解析为int
数组:int[] input = new int[args.length]; int n = 0; for (String arg : args) { input[n++] = Integer.parseInt(arg); }
让用户使用逗号将数组指定为单个命令行参数:
java YourClass "2,3,7,8,4,1"
...然后用逗号分割
args[0]
并将结果字符串数组中的条目解析为int
数组。
#1 对我来说似乎更简单,因为您从字符串数组开始。
关于Java 7 : An array as input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28273108/