简体   繁体   中英

How to call Main Method from another Class in Java as a Process

I have this 2 classes:

public class Sumador {
    
    public static void main(String[] args) {
        int primerNumero = Integer.parseInt(args[0]);
        int segundoNumero = Integer.parseInt(args[1]);
        int suma = 0;
        
        for(int k=primerNumero; k < segundoNumero; k++) {
            suma += k;
        }
        System.out.println("Resultado: " + suma);
    }
}
public class Lanzador {
    
    public void lanzarSumador() {
        Process p;
        InputStream is;
        BufferedReader br = null;
        
        try {
            p = new ProcessBuilder("java", "Sumador.java", "10", "20").start();
            is = p.getInputStream();
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while(br.ready()) {
                System.out.println(br.readLine());
            }
            
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        Lanzador l = new Lanzador();
        l.lanzarSumador();
        
    }
}

What i want to do is running the second class to get the first one as a process in the second one, but unfortunetly for me, it doesn't work and i can't understand why.

Every reply would be really thankful. Thank you for your time.

EDIT: You can call the main method of class Sumador from the main method in class Lanzador like show next:

public static void main(String[] args) {
    Lanzador l = new Lanzador();
    l.lanzarSumador();
    Sumador.main(null);
}

You only can have one main class in your program execution. What you can do is change the main method in class Sumador at a public class and call it in the main method of class Lanzador

public class Sumador {

public static void sumadorMethod() {
    int primerNumero = Integer.parseInt(args[0]);
    int segundoNumero = Integer.parseInt(args[1]);
    int suma = 0;
    
    for(int k=primerNumero; k < segundoNumero; k++) {
        suma += k;
    }
    System.out.println("Resultado: " + suma);
}   

}

Then you main method in class Lanzador look like this:

public static void main(String[] args) {
    Lanzador l = new Lanzador();
    l.lanzarSumador();
    Sumador.sumadorMethod();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM