Java: Identifier expected

Java

Java Problem Overview


What's the issue here?

class UserInput {
  public void name() {
    System.out.println("This is a test.");
  }
}

public class MyClass {
  UserInput input = new UserInput();
  input.name();
}

This complains:

<identifier> expected
   input.name();

Java Solutions


Solution 1 - Java

Put your code in a method.

Try this:

public class MyClass {
    public static void main(String[] args) {
        UserInput input = new UserInput();
        input.name();
    }
}

Then "run" the class from your IDE

Solution 2 - Java

You can't call methods outside a method. Code like this cannot float around in the class.

You need something like:

public class MyClass {

  UserInput input = new UserInput();
  
  public void foo() {
      input.name();
  }
}

or inside a constructor:

public class MyClass {

  UserInput input = new UserInput();
  
  public MyClass() {
      input.name();
  }
}

Solution 3 - Java

input.name() needs to be inside a function; classes contain declarations, not random code.

Solution 4 - Java

Try it like this instead, move your myclass items inside a main method:

    class UserInput {
      public void name() {
        System.out.println("This is a test.");
      }
    }
    
    public class MyClass {

        public static void main( String args[] )
        {
            UserInput input = new UserInput();
            input.name();
        }

    }

Solution 5 - Java

I saw this error with code that WAS in a method; However, it was in a try-with-resources block.

The following code is illegal:

    try (testResource r = getTestResource(); 
         System.out.println("Hello!"); 
         resource2 = getResource2(r)) { ...

The print statement is what makes this illegal. The 2 lines before and after the print statement are part of the resource initialization section, so they are fine. But no other code can be inside of those parentheses. Read more about "try-with-resources" here: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrandombitsView Question on Stackoverflow
Solution 1 - JavaBohemianView Answer on Stackoverflow
Solution 2 - JavaTudorView Answer on Stackoverflow
Solution 3 - JavageekosaurView Answer on Stackoverflow
Solution 4 - JavaJonathan PayneView Answer on Stackoverflow
Solution 5 - JavaEliezer MironView Answer on Stackoverflow