gpt4 book ai didi

java - 在java中读取文件并打印最大和最小数

转载 作者:行者123 更新时间:2023-12-01 23:57:50 24 4
gpt4 key购买 nike

我需要打印此文件中的最大和最小数字...我尝试了所有方法,但似乎无法使其工作。我是初学者请帮忙

public class Banck {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("Welcome to JEEEZBANK");

final int NUM_TO_QUIT = -99;

String userin ;
int num;

System.out.println("Enter a file ending with .txt");
Scanner scan = new Scanner(System.in);
userin = scan.nextLine();

// create file
PrintWriter file = new PrintWriter(userin);

for(int i=1; i<5; i++){
System.out.println("enter first number "+i +" or -99 to quit");
num = scan.nextInt();
if(num == NUM_TO_QUIT){
System.out.println("bye");
System.exit(0);
}
file.println(num);

}
file.close();
// read file and print smallest and biggest number
Scanner read = new Scanner(file);
while(read.hasNext()){

// add the numbers to the array
int[] numlist = {num};
// print the biggest and smallest number inside the numlist array.
}
}
}

最佳答案

一种方法是创建两个变量,其中一个跟踪当前最低数字,另一个跟踪当前最高数字。对于文件中的每个数字,比较它是否低于当前最低数字,如果是则替换它,或者如果它高于当前最高数字(如果是则替换它)。

您实际上可以在用户输入时比较和查找最小和最大数字,而不是使用单独的循环,因为我认为它们是相同的数字。

关于java - 在java中读取文件并打印最大和最小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15318901/

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