【发布时间】:2013-11-08 21:30:32
【问题描述】:
我有一个接受数字的数组。我的一种方法是计算数组中正数的数量。因此,如果他们输入 2 3 4 5 6 和 0 来终止程序,它应该打印出正数:5,但它会打印出正数:4。它错过了最后一个数字。但是,如果我执行 2 3 4 5 -1 4 0 {0 terminates},它会打印出正确数量的正数,在本例中为 5。我已经进行了一些调试,但似乎无法弄清楚。有什么帮助吗?
public static void main (String args[]) throws IOException
{
int i = 0;
int [] nums;
nums = new int [100];
InputStreamReader inRead = new InputStreamReader(System.in); //
BufferedReader buffRead = new BufferedReader(inRead);
String line = buffRead.readLine();
while (line.equals("0") == false && i<100)
{
i++;
line = buffRead.readLine();
nums[i]=(int) Double.parseDouble(line);
}
System.out.print ("The minimum number is " + findMin (nums, 0, nums.length - 1) + ('\n'));
System.out.println("Sum of the numbers at odd indices: " + computeSumAtOdd(nums, 0 , nums.length -1 ) + ('\n') );
System.out.println("The total count of positive numbers is " + countPositive(nums,0,nums.length -1));
}
public static int countPositive(int[] numbers, int startIndex, int endIndex)
{
if (startIndex == endIndex)
{
if (numbers[startIndex] > 0)
{
return 1;
}
else
return 0;
} else
{
if (numbers[startIndex] > 0)
{
return 1 + countPositive(numbers, startIndex +1, endIndex);
}
else
return countPositive(numbers, startIndex +1, endIndex);
}
}
【问题讨论】:
-
这段代码看起来不错。你确定输入到数组中的代码是正确的吗?同样,将带有和不带有大括号的 if else 混合在一起是一种非常糟糕的编码实践,不要两者都做。
-
我感觉您的 endIndex 计算不正确。看看它的调用是什么。
-
System.out.println("正数总数为" + countPositive(nums,0,nums.length -1));
-
我告诉过你before,这段代码似乎运行良好。您的问题可能在其他地方。你能告诉我们你是如何从用户那里读取和存储数据并使用这种方法的吗?
-
第一次进入函数的值是什么?