开发者

Java static method can't compile

the following messege appears when I compile this code.

ExtractChars(java.lang.String,int) in Question2 cannot be applied to ()

What should I fix?

Thanks.

i开发者_如何学运维mport java.util.Scanner;

public class Question2
{

    public static void main (String[] args)
    {

        ExtractChars();

    }
    public static String ExtractChars(String sOrg, int startPos)
    {

        Scanner scan = new Scanner (System.in);
        String value = "";
        System.out.print("Enter a string: ");
        sOrg = scan.next();
        System.out.print("/nEnter an integer: ");
        startPos = scan.nextInt();
        if (sOrg.length()<=startPos)
        {

            value = "";

        }
        else
        {
            for (int i=startPos; i<sOrg.length();i=i+2)
            {

                value = value + sOrg.charAt(i);

            }
        }

        return value;
    }
}


This is because the function ExtractChars expects two arguments but you are not passing any.

EDIT:

Looks like you are reading input sOrg and startPos and there is no need to pass them as arguments, you can make them local variables.

So change:

public static String ExtractChars(String sOrg, int startPos)
{
 ....

to

public static String ExtractChars()
{
  String sOrg;
  int startPos;
  ....

Also, you are just discarding the return value of the function ExtractChars in main. You might want to print the extracted characters returned by the function (as a string) as:

System.out.println("Extracted Characters = " + ExtractChars());

in your main in place of

ExtractChars();


You've defined your method to expect two arguments, but you're really using them as though they were local variables, prompting the user to enter values for them.

You should probably rewrite your method something like this

public static String ExtractChars()
{
    String sOrg;
    int startPos;

    Scanner scan = new Scanner (System.in);
    String value = "";
    System.out.print("Enter a string: ");
    sOrg = scan.next();
    System.out.print("/nEnter an integer: ");
    startPos = scan.nextInt();
    if (sOrg.length()<=startPos)
    {

        value = "";

    }
    else
    {
        for (int i=startPos; i<sOrg.length();i=i+2)
        {

            value = value + sOrg.charAt(i);

        }
    }

    return value;
}

so that sOrg and startPos are local variables in your method instead of arguments to it.

The method call as you have it will then compile.

You're also not doing anything with the return value of this function, so it may seem like nothing is happening. But this might get you on your way.


You have to use arguments when you call ExtractChars. ExtractChars wants a String and an int. When you call it, you're passing nothing.


its the arguments. You're calling a function which expects 2 arguments. The compiler generated message atlest points to that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜