首页 文章

Java 7:作为输入的数组

提问于
浏览
0

好吧,所以我应该使用它作为我的代码的开头:

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 class Problem1 {public static void main(String args []){

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
}

2 回答

  • 1

    你可能想考虑在逗号上拆分一个 String ?看这里:How to split a string in Java

  • 2

    至少有两种选择:

    • 让用户将数组条目指定为单独的命令行参数,例如:
    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对我来说似乎更简单,因为你开始使用字符串数组 .

相关问题