首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我需要代码来计算程序每次运行时随机生成的类中方法中的变量

我需要代码来计算程序每次运行时随机生成的类中方法中的变量
EN

Stack Overflow用户
提问于 2016-01-25 05:44:32
回答 1查看 28关注 0票数 0

我是否可以在每次变量选择为1或每次变量选择为2时进行计数,然后将每次计数生成的总次数相加?

罗斯·杰拉德正在喝咖啡

罗斯·杰拉德:在工作

罗斯·杰拉德:吃零食

罗斯·杰拉德:在工作

罗斯·杰拉德:和狗一起玩

罗斯·杰拉德:照镜子

罗斯·杰拉德:做柔术

罗斯·杰拉德:和狗一起玩

罗斯·杰拉德:吃零食

罗斯·杰拉德:行走

罗斯·杰拉德:吃零食

罗斯·杰拉德:玩任天堂

罗斯·杰拉德:和狗一起玩

罗斯·杰拉德:歌唱

罗斯·杰拉德:行走

罗斯·杰拉德:亲吻他的女朋友

罗斯·杰拉德:在工作

罗斯·杰拉德:游泳

罗斯·杰拉德:玩任天堂

Ross Gerard正在研究Java

代码语言:javascript
复制
import java.util.Random;
class student 
{
 public void studentIsDoing()
{
    for (int counter = 0; counter < 20; counter++)
    {
    Random r = new Random();

    int choice = 1 + r.nextInt(15);
    String response = "";

    if ( choice == 1 )
        response = "Playing with a ball";
    else if ( choice == 2 )
        response = "Studying Java";
    else if ( choice == 3 )
        response = "Kissing his girlfriend";
    else if ( choice == 4 )
        response = "Swimming";
    else if ( choice == 5 )
        response = "Doing Jiu-Jitsu";
    else if ( choice == 6 )
        response = "Reading a paper";
    else if ( choice == 7 )
        response = "Singing";
    else if ( choice == 8 )
        response = "Primping in the mirror";
    else if ( choice == 9 )
        response = "Taking a Shower";
    else if ( choice == 10 )
        response = "Eating a snack";
    else if ( choice == 11 )
        response = "Drinking some coffee";
    else if ( choice == 12 )
        response = "Walking";
    else if ( choice == 13 )
        response = "Playing with the dogs";
    else if ( choice == 14 )
        response = "At work";
    else if ( choice == 15 )
        response = "Playing nintendo";
    else 
        response = "In the Bathroom";

     System.out.println( "Ross Gerard is: " + response );

    }         

}  
}
EN

回答 1

Stack Overflow用户

发布于 2016-01-25 05:52:06

首先,我建议对这种if-else条件使用switch语法。

对于您的问题,您应该在循环开始时初始化一个大小为16 (或15)的数组,并在获得选择后添加:

代码语言:javascript
复制
arr[choice]++;

在循环结束时,数组将在每个索引中保存选择的次数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34981882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档