[英]min value in array keeps printing 0? Java (but no zero in the .txt file as a number)
我的下面的代碼工作正常,除了最小值。 我無法弄清楚為什么最小值始終保持打印為零? 它從其中提取的.txt文件中的數字為:2 6 9 35 2 1 8 8 4.好像它沒有識別出numbers [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,您將獲得適當的min。
您正在將最小值設置為0:
min = numbers[0]; //numbers[0] is 0, since you haven't initialized it
您需要將最小值定義為:
min = Integer.MAX_VALUE; //the largest possible value that int can have, so every other int is bigger
此外,建議對您的最高費用做同樣的事情。 在這種情況下,它並不重要,但是如果您恰好在.txt
文件中包含負值,那么max
也將不起作用。 為了確保最小值和最大值都正確,請按照上述說明初始化最小值,並將最大值初始化為
max = Integer.MIN_VALUE;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.