gpt4 book ai didi

java - 如何从Java中的命令行获取变量?

转载 作者:行者123 更新时间:2023-11-29 03:10:04 25 4
gpt4 key购买 nike

我已经完成了关于 drinksBot 的 java 程序的编写。我只有一个问题;我需要将命令行中的两个变量保存为 int 变量,例如。

用户输入:

Java 饮料机器人 30 40

然后程序开始运行,并保存

int cupStock=  30;

int shotStock = 40; //or whatever the user typed into the command line.

任何帮助将不胜感激;我是新手!

我的代码是这样开始的:

  import java.util.Scanner;
public class DrinksBot {

static Scanner keyboard = new Scanner (System.in);

public static void main(String[] args) {

System.out.print("Hello, what's your name? I have"+cupStock+" cups left, and " + shotStock+" shots left.);

...继续运行程序的其余部分等

最佳答案

在 main 方法中从 args[] 数组中读取它。在命令行中传递的变量被分配给在 main 方法中定义的字符串数组。

public static void main(String[] args) {
String cupStock = args[0];
String shotStock = args[1];
System.out.print("Hello, what's your name? I have"+cupStock+" cups left, and " + shotStock+" shots left.);
}

java DrinksBot 30 40 运行,其中 30 是 cupStock,40 是 shotStock

更新:

要获取整数值,只需将字符串转换为 int

int cupStock = Integer.parseInt(args[0]);
int shotStock = Integer.parseInt(args[1]);

关于java - 如何从Java中的命令行获取变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29875929/

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