有一项任务,我是新手。赋值是计算给定数组中的负数,并打印出计算的数量。我必须使用while循环。我收到了很多错误。
class NegativeNumber {
public static void main(String[] args) {
int[] wholeNumber = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int negativeCounter = 0;
int sum;
while(counter < wholeNumber.length) {
sum = sum + wholeNumber;
if(wholeNumber < 0)
{
negativeCounter++;
}
}
System.out.println("The amount of negative numbers are "+negativeCounter);
}
}
答案 0 :(得分:3)
更改
if(wholeNumber < 0)
到
if(wholeNumber[counter] < 0)
和
sum = sum + wholeNumber;
到
sum = sum + wholeNumber[counter];
或更短的
sum += wholeNumber[counter];
并且不要忘记在循环体的末尾增加counter
counter++;
您可以使用IntStream
int[] wholeNumber = { 1, 4, 5, -2, -4, 6, 10, 3, -2 };
int sum = IntStream.of(wholeNumber).sum();
long negativeCount = IntStream.of(wholeNumber).filter(x -> x < 0).count();
System.out.printf("%s Sum=%d, Count=%d%n",
Arrays.toString(wholeNumber), sum, negativeCount);
答案 1 :(得分:2)
你必须使用wholeCounter [counter]并在最后增加计数器
答案 2 :(得分:2)
答案 3 :(得分:1)
while(counter < wholeNumber.length) {
if(wholeNumber[counter] < 0)
{
sum += wholeNumber[counter];
negativeCounter++;
}
counter++
}
答案 4 :(得分:1)
一些提示:
public class NegativeNumber {
如果您想稍后运行主方法,您的课程必须公开!
您的循环可以简化,使用用于for循环的每种样式:
for (int number : wholeNumber } {
sum = sum + number;
if(number < 0) {
negativeCounter++;
}
}
并提示:wholeNumber是一个误导性的数组名称。为什么不把它称为wholeNumber s ?!表达这个变量是关于多个数字的事实!
答案 5 :(得分:0)
您可以使用for循环
轻松完成public class NegativeNum {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] wholeNumber = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int negativeCounter = 0;
int sum=0;
for(int i =0; i<wholeNumber.length; i++)
{
if(wholeNumber[i]< 0)
{
sum =sum+ wholeNumber[i];
negativeCounter++;
}
}
System.out.println(sum + " " + negativeCounter);
}
}