I'm doing a project for a class and it says to write a program that translates code from one programming language to another. It says that my class containing my static main method should be named "Translate". It should take as input source code of a programming language as a text file with the extension ".x". For example the grader should be able to test using "Translate loop.x" . I can assume that the input file is in the same directory but my question is how do I create a static main method that takes such a parameter. Hope someone can help.

public static void main(String [] args) {

}

The (String [] args) is the argument of the main. When you call the java program with arguments at the command line those arguments are stored in the args array:


>java Translate arg1 arg2 "arg 3"

Now in your program the args array has values:
args[0] : arg1
args[1] : arg2
args[2] : arg 3

If you call the program with no arguments the array will have length zero
If you call it with 5 arguments it will have: args[0], args[1], args[2], args[3], args[4].
So use the args.length to check how many arguments the program has.

public class Translate {
public static void main(String [] args){
String filename = null;
if(args != null && args.length() > 0){
filename = args[0];
}
}
}
public class Translate {
public static void main(String [] args){
String filename = null;
if(args != null && args.length() > 0){
filename = args[0];
}
}
}

The parameter args is never null and you didn't explain how to pass that ars[0] argument in the code

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.