数组排序输入

我使用数组排序输入重新获得帮助。 所以故事是下一个我正在制作一个代码来输入候选人的投票号码(其中有5个)并输出每个候选人的投票数量。 它也需要在输入-1时终止。 我已经计算了所有排序和交换function,并且实际输入代码存在问题。 我到目前为止所做的不对,但它可能会给你一个想法。

import java.util.*; public class VoteCount { public static void main(String[] args) { //create empty array int[] votes = new int[5]; //input data input(votes); } public static void input(int[] votes) { Scanner kybd = new Scanner(System.in); System.out.println("Enter vote number of the candidate results: "); int votecount = kybd.nextInt(); while (votecount !=-1) { votes[votecount]++; System.out.println("Candidate" + votes +"Has" +votecount + "votes"); } } } 

你似乎已经创建了一个无限循环的原因,因为你永远不会在循环中改变它,因此votecount永远不会等于-1。

您需要做的是将代码移动到您要求的位置并在循环中记录投票。 但在进行votes[votecount]++之前votes[votecount]++检查以确保用户没有输入-1因为这会导致ArrayOutofBoundsException 。 所以你可以永远循环,当用户输入-1时你可以break循环。

以下是如何从控制台读取并填写votes数组:

 public static void main (String[] args){ String line = null; int val = 0; BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); do{ System.out.println("Usage: Enter votes. Enter -1 to exit"); int voteNumber = 0; while(voteNumber<5){ try { line = is.readLine(); val = Integer.parseInt(line); votes[voteNumber] = val; voteNumber++; } catch (NumberFormatException ex) { System.err.println("Not a valid number: " + line); System.out.println("Usage: Enter votes. Enter -1 to exit"); } } }while(val != -1); } 

我会这样做:

 import java.util.Scanner; public class VoteCount { public static void main(String[] args) { //create empty array int[] votes = new int[5]; //initialise with 0 for (int i=0; i<5; i++){ votes[i] = 0; } //input data input(votes); } public static void input(int[] votes) { System.out.println("Enter vote number of the candidate results: "); Scanner kybd = new Scanner(System.in); int votecount = kybd.nextInt(); while (votecount !=-1) { votes[votecount]++; System.out.println("Candidate " + votecount +" Has " +votes[votecount] + " votes"); System.out.println("Enter vote number of the candidate results: "); votecount = kybd.nextInt(); } } } 

现在您必须添加不允许用户输入高于4且低于-1的任何内容的function,否则您将获得exception。 祝你好运!

使用此代码您将创建一个无限循环。

相反,你应该写:

 votecount = kybd.nextInt(); // in the Loop and At End.. 

古隆是对的..