0

数値を取る配列があります。私の方法の 1 つは、配列内の正の数の数を数えることです。したがって、プログラムを終了するために 2 3 4 5 6 と 0 を入力すると、Positive Numbers: 5 が出力されるはずですが、代わりに Positive Numbers : 4 が出力されます。最後の数字が抜けています。ただし、 2 3 4 5 -1 4 0 {0 終了} を実行すると、正の数の正しい数 (この場合は 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(); //<--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 に答える