How to put multiple programs into one class?

Joseph Wokil :

I have made two programs for an assignment. Now my professor wants me to put both programs into the same file and use a switch to create a menu where the user can use to choose what program they want to run. How do I do this? I will copy-paste both of my original programs below.

Program 1:

import java.util.Scanner;
public class ReadName {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Please type in your full name: ");

        String names = scanner.nextLine();

        String[] namesSep = names.split(" ");

        int lastString = namesSep.length - 1;

        System.out.println(namesSep[0]);

        System.out.println(namesSep[lastString]);
    }
}

Program 2:

import java.util.Scanner;

public class FindSmith {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Type in your list of names: ");
        String names = scanner.nextLine();

        String[] namesSep = names.split(",");

        for (int i=0; i<namesSep.length; i++) {
            if (namesSep[i].contains("Smith")) {
                System.out.println(namesSep[i]);
            }
        }
    }
}
GhostCat salutes Monica C. :

You have two classes that do work in a single main() method each.

Start with: moving the content of that main() methods into another static method within each class, like:

import java.util.Scanner;
public class ReadName {
  public static void main(String[] args) {
    askUserForName();
  }
  public static void askUserForName() {
    Scanner scanner = new Scanner(System.in);   
    System.out.print("Please type in your full name: ");
  ...
  }  
}

Do that for both classes, and make sure that both classes still do what you want them to do.

Then create a third class, and copy those two other methods into the new class. Then write a main() method there, that asks the user what to do, and then runs one of these two methods from there.

Alternatively, you could also do

public class Combo {
 public static void main(String[] args) {
   ...
   if (userWantsToUseClassOne) {
     Readme.main(new String[0]);
   } else {
     FindSmith.main(...

In other words: as long as you keep your classes in the same directory, you can directly re-use what you already have. But it is much better practice to put your code into meaningful methods, like I showed first.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=165496&siteId=1