2013-03-10 27 views
0

我需要打印此文件中的最大和最小数字...我尝试了一切,我似乎无法使它工作。我是初学者,请帮助阅读文件并在java中打印最大和最小数字

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. 
     } 
    } 
} 
+1

看看[Math.min](http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#min(int,%20int))和[Math.min的.max](http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#max(INT,%20int)) – MadProgrammer 2013-03-10 04:30:59

回答

2

一种方法是创建两个变量,其中一个保持当前的最低数量的轨迹和其他保持当前最高的曲目。对于文件中的每个数字,比较它是否低于当前最低数字,如果是,则替换它,或者如果它高于当前最高数字(并且如果更换它)。

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

1

不要保留一个列表。使用两个变量来跟踪最大的最大值&分钟。

int min = Integer.MAX_VALUE; 

int max = 0; 

if(num < min) min = num; 

if(num > max) max = num; 

假设NUM是从在上述回路中的文件正被读取的整数。

相关问题