用户输入的数组完全是最后一个输入

时间:2017-10-03 08:49:59

标签: java

当我执行此程序时,canidateArray仅将最后一个用户输入存储为数组中的每个变量。

import java.util.Arrays;

import java.util.Collections;

import java.util.Scanner;

public class ArrayElection {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in); 
        System.out.println("Enter the number of candidates: ");
        int loops = input.nextInt();
        int loops2 = loops;
        Canidate[] canidateArray = new Canidate[loops];         
        String canidatename;
        int canidatevotes = 0;
        int outputno = 1;
        while (loops > 0){
            System.out.println("Enter " + outputno +". name:");
            canidatename = input.next();
            System.out.println("Enter votes:");
            canidatevotes = input.nextInt();
            new Canidate(canidatename, canidatevotes);
            loops = loops - 1;
            outputno = outputno + 1;
        }


        if (canidateArray[0].getVotes() == canidateArray[1].getVotes()) {
            System.out.println("The election is a tie between the following candidates: ");
            System.out.println(canidateArray[0].getName() + " (" + canidateArray[0].getVotes() + " votes)");
            System.out.println(canidateArray[1].getName() + " (" + canidateArray[1].getVotes() + " votes)");
            System.out.println(canidateArray[2].getName() + " (" + canidateArray[2].getVotes() + " votes)");
        }
        else {
            System.out.println("The winner is " + canidateArray[0].getName() + " with " + canidateArray[0].getVotes() + " votes!");
        }

    }
    public static class Canidate {
        private static String name;
        private static int votes;

        public Canidate(String name, int votes) {
            this.name = name;
            this.votes = votes;
        }

        public static String getName() {
            return name;
        }
        public static int getVotes() {
            return votes;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您不会在数组中存储任何内容。修复:

    while (loops > 0){
        System.out.println("Enter " + outputno +". name:");
        canidatename = input.next();
        System.out.println("Enter votes:");
        canidatevotes = input.nextInt();
        loops = loops - 1;
        canidateArray[outputno-1] = new Canidate(canidatename, canidatevotes);
        outputno = outputno + 1;
    }

但是你必须修复你的最后一部分代码。您可以使用

测试canidateArray[0] vs canidateArray[1]
  • 1候选人,然后它将触发IndexOutOfBoundsException
  • 或超过2名候选人