Java Method Confusion

Question: I get an error with my user defined methods. I followed the examples laid out in my textbook to write the program. What syntax rule am I missing?

Repl link: —OUT OF ORDER— https://replit.com/@ThomasWarenski/Java-Exercise-69#Main.java

1 Like

Not a Java programmer, but this seems to be running as expected, with no errors whatsoever. I’m guessing you probably provided the wrong link, as Main.java (at least for me) is Replit’s default Hello World template, and you specified you had user-defined methods.

class Main {
  public static void main(String[] args) {
    System.out.println("Hello world!");
  }
}
1 Like

I don’t know why that link doesn’t work. I’ll look at fixing it. In the meantime, I’ll put my whole program here.

class Main {
  public static void main(String[] args) {
    int foot, meter;
		for(int i = 0; i < 10; i++){
			foot = 1 + 1 * i;
			meter = 20 + 5 * i;
			System.out.printf(foot + " " + footToMeter(foot) + " " + meter + " " + meterToFoot(meter) + "\n");
		}
		
		// Define functions.
		public static double footToMeter(double foot){
			double meters = foot * .305;
			return meter;
	}

		public static double meterToFoot(double meter){
			double foot = meter / .305;
			return foot;
		}
  }
}
1 Like

Yeah, that’s pretty weird, don’t think I’ve ever seen that before. Anyway, could you provide the error you are facing?

Edit: Nevermind, tested myself. Seems to be outputting

./Main.java:11: error: illegal start of expression
        public static double footToMeter(double foot){
        ^
./Main.java:21: error: class, interface, enum, or record expected
}
^
2 errors

Found your problem here. You were nesting these functions inside of main(), which was causing a lot of issues. Some of your closing brackets were placed a bit oddly, and I think you also specified the wrong variable name in your footToMeter() function.

This should all be fixed in the code below.

class Main {
    public static void main(String[] args) {
        int foot, meter;
        for (int i = 0; i < 10; i++) {
            foot = 1 + 1 * i;
            meter = 20 + 5 * i;
            System.out.printf(foot + " " + footToMeter(foot) + " " + meter + " " + meterToFoot(meter) + "\n");
        }
    }

    // Define functions.
    public static double footToMeter(double foot) {
        double meters = foot * .305;
        return meters;
    }

    public static double meterToFoot(double meter) {
        double foot = meter / .305;
        return foot;
    }

}

Hope this helps!

3 Likes

Where am I supposed to put the methods? My textbook shows them in Main()

1 Like

Yes, these methods are inside Main, the class, not the main method like they were before.

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.