如何使用 main args[] 调用 Java 中的方法
How to use main args[] to call methods in Java
我想知道是否有任何方法可以通过使用 main args[] 而不是像下面这样调用 class 函数:
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
在 main 方法中,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();
}
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();
}
}
当我遇到这句话时,我刚好需要参考教科书中有关二维数组的内容!
It is not required that the name of main’s parameter array
be args. You can name it anything you wish. It is a standard convention,
however, for the name args to be used.
我试过了,确实如此。也许这是常识,但我不知道。不相信我?试试吧!
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] + " ");
}
}
}
我想知道是否有任何方法可以通过使用 main args[] 而不是像下面这样调用 class 函数:
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
在 main 方法中,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();
}
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();
}
}
当我遇到这句话时,我刚好需要参考教科书中有关二维数组的内容!
It is not required that the name of main’s parameter array be args. You can name it anything you wish. It is a standard convention, however, for the name args to be used.
我试过了,确实如此。也许这是常识,但我不知道。不相信我?试试吧!
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] + " ");
}
}
}