简体   繁体   中英

Can't define method in class

I am trying to create a simple Java class in Eclipse which pulls in a JSON array over an api. I'm trying to add a method to return a string value, which is creating an error. It seems that Java doesn't recognize it as a method.

import org.springframework.web.client.RestTemplate;

public class GetSurvey {
    public static void main(String[] args)
    {
        int SurveyID   = 2107240;
        String SurveyDate = "2016-01-07";
        String SurveyType;
        String apiurl = "https://restapi.surveygizmo.com/v4/survey/" + SurveyID + "...";
        String Result(){
            return restTemplate.getForObject(apiurl,String.class);
        }
    }
}

This is resulting in the following errors:

Syntax error on token "String", new expected

Result cannot be resolved to a type

Syntax error, insert ";" to complete Statement

Void methods cannot return a value

It seems that it is not recognizing String Result(){ as a method. I created the class without defining a method and there's no errors.

To address the errors. Other than you can't define a method within a method.

Syntax error on token "String", new expected

Java syntax is looking for an object declaration like String s = new String() .

Result cannot be resolved to a type

Result() is not a defined as a method, so it is trying to be invoked, but can't.

Syntax error, insert ";" to complete Statement

String Result() expects to be ended by a semi-colon.

Void methods cannot return a value

Self-explanatory, you can't do any more than return; in a void method, which main is.


It would appear you meant to do this

import org.springframework.web.client.RestTemplate;

public class GetSurvey {

   @Autowired
   private RestTemplate restTemplate;

    private static String getTemplate(String apiUrl) {
        return restTemplate.getForObject(apiUrl,String.class);
    }

    public static void main(String[] args)
    {
        int SurveyID   = 2107240;
        String SurveyDate = "2016-01-07";
        String SurveyType;
        String apiurl = "https://restapi.surveygizmo.com/v4/survey/" + SurveyID + "...";
        String result = getTemplate(apiurl);
    }
}

您不能在main方法内定义方法。

You are nesting methods by defining them inside others, that is not how java works..

move the method

String Result(){
    return restTemplate.getForObject(apiurl,String.class);
}

out of the main method. and be careful with the scope of the returned val.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM