Converting to Object/Classes
I have the following code i wrote to manipulate terminal commands in linux(CentOS)
import java.util.Scanner;
public class JavaExecuteShellCMD{
public static void main(String[] args) throws Exception{
String cmd = "pwd"; //Command "pwd"
String cmd1 = "ls -l";
Runtime run = Runtime.getRuntime(); //create a runtime
Process pr = run.exec(cmd);
pr.waitFor();
Scanner in = new Scanner(pr.getInputStream()); //take input from terminal
while(in.hasNext()){
System.out.println(in.nextLine());
}
in.close();
Process pr1 = run.exec(cmd1);
pr1.waitFor();
Scanner in1 = new Scanner(pr1.getInputStream());
while(in1.hasNext()){
System.out.println(in1.nextLine());
}
in1.close();
}
}
Though I know how to create simple objects and classes, i do not know how to put this in class form.
Any help would be appreciated.
Thanks
Re: Converting to Object/Classes
What are you trying to do with this code ultimately? What have you tried to do in your effort to make an OOP-compliant class, and where exactly are you stuck?
Re: Converting to Object/Classes
To clarify my questions above, certainly we could tell you to plop all the code above into a class constructor, but to what purpose? And how would this help in any way? Unless we know what you're trying to ultimately do with this code, how you're going to want to use it, our advice will be limited.
Also, please read my link on how to use code tags so that you can edit your post and allow your code to retain its formatting and be readable.
Re: Converting to Object/Classes
Re: Converting to Object/Classes
what am trying to do is for example a Class vehicle, i want to instantiate 4 vehicles. same here, i want to have the code written in a class so i can instantiate and use it more than once. For example, i want to create an object that will use "pwd" and a second object "ls -l"
what i managed to do which i guess is quite wrong:
Code:
public class ShellCMD {
private String cmd;
ShellCMD(String cmd){
this.cmd = cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String getCmd() {
return cmd;
}
}
Code:
import java.util.*;
public class ShellExecute {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("1.Current Directory Path\t2.Directory Listing");
System.out.println("Make a choice: ");
int choice = input.nextInt();
switch(choice){
case 1:{
ShellCMD("pwd");
System.out.println("pwd object created");
break;
}
case 2:{
ShellCMD("pwd");
System.out.println("ls -l object created");
break;
}
}
}
}
Re: Converting to Object/Classes
Since my earlier response was not visible, I guess this one won't be noticed.
db