所以,
这个问题很基本。在下面的代码中,当我将命令行参数作为java CommandLineDemo 3 5 *
传递时,将列出当前目录中的文件名。在谷歌做一些研究我发现我们应该在命令行中提供*
'*'
。
我的问题是,如何修改我的代码,使其在命令行中接受'*'
并执行operand1
和operand2
的产品
class CommandLineDemo {
public static void main(String[] args) {
int operand1 = Integer.parseInt(args[0]);
int operand2 = Integer.parseInt(args[1]);
char theOperator = args[2].charAt(0);
System.out.print(args[0] + args[2] + args[1] + " = ");
switch(theOperator) {
case ('+'):
System.out.println(operand1 + operand2); break;
case ('-'):
System.out.println(operand1 - operand2); break;
case ('*'):
System.out.println(operand1 * operand2); break;
case ('/'):
System.out.println(operand1 / operand2); break;
default:
System.out.println("Invalid Operator selected");
}
}
}
答案 0 :(得分:1)
您可以尝试使用以下修改后的代码将命令行参数作为单个字符串传递(例如:“2 3 +”)。
import java.util.Arrays;
class CommandLineDemo {
public static void main(String[] args) {
String strArray = Arrays.toString(args);
strArray = strArray.replace("[", "").replace("]", "").replaceAll("[, ]", "");
String[] splits = strArray.split("");
int operand1 = Integer.parseInt(splits[1]);
int operand2 = Integer.parseInt(splits[2]);
char theOperator = splits[3].charAt(0);
System.out.print(splits[1] + " " + splits[3] + " " + splits[2] + " = ");
switch(theOperator) {
case ('+'):
System.out.println(operand1 + operand2); break;
case ('-'):
System.out.println(operand1 - operand2); break;
case ('*'):
System.out.println(operand1 * operand2); break;
case ('/'):
System.out.println(operand1 / operand2); break;
default:
System.out.println("Invalid Operator selected");
}
}
}
用法&输出如下:
C:\Users\sarath_sivan\Desktop>java CommandLineDemo "2 3 +"
2 + 3 = 5
C:\Users\sarath_sivan\Desktop>java CommandLineDemo "2 3 -"
2 - 3 = -1
C:\Users\sarath_sivan\Desktop>java CommandLineDemo "2 3 *"
2 * 3 = 6
C:\Users\sarath_sivan\Desktop>java CommandLineDemo "2 3 /"
2 / 3 = 0
C:\Users\sarath_sivan\Desktop>java CommandLineDemo "2 3 a"
2 a 3 = Invalid Operator selected
C:\Users\sarath_sivan\Desktop>
答案 1 :(得分:0)
*
是shell中的元字符,这意味着它具有特殊含义。因此,您需要使用\
转义它,无需修改代码,只需键入\*
即表示*
答案 2 :(得分:0)
您无需延长程序。将*
作为'*'
传递是因为如果直接传递*
,shell(或更确切地说,Linux shell,对Windows cmd:p知之甚少)将执行file name expansion,它将作为当前目录中的所有文件进行扩展。 '*'
阻止此操作并将*
作为命令行参数传递给您的程序。