Search code examples
javacompiler-errorscommand-line-argumentsargument-passingsymbol-not-found

Symbol not found in function's argument in main loop?


Description

I have a beginner's-level program. My goal is to pass an argument in at runtime for the first time.

Proposed questions

  • Describe the error in greater detail?
  • How are errors like this traced and repaired?
  • I've used google and StackOverflow. Should I be using a different resource to help with errors like this in my beginner programs?

My code

class sayagain {

    public static void sayagain(String s){

        System.out.print(s);

    }

    public static void main(String[] args){

        sayagain(arg);  

    }

}

Compile error

print2.java:11: error: cannot find symbol
                print2(arg);
                       ^
  symbol:   variable arg
  location: class print2
1 error

Solution

  • Correct

    arg is not defined. Maybe you mean sayagain(args[0]), which will print the first argument in the main method.

    Explanation of string array types-and-indexes

    args is a string array, so to get the first argument you need to access the first element in the array: [0].

    Warning

    You will be given an index out of bounds error if you do not include any arguments when you call the main method.

    • Example input: >java sayagain
    • Example output:

      Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at sayagain.main(sayagain.java:11)

    Variable plurality

    There's no built-in function to discover arg as the singular of args. Variables may be anything within the specification of the formal language, even asdfsfaeef. It is much better practice to use a descriptive name; therefore, people tend to use plural form when naming arrays.