[英]how do I find the smallest number in a text file? (Java)
I have written code for a program meant to have the user input a text file and an output file, then the program must read each line in the input file to find the smallest number.我为一个程序编写了代码,该程序旨在让用户输入一个文本文件和一个输出文件,然后该程序必须读取输入文件中的每一行以找到最小的数字。 The output is supposed to have the smallest number followed by "<== smallest number".输出应该具有最小的数字,后跟“<== 最小的数字”。 When I run it the smallest number ends up being the last number in the text file every time当我运行它时,最小的数字每次都会成为文本文件中的最后一个数字
This is the code I have so far:这是我到目前为止的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class FindSmallest {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.print("Your input file: ");
String inputFileName = console.next();
System.out.print("Your output file: ");
String outputFileName = console.next();
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
double smallNum = in.nextDouble();
while(in.hasNextDouble()){
double number = in.nextDouble();
if (number < smallNum); {
smallNum = number;
}
}
System.out.println(smallNum);
//out.printf("%8.2f <== smallest number", smallNum);
in.close();
out.close();
}
}
You have a typo, remove the ';'你有一个错字,删除';' right after the if (number < smallNum)
.在if (number < smallNum)
。 The ;
;
after the if
causes the `smallNum = number;'在if
导致 `smallNum = number;' 之后instruction to run irrespective of the condition.不考虑条件运行的指令。
You can also use import java.io.您也可以使用 import java.io。 ; ; instead of importing specific libraries to shorten your code.而不是导入特定的库来缩短您的代码。 " " calls up all the libraries in the specified import. " " 调用指定导入中的所有库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.