NurieDavis
NurieDavis

Reputation: 33

Is it possible to call to main method from a class that already has a main method?

I have a program with two class and each has a main method, i wanted to know if it is possible to call the main method from my second class to work in my first class. I can't seem to find any examples that will help, that makes me think that it's not possible for me to do what I want to.

First Class:

    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(); 

Second Class:

 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());

      }



     }

Upvotes: 0

Views: 78

Answers (1)

Stanislav
Stanislav

Reputation: 28106

The main method is like any other static method of your class, so you can call it the same way, just like:

IdDetails.main();

Or with any number of String parameters:

IdDetails.main("name", "surname", "12");

But that seems a litte bit confusing, to use a logic within a main method this way. If you really need to do it, just make another method with fixed input parameters and call it everywhere you need it (in your case in both main methods).

Upvotes: 2

Related Questions