0

好的,所以我有一个我一直在研究的程序,它需要使用递归方法,并且数组编号必须是数组而不是 ArrayList。该程序的目的是允许用户输入双精度数,直到键入 0。双精度数必须存储到一个数组中,并且我必须使用递归方法找到最大值、负数的个数和正数的总和。我遇到的问题是当程序退出并打印结果时,它打印最大值并总和​​为 0 而不是答案。我已经尝试了几乎所有我能想到的但无法让它发挥作用的东西。如果有人能告诉我我的问题是什么,将不胜感激......谢谢。

注意:起初我将 max、negative 和 sum 放在 assignment9 方法中,还尝试从 main 方法打印,但似乎没有任何效果。

import java.util.*;
import java.text.*;;

public class Assignment9 {

//main method initializes variables then calls method assignment9
public static void main(String[] args)
{
    int count = 0;
    ArrayList<Double> help = new ArrayList<Double>();
    double max = 0;
    int negative = 0;
    double sum = 0;
    assignment9(help, count, max, negative, sum);

}//end main

//adds user input to array until 0 is entered; it then calls other methods
public static void assignment9(ArrayList<Double> help, int count, double max, int negative, double sum)
{
    DecimalFormat fmt = new DecimalFormat("#.##");
    double input;

    Scanner scan = new Scanner(System.in);

    input = scan.nextInt();

    if (input == 0)
    {
        double[] numbers = new double[count];
        for(int i = 0; i < numbers.length; i++)
        {
            numbers[i] = help.get(i);
        }
        findMax(numbers, count-1, max);
        countNegative(numbers, count-1, negative);
        computeSumPositive(numbers, count-1, sum);

    }else{
            help.add(input);
            count++;
            assignment9(help, count, max, negative, sum);
    }//end if
    System.out.println("The maximum number is " + fmt.format(max));
    System.out.println("The total number of negative numbers is " + negative);
    System.out.println("The sum of positive numbers is " + fmt.format(sum));
    System.exit(0);

}//end assignment9

//compares elements of array to find the max until count = -1
public static double findMax(double[] numbers, int count, double max)
{

    if (count == -1)
    {
        return max;
    }else if(numbers[count] > max){
        max = numbers[count];
        count--;
        findMax(numbers, count, max);
    }//end if
    return max;

}//end findMax

public static int countNegative(double[] numbers, int count, int negative)
{

    if(count == -1)
    {
        return negative;
    }else if(numbers[count] < 0){
        negative++;
        count--;
        countNegative(numbers, count, negative);
    }
    return negative;
}//end countNegative

public static double computeSumPositive(double[] numbers, int count, double sum)
{
     if(count == -1)
     {
         return sum;
     }else{
         sum = sum + numbers[count];
         count--;
         computeSumPositive(numbers, count, sum);
         return sum;
     }
}//end computeSumPositive

}//end class
4

1 回答 1

1

当您打印出行中的值时

System.out.println("The maximum number is " + fmt.format(max));

您永远不会将max变量分配给assignment9方法中的任何内容。当然,你可以打电话findMax,但max = findMax(...)在此之前你从来没有说过。既然你main通过传入 0 来调用它,那就是它打印出来的东西。

您的 max 函数中存在某种其他错误,但这就是它始终打印 0 的原因。

于 2013-03-30T01:19:01.877 回答