【问题标题】:Command line argument: 95 -> 1995 and 15 -> 2015 [closed]命令行参数:95 -> 1995 和 15 -> 2015 [关闭]
【发布时间】:2018-04-25 02:49:32
【问题描述】:

如果我的命令行参数输入是介于3299 之间的数字,我想将其保存为变量int year = Integer.parseInt(args[0])+1900;,因此year 将介于19321999 之间。

如果我的命令行参数输入是介于015 之间的数字,我想将其保存为同一个变量,但year 现在将介于20002015 之间。

我已经在使用tryexcept 来捕获NumberFormatException,所以如果输入不是整数,那应该不会成为问题。

我无法通过使用ifelse ifelse 来解决这个问题,因为Java 不允许我在if 语句之后使用year,我需要它计算另一个变量。那么还有其他更好的方法吗?

【问题讨论】:

  • 我对这个问题投了反对票,因为它是一个零努力的需求转储。如果您可以 edit 您的问题向我们展示您的尝试 Minimal, Complete, and Verifiable example,或准确地澄清您遇到困难的地方,此反对票可能会被撤回。

标签: java command-line-arguments


【解决方案1】:

您应该提供一些代码来显示您的尝试。

但听起来您在变量范围界定方面遇到了问题。您很可能需要在任何 try 或 if 语句之外声明您的 year 变量,以便您可以在方法中的其他位置使用它。

例如,这将不起作用。

try {
    // We're declaring this variable in the try block
    // so it can only be used in the try block
    int year = Integer.parseInt(args[0])+1900;
} catch (...) {
    ...
}
if (/* some boolean statement with year */) { ... }

但这会

// Here we declare it outside the try and if so we can use it in both
int year = 0;
try {
    year = Integer.parseInt(args[0])+1900;
} catch (...) {
    ...
}
if (/* some boolean statement with year */) { ... }

【讨论】:

    【解决方案2】:

    我建议你先解析,如果需要再添加100

    int year = Integer.parseInt(args[0])+1900;
    if (year < 1916) {
        year += 100;
    }
    

    我看不出 Java 不允许这样做。

    【讨论】:

    • 非常感谢!我没有想到这一点,所以因为我在if-statement 之外声明了变量,所以即使它没有进入if,我也可以使用它,对吧?
    • "...能够使用它...?" : 正确的!很高兴为您提供帮助 - 如果这对您有所帮助,请随时将答案标记为正确 :)
    猜你喜欢
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 2016-03-25
    • 2015-02-19
    • 2010-10-26
    • 2013-06-22
    相关资源
    最近更新 更多