我想使用list.negativeNumbers();
来调出代码的一部分,该代码计算列表中有多少个负数。
public void negativeNumbers(){
int negative = 0;
for (int i = 0; i <= size; i++){
if (i < 0) {
negative = negative + 1;
}
System.out.println("There are "+ negative +" negative elements in the list!");
}
}
你能帮我创建一个方法,可以用正确的方式计算列表中的负数吗?
答案 0 :(得分:0)
如果它是一个整数列表,你不应该做“i&lt; 0”,而应该是i的索引处的数字。如果你这样做,你也想做“&lt; size”而不是“&lt; = size”,否则你会遇到IndexArrayOutOfBounds。
答案 1 :(得分:0)
这取决于双链表的实现方式,但如果它扩展了普通List<Integer>
接口,它将如下所示:
final Integer ZERO = Integer.valueOf(0);
int countNegativeElements() {
return stream().filter(MyList::isNegative).count();
}
static boolean isNegative(Integer i) {
return i.compareTo(ZERO) < 0;
}
有溪流。更传统的是每个集合(或者每个迭代器):
int countNegativeElements() {
int count = 0;
for(Integer i : this) { // or iterator()
if (isNegative(i)) count++;
}
return count;
}
这不期望并发修改,并且针对迭代是最快访问的集合进行了优化。如果您有一个简单的类型列表,那么您可以使用简单的isNegative
替换< 0
。
这里article讨论了迭代集合的不同方法。
在我的代码中,我假设您将该方法直接添加到列表实现类中。如果是实际的列表实例,请将this
或this.iterator()
或this.stream()
替换为外部。
<强>更新强>
我刚刚看到你的link to the actual linked list you are using,这看起来像这样(手工制作迭代):
int countNegativeElements() {
Node n = start;
int count = 0;
while(n != null) {
if (n.getData() < 0) count++;
n = n.getLinkNext();
}
return count;
}
使用null
因为没有hasLinkNext()
,这对于家庭作业来说是典型的:)
我认为使用不适合集合框架的实现并不是一个特别好的主意,但可能需要保持课程简单。
答案 2 :(得分:0)
public void negativeNumbers(){
int negative = 0;
for (int i = 0; i <= size; i++){
if (i < 0) {
negative = negative + 1;
}
System.out.println("There are "+ negative +" negative elements in the list!");
}
}
通过为自己制定解决方案,您将学到更好的知识。
您提供的代码是一个良好的开端,但缺乏:
这是一个简单的例子:
import java.util.ArrayList;
public class negnum {
public static void main(String [] args) {
ArrayList<Integer> nums = new ArrayList();
nums.add(0);
nums.add(10);
nums.add(-10);
nums.add(20);
nums.add(-20);
nums.add(30);
nums.add(-30);
nums.add(40);
nums.add(-40);
nums.add(50);
int negs = 0;
for (int i = 0; i < nums.size(); i++){
int n = nums.get(i);
if (n < 0) {
++negs;
System.out.println(n);
}
}
System.out.println(negs +" negatives");
}
}
c:\dev>java negnum
-10
-20
-30
-40
4 negatives