gpt4 book ai didi

java - 计数结果错误

转载 作者:行者123 更新时间:2023-12-01 13:49:22 24 4
gpt4 key购买 nike

我正在编写一个程序,计算每个类(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com