![](/img/trans.png)
[英]How to use -DApp -Dtime as name bound args to main method in java
[英]How to use main args[] to call methods in Java
我想知道是否可以通过使用main args []而不是像下面这样来调用类函数:
public class Test {
public static void main(String[] args) {
String choice="";
System.in(choice);
if (choice.contains("1"))
{
Item item = new Item();
item.function();
}
else
{
Item2 item2 = new Item2();
item2.function2();
}
}
}
并有类似的东西:
-a calls the x function
-b calls the y function
public static void main(String[] args) {
String choice=args[0];
if (choice.equals("a")) {
Item item =mFinal.new Item();
item.function();
}else{
Item2 item2 =mFinal.new Item2();
item2.function2();
}
}
在主要方法中, args
是一个数组,其中包含传递给程序的参数,因此您可以像其他Java数组一样通过索引访问其元素。
这是您需要做的:
if (args[0].contains("a")){
Item item = new Item();
item.function();
}
else if(args[0].contains("b")){
Item2 item2 = new Item2();
item2.function2();
}
当我碰到这个让我大吃一惊的句子时,我碰巧需要在我的教科书上引用有关二维数组的内容!
不需要main的参数数组的名称为args。 您可以随意命名。 但是,使用名称args是一个标准约定。
我试过了,这是真的。 也许这是常识,但我不知道。 不相信我吗? 试试吧!
import java.util.*;
public class ReverseString {
public static void main(String[] gafuydqaFUYQ) {
String userString;
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence and I will reverse in.");
userString = input.nextLine();
String a[] = userString.split(" ");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println("");
for (int i = a.length - 1; i >= 0; i--) {
System.out.print(a[i] + " ");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.