gpt4 book ai didi

java - 数组中的最小值一直打印 0? Java(但 .txt 文件中没有零作为数字)

转载 作者:行者123 更新时间:2023-11-29 07:31:51 24 4
gpt4 key购买 nike

除了最小值,我的下面代码工作正常。我不明白为什么最小值一直打印为零?它从中提取的 .txt 文件中的数字是:2 6 9 35 2 1 8 8 4。就好像它没有识别出数字 [0] = 2。但是 max 工作正常并且它的相同代码只是颠倒了?感谢您的帮助。

import java.io.*;

import java.util.*;

class Thirteen{
public static void main(String [] args) throws IOException{

int count = 0;

Scanner keys = new Scanner(System.in);
Scanner keystwo;

System.out.println("Please enter an input file name");
String filename = keys.next();
File infile = new File(filename);
keystwo = new Scanner(infile);

System.out.println("Please enter an output filename");
String outputfile = keys.next();
File outfile = new File(outputfile);

FileOutputStream outstream = new FileOutputStream(outfile);
PrintWriter display = new PrintWriter(outstream);


while(keystwo.hasNext()){

count++;
int numbers [] = new int [count];
int max = numbers[0];
int min = numbers[0];
int average = 0 ;
int sum = 0;
int counttwo = 0;

while(keystwo.hasNext()){
counttwo++;
//add numbers to array
for(int A = 0; A < numbers.length; A++){
numbers[A] = keystwo.nextInt();
sum = sum+ numbers[A];
}
// output numbers into txt file
for(int item : numbers){
display.println(item);
}
for(int C: numbers){
if(C < min){
min = C;
}
}
for(int B : numbers){
if(B > max){
max = B;
}
}

average = sum / counttwo;
}//end while

System.out.println("The total numbers in the array: " + counttwo );
System.out.println("The maximum value is: " + max);
System.out.println("The minimum value is: " + min);
System.out.println("The average value is: " + average);
display.println("The total numbers in the array: " + counttwo );
display.println("The maximum value is: " + max);
display.println("The minimum value is: " + min);
display.println("The average value is: " + average);
}//end first while

keystwo.close();

display.close();

}
}//end

最佳答案

这是因为您的 min 起始值将为 0。相反,将其设置为 Integer.MAX_VALUE,您将获得合适的最小值。

关于java - 数组中的最小值一直打印 0? Java(但 .txt 文件中没有零作为数字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41078725/

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