日期:2014-05-20 浏览次数:20694 次
import java.util.Scanner; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class Ansewer25 { public static void main(String[] args) { StringBuffer sbf=new StringBuffer(); int[] scores=new int[5]; inputScore(scores); int[] temp=viewScore(storeScores(scores)); Arrays.sort(temp); for(int i=temp.length-1;i>=0;i--) { sbf.append(String.valueOf(temp[i])).append(" "); } System.out.println("输入的成绩从高到低的排列为:"+sbf.toString()); System.out.println("平均每科平均成绩为:"+avgScore(scores)); } public static void inputScore(int[] scores) { System.out.println("请输入5个学生的成绩:(0-100的整数)"); for(int i=0;i<5;i++) { Scanner sc=null; sc=new Scanner(System.in); if(sc.hasNextInt()) { int n=sc.nextInt(); if(n>=0&&n<=100) { scores[i]=n;; } else { System.out.println("输入不合法,请重新输入!"); i--; } if(i<scores.length-1) { System.out.println("请输入下一个学生的成绩!"); } } else { System.out.println("输入不合法,请重新输入!"); i--; } } } public static File storeScores(int[] scores) { PrintStream ps=null; File file=new File("d:"+File.separator+"data.txt"); FileOutputStream foutput=null; try { foutput=new FileOutputStream(file); ps=new PrintStream(foutput); for(int i:scores) { ps.println(i); } }catch(Exception e) { e.printStackTrace(); } finally { try { ps.close(); foutput.close(); } catch(Exception e) { e.printStackTrace(); } } return file; } public static int[] viewScore(File file) { BufferedReader br=null; int[] tempInt=new int[5]; FileInputStream finput=null; String temp=null; int n=0; if(file.exists()) { try { finput=new FileInputStream(file); br=new BufferedReader(new InputStreamReader(finput)); while((temp=br.readLine())!=null) { tempInt[n++]=Integer.parseInt(temp); } } catch(Exception e) { e.printStackTrace(); } finally { try { br.close(); finput.close(); } catch(Exception e) { e.printStackTrace(); } } } else { System.out.println("文件不存在!"); } return tempInt; } public static int avgScore(int[] temp) { int total=0; for(int i:temp) { total+=i; } return total/temp.length; } }