Java 如何在循环中组合if语句
我有这个类,在printVoces方法中,我每次都必须执行if语句来打印每个投票。是否有任何方法可以合并这两个if语句。我能打印出所有候选人的名字和他们同时获得的票数吗Java 如何在循环中组合if语句,java,loops,Java,Loops,我有这个类,在printVoces方法中,我每次都必须执行if语句来打印每个投票。是否有任何方法可以合并这两个if语句。我能打印出所有候选人的名字和他们同时获得的票数吗 public class TestCandidate { public static void main(String[] args) { Canidate[] canidate = new Canidate[5]; // create canidate cani
public class TestCandidate {
public static void main(String[] args)
{
Canidate[] canidate = new Canidate[5];
// create canidate
canidate[0] = new Canidate("John Smith", 5000);
canidate[1] = new Canidate("Mary Miller", 4000);
canidate[2] = new Canidate("Michael Duffy", 6000);
canidate[3] = new Canidate("Tim Robinson", 2500);
canidate[4] = new Canidate("Joe Ashtony", 1800);
printVotes(canidate) ;
}
public static void printVotes(Canidate [] List)
{
double max;
int index;
if (List.length != 0)
{
index = 0;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
}
if (List.length != 0)
{
index = 1;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
return;
}
}
}
公共类TestCandidate{
公共静态void main(字符串[]args)
{
Canidate[]Canidate=新Canidate[5];
//创建日期
canidate[0]=新的canidate(“约翰·史密斯”,5000);
canidate[1]=新的canidate(“玛丽·米勒”,4000);
canidate[2]=新的canidate(“Michael Duffy”,6000);
canidate[3]=新的canidate(“Tim Robinson”,2500);
canidate[4]=新的canidate(“乔·阿什托尼”,1800年);
打印投票(日期);
}
公共静态无效打印投票(Canidate[]列表)
{
双峰;
整数指数;
如果(List.length!=0)
{
指数=0;
for(int i=1;i
如果您通过了候选名单
并假设每个候选人都有一个列表投票
:
List<Integer> votes= new ArrayList<Integer>() ;
for(Candidate c:candidates)
{
votes.add(c.GetVote()) ;
}
for(Integer v:votes)
{
System.out.println(v);
}
List vows=new ArrayList();
(候选人c:候选人)
{
添加(c.GetVote());
}
for(整数v:投票数)
{
系统输出打印Ln(v);
}
您可以像这样重写候选者
类的toString()
方法:
public String toString() {
return "Candidate Name: " + this.name + "\nVotes: " + this.votes;
}
然后,您的printVotes
方法将如下所示:
public static void printVotes(Candidate[] list) {
for(Candidate c : list) {
System.out.println(c);
}
}
正如其他人提到的,避免在变量名中使用大写字母,尤其是在使用诸如List之类的单词的情况下。列表是一种集合类型,很容易混淆。在Java中最好不要将变量名大写。尤其是因为有这么多的
列表
类型。为什么不使用for循环在您的printVotes(canidate)
5次呢?每次发送不同的数组索引值。这两个控制流之间的区别是什么?是的,我想打印所有候选人的名字以及他们的选票@t第二个索引为1,第一个索引为0@刘易斯·瑟里尼斯:有没有办法让我遍历姓名和选票,然后打印出来?@user2337902为什么之后还要打印出来?我的意思是,在遍历所有这些之后,我应该返回那个数字@LonenebulaSo你想循环所有候选人的选票,循环后打印每张选票?“什么号码?”是的,这就是我的意思。@Lewsterin