由于int数据分配中的逻辑错误而打印零值

时间:2014-05-16 21:13:39

标签: java int

除最后一列数据输出外,此代码可生成准确的输出。

输出旨在显示候选人的非十进制投票百分比值。

我的逻辑错误导致上述值打印为0。

输出如下:

CandidateTester output.

public class Candidate {
    public String name;
    public int numVotes;

    public Candidate(String name, int numVotes) {
        this.name = name;
        this.numVotes = numVotes;
    }

    public String getName() {
        return name;
    }

    public int getNumVotes() {
        return numVotes;
    }

    public String toString() { 
        return getName() + " received " + getNumVotes() + " votes.";
    }
}


import java.util.*;
public class TestCandidate {
    public static void main(String [] args) {
        ArrayList<Candidate> list = new ArrayList<Candidate>();
        list.add(new Candidate("John Smith", 5000));
        list.add(new Candidate("Mary Miller", 4000));
        list.add(new Candidate("Michael Duffy", 6000));
        list.add(new Candidate("Tim Robinson", 2500));
        list.add(new Candidate("Joe Ashtony", 1800));

        System.out.println("Results per candidate:");
        System.out.println("______________________\n");

        int total = getTotal(list);
        printVotes(list);
        System.out.print("\nCandidate\t\tVotes Received\t\t% of Total Votes");
        printResults(list);
        System.out.println("\n\nTotal number of votes in election: " + total);
    }

    public static void printResults(ArrayList<Candidate> list) {
        String name = "";
        int percent = 0;
        int votes = 0;
        int total = getTotal(list);
        for(Candidate token : list) {
           name = token.getName();
           votes = token.getNumVotes();
           percent = (votes / total) * 100;
           System.out.printf("\n%1s\t%12d\t%17d", name, votes, percent);
        }
    }

    public static void printVotes(ArrayList<Candidate> list) {
        for(Candidate token : list) {
            System.out.println(token);
        }
    }

    public static int getTotal(ArrayList<Candidate> list) {
        int total = 0;
        for(Candidate token : list) {
            total += token.getNumVotes();
        }
        return total;
    }
}

1 个答案:

答案 0 :(得分:4)

您正在此处执行整数除法。

percent = (votes / total) * 100;

votes总是比total更低或更低,因此votes/total可能会因整数除法而导致0。

percent更改为double并将分部的操作数之一强制转换为double,或者如果要将percent保留为整数,则乘以{{ 1}}先用100然后除以vote

total