gpt4 book ai didi

java - 使用递归求最小值

转载 作者:行者123 更新时间:2023-12-02 07:53:30 25 4
gpt4 key购买 nike

好的,所以我需要继续获取用户输入,直到他们输入 0。我需要将它们存储在一个数组中并打印出最小值。但它继续给我给出的最后一个输入数字,而不是排序并获取列表中的最小值。这是我到目前为止所做的事情。

import java.io.*;
import java.util.*;

public class FindingMin
{

public static void main(String[] args) throws IOException
{
int[] Numbers = new int[100];
int minimum = 0;
int InputParser;
String input= "1";


try
{
InputStreamReader stream = new InputStreamReader (System.in);
BufferedReader scan = new BufferedReader(stream);

InputParser = Integer.parseInt(input);

while(InputParser != 0)
{
input = scan.readLine();
InputParser = Integer.parseInt(input);
for(int i = 0;i<Numbers.length;i++)
{
if(InputParser == 0)
{
InputParser = 0;
}
else
Numbers[i] = InputParser;

}

}

minimum = findingMin(Numbers,Numbers[0],Numbers.length-1);
System.out.println("The minimum number is "+minimum);


}
catch(NumberFormatException exception)
{
System.out.println("Please enter integers only");
}

}

public static int findingMin(int[] list, int start, int end)
{
if (start == end)
return list[start];
else
{
int Min = findingMin(list, start, end-1);
if (Min < list[end])
return list[end];
else
return Min;
}


}
}

任何建议将不胜感激!

最佳答案

那是因为你有一个额外的循环:

while(InputParser != 0)
{
input = scan.readLine();
InputParser = Integer.parseInt(input);
for(int i = 0;i<Numbers.length;i++)
{
if(InputParser == 0)
{
InputParser = 0;
}
else
Numbers[i] = InputParser; // <-- you set all numbers
// to the last input here

}

}

正确的版本是:

int i = 0;
while(InputParser != 0)
{
input = scan.readLine();
InputParser = Integer.parseInt(input);
if(InputParser == 0)
{
InputParser = 0;
}
else
{
Numbers[i] = InputParser;
i++;
}
}

此外,调用方法应该是:

minimum = findingMin(Numbers,0,Numbers.length-1);

不是

minimum = findingMin(Numbers,Numbers[0],Numbers.length-1);

关于java - 使用递归求最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9934772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com