我正在编写一个程序,计算每个类(class)(音乐、艺术、戏剧、体育)的学生总数。如果我有 3 个学生,其中两个学生上艺术课,一个学生上音乐课,那么结果应该是:艺术 -2 和音乐 -1。我得到了错误的结果。
评论:第一代表音乐类,第二代表艺术。
结果:
插入参与者人数: 3 将学生插入类: 2 类(class)学生:2 总数:1 类(class)学生:4人 总计:0 将学生插入类: 2 类(class)学生:2 总数:3 类(class)学生:4人 总数:1 将学生插入类: 1 类(class)学生:1 总数:1 类(class)学生:4人 总计:2
我的代码:
导入java.util.Scanner; 公开课小组 Activity { 公共(public)静态无效主()
{
Scanner GActivity=new Scanner(System.in);
System.out.println("Insert numbers of participants:");
int participantNo= GActivity.nextInt();//Insert numbers of participants
int music= 1;int art=2; int theatre= 3; int sport= 4; // Representation of each class by numbers.
int countM=0; //This variable contains the number of the participants in music class.
int countA=0; //This variable contains the number of the participants in art class.
int countT=0; //This variable contains the number of the participants in theatre class.
int countS=0; //This variable contains the number of the participants in sport class.
for(int i=0;i<participantNo;i++)
{
System.out.println("Insert student in class:");
int p= GActivity.nextInt();// // Representation of student by number.
if(p==music)
{
countM++;
System.out.println("student in class:"+music);
System.out.println("Total:"+countM++);
}
else if(p==art)
{
countA++;
System.out.println("student in class:"+art);
System.out.println("Total:"+countA++);
}
else if(p==theatre)
{
countT++;
System.out.println("student in class:"+theatre);
System.out.println("Total:"+countT++);
}
else
countS++;
System.out.println("student in class:"+sport);
System.out.println("Total:"+countS++);
}
}
}
最佳答案
else
countS++;
System.out.println("student in class:"+sport);
你缺少大括号!您的代码有效地运行如下:
else {
countS++;
}
System.out.println("student in class:"+sport);
在else
后面添加大括号来解决问题。
此外,正如泰勒在评论中指出的那样,每添加一个学生,音乐课计数器就会增加两次,而不是一次。
编辑:因为显然只是说还不够清楚,这里有一些代码来演示:
countS++; //countS is incremented by one
System.out.println("student in class:"+sport);
System.out.println("Total:"+countS++); //countS is incremented by one AGAIN
所以你的学生人数增加了一倍。但是,由于 countS++
的计算结果为 countS
,第一次执行此操作时,打印消息显示正确 - 但 countS
的值仍然会发生更改在下一次迭代中会产生错误的结果。
关于java - 计数结果错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20083531/