0

I have written my first code in Java, one which prints a frame surrounding a word entered as parameter to the class. I have declared the public variable "word" and assigned it to the parameter, also named "word". I believe there is no problem with the method, named "print", which does most of the job. However, the main method which calls "print" doesn't work, saying it can't make a static reference to the non-static field "word".

I don't fully understand the concepts of static and void yet, but all the examples I've seen use static and void for the methods, especially for the main method. I've tried removing the static from the main method and when I do so, the error disappears before running, but reappears in the console when I run it, saying main absolutely has to be static.

public class Show {

    public Show(String word) {

        this.word = word;

    }

    public static void main(String[] args) {

        print(word);

    }

    public static void print(String word) {

        System.out.print("+");
        for(int i = 0; i < word.length(); i++) {
            System.out.print("-");
        }
        System.out.println("+");
        System.out.print("|");
        System.out.print(word);
        System.out.println("|");
        System.out.print("+");
        for(int i = 0; i < word.length(); i++) {
            System.out.print("-");
        }
        System.out.println("+");

    }

    public String word;

}

I think the logic in my code, by which I mean the method print, is sound. I just don't understand how to make everything work. I just want to eventually compile the Show.java to Show.class and be able to do, let's say, java Show mammoth, which would print "mammoth" surrounded by a frame. What am I doing wrong? I know it has something to do with the static and void in either or both of the methods, but I've tried seemingly all combinations to no avail.

QCyrax
  • 9
  • 1
  • Your direct issue is explained in the question linked above. And this question explains how you achieve what you actually want to do: [Passing on command line arguments to runnable JAR](//stackoverflow.com/q/8123058) (just ignore that the other question uses a JAR, that's not important) – Tom Sep 22 '19 at 18:29

1 Answers1

0

Non static variables cannot be referenced from a static method, you need an object of the class Show in order to access the "word" instance variable in your main. If you arent sure what an Object is or how to create one, for now remove your constructor (the public Show(String word) method) and just define "word" as static (public static String word;), your code will work, and welcome to the world of object oriented programming, you have a lot to read upon.

Also, this is most definitly a duplicate. Non-static variable cannot be referenced from a static context

Martin'sRun
  • 522
  • 3
  • 11