将Java参数值分配给变量[关闭]。

问题描述 投票:-1回答:2

在一个Java程序中,我需要给程序中的变量分配命令行参数值。

例如,命令行有以下参数name=Stan age=50。

该程序有2个变量name和age,我需要将参数的值分配给相应的变量。

我需要将参数的值赋值给相应的变量,可以传递的参数数量是可变的。

有没有一种简单的方法来完成赋值

谢谢你

java
2个回答
2
投票

正如Federico所提到的那样,如果有了一个 Map 但我不确定你是否已经达到了可以使用 Map. 因此,我在下面的例子中使用了数组。

public class Main {
    public static void main(String[] args) {
        String name = "";
        int age = 0;
        // Loop through all the arguments
        for (String s : args) {
            // Split each argument on '='
            String[] parts = s.split("=");
            // The name of the variable is the first part while the second part is value
            if (parts[0].equalsIgnoreCase("name")) {
                name = parts[1];
            } else if (parts[0].equalsIgnoreCase("age")) {
                try {
                    age = Integer.parseInt(parts[1]);
                } catch (NumberFormatException e) {// Handle exception in case of non-integer
                    System.out.println("Age must be an integer");
                    // ...
                }
            }
        }

        // Process (e.g. display) name and age
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

一个样本运行。

Name: Stan
Age: 50
© www.soinside.com 2019 - 2024. All rights reserved.