java - 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);
}
}
解决方案
当您使用如下参数执行程序时:
javac GambleRuin 1 2 3
然后你的程序将通过调用 main 函数来执行。
String[] args
数组将是["1","2","3"]
. 由于参数始终作为字符串传递,因此您需要将它们转换为整数才能使程序正常工作,因此解析 int
警告:如果参数不是整数,则会引发异常并且您的程序将崩溃。
推荐阅读
- javascript - 通过检查对象内部字段的唯一性来创建对象的动态数组:Javascript
- javascript - 设置类值时无法设置未定义的属性
- python - 通过 CAN 总线接口的通信不起作用
- css - 使用 XSLT 和 CSS 将 XML 文件转换为 PDF(使用免费软件许可证)
- python - 逗号分隔变量的类型是什么?
- c# - 为什么一个文件中的每个连续单元测试的运行时间往往比以前的要长?
- linux - FAT 系统:msdos_create 和 msdos_mkdir 之间的区别
- c# - System.Windows.Input.Key 在 c# 中不起作用
- r - 每组 n 行的比例选择
- python - 使用 hadoop 3.2 安装 Pyspark 3.0+,df.write 错误