0

我有一个带数字的数组。我的一种方法是计算数组中正数的数量。因此,如果他们输入 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);     
    }
 } 
4

3 回答 3

0

您在此处向我们展示的代码有效且有效。

在调用它之前尝试输出数组中的值以查看它们是什么。

例如,如果您的输入是一个名为 numbers 的数组,请在代码的前面添加:

for ( int i=0; i < numbers.length; i++)
{
    System.out.println(numbers[i]);
}

并尝试仔细查看阵列中发生的情况。

此外,请确保在调用 countPositive 时输入:

countPositive(numbers, 0, numbers.length - 1)

并确保你没有用错误的输入切断任何东西。

于 2013-11-08T21:41:15.490 回答
0

在您的代码中

String line = buffRead.readLine();

while (line.equals("0") == false && i < 100) {
    i++;
    line = buffRead.readLine();
    nums[i] = Integer.parseInt(line);
}

您忽略了用户给出的第一个数字。如果不是0你应该把它放在数组中,而是你正在读取下一个值。试试这种方式

String line = buffRead.readLine();

while (line.equals("0") == false && i < 100) {
    nums[i] = Integer.parseInt(line);
    i++;
    line = buffRead.readLine();
}
于 2013-11-08T21:51:12.070 回答
0

输入的第一个数字不会包含在数组中(请参阅我的嵌入式评论)

String line = buffRead.readLine(); //<--read a line...

while (line.equals("0") == false && i < 100) {
    i++;
    line = buffRead.readLine(); <-- read another line, what happened to the last line?
    nums[i] = Integer.parseInt(line);
}
System.out.println("The total count of positive numbers is  " + countPositive(nums, 0, nums.length - 1));
于 2013-11-08T21:52:45.880 回答