日期:2014-05-20 浏览次数:20955 次
import java.util.Scanner; /* * 给定n个整数,求出其中k个最大的数 */ public class Temp { private int k; private int n; private int[] intInputArray; private int[] intSomeMaxNumbersArray; private Scanner sca; public Temp() { System.out.println("this is temp constructor!"); this.setN(); this.setK(); this.intInputArray = new int[this.getN()]; this.intSomeMaxNumbersArray = new int[this.getK()]; this.initIntInputArray(); sca = new Scanner(System.in); } public int getK() { return k; } public void setK() { System.out.println("Input k:"); k = sca.nextInt(); } public int getN() { return n; } public void setN() { System.out.println("Input n:"); n = sca.nextInt(); } private void initIntInputArray() { System.out.println("Input IntInputArray:"); for (int i = 0; i < this.getN(); i++) { this.intInputArray[i] = sca.nextInt(); } } public void operation() { int[] minNumAndIndex = new int[2]; for (int i = 0; i < this.getN(); i++) { if (i < this.getK()) { this.intSomeMaxNumbersArray[i] = this.intInputArray[i]; } else { minNumAndIndex = this.getMinNumIndex(); if (minNumAndIndex[0] < this.intInputArray[i]) { this.intSomeMaxNumbersArray[minNumAndIndex[1]] = this.intInputArray[i]; } } } } private int[] getMinNumIndex() { int minIndex; int min; int[] minNumAndIndex = new int[2]; min = this.intSomeMaxNumbersArray[0]; minIndex = 0; for (int i = 0; i < this.getK(); i++) { if (min >= this.intSomeMaxNumbersArray[i]) { min = this.intSomeMaxNumbersArray[i]; minIndex = i; } } minNumAndIndex[0] = min; minNumAndIndex[1] = minIndex; return minNumAndIndex; } private void printResult() { for (int i = 0; i < this.getK(); i++) { System.out.println(this.intSomeMaxNumbersArray[i] + " "); } } public static void main(String args[]) { Temp temp = new Temp(); temp.operation(); temp.printResult(); } }
this.setN(); //setN用到sca this.setK(); this.intInputArray = new int[this.getN()]; this.intSomeMaxNumbersArray = new int[this.getK()]; this.initIntInputArray(); sca = new Scanner(System.in); //而sca在这里才初始化,所以setN就抛出空指针异常了