gpt4 book ai didi

java - 如何将运行者中的数字列表设置为构造函数中的 ArrayList?

转载 作者:行者123 更新时间:2023-12-01 19:42:46 24 4
gpt4 key购买 nike

我已经为此苦苦挣扎了一段时间了。我知道我可以在构造函数中将 String 实例化为 ArrayList,但我不知道如何从运行程序将一组 int 实例化为 ArrayList,而无需一遍又一遍地使用 list.add(number) 手动完成所有操作。

void setup() { //My runner
NumAnalyzer test = new NumAnalyzer("5 12 9 6 1 4 8 6");

out.println("even count = "+test.countEvens());
out.println("odd count = "+test.countOdds());
out.println("perfect count = "+test.countPerfects()+"\n\n\n");


//add more test cases
}




import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.System.*;

public class NumAnalyzer{
private ArrayList<Number> list;

public NumAnalyzer(String word){
list = new ArrayList<Number>(); //This instantiates it as a String but I want it to instantiate it as a list of integers.
}


public int countOdds(){ //counting odds
int oddCount=0;
for(int x=0; x<list.size(); x++){
if(list.get(x)%2 != 0){
oddCount++;
}
}
return oddCount;
}

public int countEvens(){ //counting evens
int evenCount=0;
for(Number num : list){
if(list.get(num)%2 == 0){
evenCount++;
}
}
return evenCount;
}

public int countPerfects() {
int perfectCount=0;
for(int x=0; x<list.size(); x++){

int mult=2, factorsum=0; //gets the sum of the multiples
while(list.get(x) != mult){
if(list.get(x)%mult == 0){
factorsum=factorsum+list.get(x);
}
mult++;
}

if(factorsum == list.get(x)){ //testing to see if it's perfect
perfectCount++;
}
}
return perfectCount;
}

public String toString( ){





return "Number of Odds:"+oddCount+"/n Number of Evens:"+evenCount+"/n Number of Perfects:"+perfectCount+list;
}
}

总的来说,我只希望构造函数使用来自运行者的数字实例化 ArrayList。

最佳答案

在构造函数中,您可以使用空格分割单词,然后将每个标记转换为整数,最后收集到列表中:-

list = Arrays.stream(word.split("\\s+"))
.map(Integer::parseInt)
.collect(Collectors.toList());

更新

对于数字而不仅仅是整数,您可以使用此映射:-

.map(s -> s.contains(".") ? (Number) Double.parseDouble(s) : Integer.parseInt(s))

如果您严格想要 ArrayList 而不是任何列表,您可以将其收集为:-

.collect(Collectors.toCollection(ArrayList::new));

但是如果您不使用字符串,最好使用可变参数。

关于java - 如何将运行者中的数字列表设置为构造函数中的 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54681556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com