简体   繁体   English

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

[英]How to get variables from the command line in Java?

I've finished writing a java program about a drinksBot. 我已经完成了一个关于DrinksBot的Java程序。 I just have one issue; 我只有一个问题。 I need two variables from the command line to be saved as int variables eg. 我需要从命令行中将两个变量另存为int变量。

The user types in: 用户输入:

java DrinksBot 30 40 java DrinksBot 30 40

and the program begins to run, and saves 程序开始运行并保存

int cupStock=  30;

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

Any help would be greatly appreciated; 任何帮助将不胜感激; I'm new to this! 我是新来的!

My code begins like this: 我的代码是这样开始的:

  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.);

... continues to run rest of program etc. ...继续运行程序的其余部分等。

Read it from args[] array in main method. 从main方法的args[]数组中读取它。 The variables passed in command line get assigned to String array defined in the main method. 在命令行中传递的变量将分配给main方法中定义的String数组。

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.);
}

run as java DrinksBot 30 40 where the 30 is cupStock and the 40 is shotStock java DrinksBot 30 40身份运行,其中30是cupStock,40是ShotStock

Update: 更新:

to get the value as integer just convert the string to int 要获取整数值,只需将字符串转换为int

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

Command line arguments are stored in the args array passed to the main method. 命令行参数存储在传递给main方法的args数组中。 The first argument is the first element args[0] , the second is args[1] and so on. 第一个参数是第一个元素args[0] ,第二个args[1]args[1] ,依此类推。 Since the elements are of type String , you can convert to int using Integer.parseInt(String) : 由于元素的类型为String ,因此可以使用Integer.parseInt(String)转换为int

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

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

Of course you should validate the input before doing this by checking the length of the array, otherwise an exception would occur: 当然,您应该在执行此操作之前通过检查数组的长度来验证输入,否则会发生异常:

if(args.length < 2) {
   // print a message to the user and exit
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM