返回数字,但它们打印为0

时间:2013-03-30 01:03:51

标签: java arrays recursion printing return

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

注意:首先我将maximum,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

1 个答案:

答案 0 :(得分:1)

当您打印出

行中的值时
System.out.println("The maximum number is " + fmt.format(max));

您永远不会将max变量分配给assignment9方法中的任何内容。当然,你可以致电findMax,但在此之前你永远不会说max = findMax(...)。因为你通过传递0在main中调用它,所以它打印出来的东西。

你的max函数中还有其他一些错误,但这就是它总是打印0的原因。