命令行参数:95 -> 1995 和 15 -> 2015
Command line argument: 95 -> 1995 and 15 -> 2015
如果我的命令行参数输入是 32
和 99
之间的数字,我想将其保存为变量 int year = Integer.parseInt(args[0])+1900;
,所以 year
会去在 1932
和 1999
之间。
如果我的命令行参数输入是 0
和 15
之间的数字,我想将其保存为同一个变量,但是 year
现在会介于 [=] 之间19=]和2015
.
我已经在使用 try
和 except
来捕获 NumberFormatException
,所以如果输入不是整数,那应该不会成为问题。
我无法用if
、else if
和else
解决这个问题,因为java不让我使用year
在 if
语句之后,我需要它来计算另一个变量。那么还有其他更好的方法吗?
我建议你先解析,然后在需要时添加 100
int year = Integer.parseInt(args[0])+1900;
if (year < 1916) {
year += 100;
}
我不明白什么 Java 不允许这样做。
您应该提供一些代码来展示您的尝试。
但听起来您在变量作用域方面遇到了问题。您很可能需要在任何 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 */) { ... }
如果我的命令行参数输入是 32
和 99
之间的数字,我想将其保存为变量 int year = Integer.parseInt(args[0])+1900;
,所以 year
会去在 1932
和 1999
之间。
如果我的命令行参数输入是 0
和 15
之间的数字,我想将其保存为同一个变量,但是 year
现在会介于 [=] 之间19=]和2015
.
我已经在使用 try
和 except
来捕获 NumberFormatException
,所以如果输入不是整数,那应该不会成为问题。
我无法用if
、else if
和else
解决这个问题,因为java不让我使用year
在 if
语句之后,我需要它来计算另一个变量。那么还有其他更好的方法吗?
我建议你先解析,然后在需要时添加 100
int year = Integer.parseInt(args[0])+1900;
if (year < 1916) {
year += 100;
}
我不明白什么 Java 不允许这样做。
您应该提供一些代码来展示您的尝试。
但听起来您在变量作用域方面遇到了问题。您很可能需要在任何 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 */) { ... }