数组中的最小值是否保持打印0? Java(但.txt文件中没有零作为数字)

时间:2016-12-10 18:16:28

标签: java

我的代码工作正常,除了最小值。我无法弄清楚为什么最小值保持打印为零?它拉出的.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

2 个答案:

答案 0 :(得分:3)

这是因为你的min的起始值,它将为0.相反,将它设置为Integer.MAX_VALUE,你将得到一个适当的分钟。

答案 1 :(得分:2)

您将最小值设置为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也无法正常工作。要确保最小值和最大值都正确,请按上述说明初始化min,并将max设置为

max = Integer.MIN_VALUE;