2016-12-10 13 views
1

我的代碼下面的工作正常,除了最小值。我無法弄清楚爲什麼最小值保持打印爲零?其拉動的.txt文件中的數字是:2 6 9 35 2 1 8 8 4.它就好像它不識別數字[0] = 2。但是,max是否正常工作,其相同的代碼剛剛顛倒過來?任何幫助表示讚賞。數組中最小值保持打印0? Java(但在.txt文件中沒有零作爲數字)

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 
+0

爲什麼外部'while'循環是循環?如果內層循環確保外層循環不會第二次迭代,它何時會循環回去? – Andreas

回答

3

這是因爲你的min的起始值爲0,而是將其設置爲Integer.MAX_VALUE,你將得到一個合適的最小值。

+0

謝謝。這樣可行。 – jeblacker

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也不起作用。爲確保最小值和最大值都正確,請按上面所述初始化最小值,並將最大值初始化爲

max = Integer.MIN_VALUE; 
+0

謝謝,它只能逆轉。 max = Integer.MIN_VALUE; min = Integer.MAX_VALUE;如果我這樣做,另一種方式我得到在java中使用的最大和最小的數字 – jeblacker

+0

@jeblacker是的。 oops:P我的壞 – ItamarG3

相關問題