gpt4 book ai didi

java - 比较输入文件列表中的数字

转载 作者:行者123 更新时间:2023-11-30 11:35:17 25 4
gpt4 key购买 nike

我正在学习 java 并且很难应对这一挑战。我搜索了我的书和此处的有用链接,但没有找到与我正在做的事情相关的任何内容。

挑战是在记事本文件中创建一个数字列表。 java 程序必须导入数字,比较每个数字,然后打印出列表中的最小值。

在此输入验证码

这是我的代码

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

/**
Aaron Moores
March 2, 2013
Input: Numbers file
Output: Highest number, lowest number
*/

public class LargenSmall
{
public static void main(String[] args) throws IOException
{
String filename; //Numbers file
double lowest;

//Open the file
File file = new File("Number.txt");
Scanner inputFile = new Scanner(file);

lowest = 0.0;

//Read all the values in Numbers file and find the lowest value
while (inputFile.hasNext())
{
//Read a number in the file
double number = inputFile.nextDouble();
lowest = < number;
}

//Close file
inputFile.close();

//Print out lowest value in the list
System.out.println("The lowest number in your file called, " +
"Numbers.txt is " +lowest);
}
}

我的问题是弄清楚如何格式化比较每个值以存储最低值的代码行。如果我将 (lowest = lowest < number) 更改为 (lowest = lowest + number) 并添加一个累加器,程序将添加我文件中的所有值并显示它们,所以我知道程序的导入部分有效。我只是不清楚如何制定比较语句以使其显示最低值。

请帮帮我,我很难过。谢谢

最佳答案

首先,将 lowest 初始化为正无穷大,使其大于任何输入:

double lowest = Double.POSITIVE_INFINITY;

在循环中,只需取 lowest 和输入中较小的一个:

lowest = Math.min(lowest, number);

关于java - 比较输入文件列表中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15187143/

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