我有一个带有两个类的程序,每个都有一个main方法,我想知道是否可以从我的第二个类调用main方法在我的第一个类中工作。我似乎无法找到任何有用的例子,这让我觉得我不可能做我想做的事。
头等舱:
package scannerarrays;
import java.util.Scanner;
public class ScannerArrays {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String words;
int IDnum;
System.out.println("Enter your Name");
words = input.nextLine();
System.out.println("Enter your Surname");
words = input.nextLine();
System.out.println("Enter your ID number");
IDnum = input.nextInt();
第二课:
package scannerarrays;
import java.util.Scanner;
public class IdDetails {
String id;
int month[] = {31 , 29 , 31 , 30 , 31, 31 , 30 , 31 , 30 , 31};
public IdDetails() {
Scanner input = new Scanner(System.in);
System.out.println("Enter your ID number \nLike : 000000000V");
id = input.next();
}
public int getYear() {
return(1900 + Integer.parseInt(id.substring(0, 2)));
}
public int getDays() {
int d = Integer.parseInt(id.substring(2, 5));
if (d > 500) {
return (d - 500);
}else{
return d;
}
}
public void setMonth() {
int mo = 0, da = 0;
int days = getDays();
for (int i = 0; i < month.length; i++) {
if (days < month[i]) {
mo = i + 1;
da = days;
break;
}else{
days = days - month[i];
}
}
System.out.println("Month: " + mo + "\nDate : " + da);
}
public String getSex() {
String M = "Male" , F = "Female";
int d = Integer.parseInt(id.substring(2 , 5));
if (d>81) {
return F;
}else{
return M;
}
}
public static void main(String[]args) {
IdDetails ID = new IdDetails();
System.out.println("Your Details of DOB from ID");
System.out.println("Year : " + ID.getYear());
ID.setMonth();
System.out.println("Sex : " + ID.getSex());
}
}
答案 0 :(得分:2)
主方法就像你的类的任何其他静态方法一样,所以你可以用同样的方式调用它,就像:
IdDetails.main();
或者使用任意数量的String参数:
IdDetails.main("name", "surname", "12");
但这似乎有点令人困惑,在这种方式中使用主方法中的逻辑。如果你真的需要这样做,只需使用固定的输入参数制作另一个方法,并在需要的任何地方调用它(在两种主要方法中都是如此)。