首页 > 解决方案 > Integer.parseInt 做什么?

问题描述

我刚刚开始学习 Java,我的任务之一是通过这段代码并了解它的作用。但是,尽管咨询了许多在线资源,但我在这样做时遇到了麻烦。特别是,我仍在努力理解变量权益、目标和 num_trials 的声明。Integer.parseInt(args[0]) 是什么意思?请用非常简单的语言解释,因为我对 OOP 很陌生。

public class GamblerRuin{
    public static void main(String[] args)
    {
        int stake = Integer.parseInt(args[0]);
        int goal = Integer.parseInt(args[1]);
        int num_trials = Integer.parseInt(args[2]);

        int bets = 0;
        int wins = 0;

        for (int t = 0; t < num_trials; t++)
        {
            int cash = stake;
            while (cash > 0 && cash < goal)
            {
                bets++;
                if (Math.random() < 0.5 ) cash++;
                else                      cash--;
            }
            if (cash == goal) wins++;
        }

        System.out.println(100 * wins/num_trials + "% wins");
        System.out.println("Avg # bets: " + bets/num_trials);

    }
}

标签: java

解决方案


当您使用如下参数执行程序时:

javac GambleRuin 1 2 3

然后你的程序将通过调用 main 函数来执行。

String[] args数组将是["1","2","3"]. 由于参数始终作为字符串传递,因此您需要将它们转换为整数才能使程序正常工作,因此解析 int

警告:如果参数不是整数,则会引发异常并且您的程序将崩溃。


推荐阅读