所以我正在尝试创建一个java程序,它将生成20个学生的随机活动。然后计算他们正在做的百分比。例如:
40%的时间睡觉
步行30%的时间
在课堂上30%的时间
但是,对于三种选择,我的百分比仍为0%,而只有一种选择为5%。
app.java
input: [(I) 44like22 .cookies. ,This, /is\ ?tricky?]
"("
"I"
")"
"44"
"like"
"22"
"."
"cookies"
"."
","
"This"
","
"/"
"is"
"\"
"?"
"tricky"
"?"
( I ) 44 like 22 . cookies . , This , / is \ ? tricky ?
然后 student.java
public class app {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String initName = "John";
String lastName = "Smith";
int age = 20;
double stcount = 0;
double slcount = 0;
double clcount = 0;
double wkcount = 0;
student st1 = new student(initName, lastName, age);
for (int i = 1; i <= 20; i++);
{
String activity = st1.whatsUp1();
System.out.print(1 + " ");
System.out.println(st1.whatsUp1());
if (activity.equals(" studying")) {
stcount++;
}
if (activity.equals(" sleeping")) {
slcount++;
}
if (activity.equals(" in class")) {
clcount++;
}
if (activity.equals(" walking")) {
wkcount++;
}
}
System.out.println(" ");
System.out.println(stcount++ / 20 * 100 + "% " + "of the time the student is studying");
System.out.println(slcount++ / 20 * 100 + "% " + "of the time the student is reading");
System.out.println(clcount++ / 20 * 100 + "% " + "of the time the student is walking");
System.out.println(wkcount++ / 20 * 100 + "% " + "of the time the student is in class");
}
}
答案 0 :(得分:4)
您的错误就在这一行
for (int i = 1; i <= 20; i++);
for,if,else,而line不应该以&#34 ;;&#34;结束。 (分号),因为那样你的for循环将从1到20计数但不执行以下{}
语句及其子语句。
例如:
for(int i = 1; i <= 20; i++); {
System.out.println("ouch");
}
此代码看起来像打印ouch 20次,但事实上它只执行一次,因为它相当于简单:
for(int i = 1; i <= 20; i++) {
};
{
System.out.println("ouch");
}
是的,你可以把{}
放在任何地方来包装一个语句,它很少有意义,这就是为什么编译器不会因编译时错误而烦恼的原因。代码仍然会被执行(确切地)一次,这对于不太熟悉java语法的人来说是一个耗时的错误。
答案 1 :(得分:0)
错误在以下几行:
System.out.println(stcount++/20 * 100 + "% "+ "of the time the student is studying");
罪魁祸首是整数除法:stcount是一个除以20的整数,它也是一个整数。然后,Java将生成一个也是整数的变量。它通过剥离小数部分来实现这一点,例如。如果stcount是10那么它会做10/20 = 0.5,这将变为0!您需要确保它不会通过使用浮点除法变为整数,这可以通过简单地确保其中一个是浮点数来完成:stcount++/20.0
答案 2 :(得分:-2)
将.0放在整数20的末尾,或在其末尾附加'd'。
你有这个
System.out.println(stcount++/20 * 100 + "% "+ "of the time the student is studying");
你应该
System.out.println(stcount++/20.0 * 100 + "% "+ "of the time the student is studying");
OR
System.out.println(stcount++/20d * 100 + "% "+ "of the time the student is studying");