3

是否可以在 if 语句中调用方法,然后在 if else 语句中调用单独的方法?

我创建了一个扫描仪而不是读取键盘输入,并且根据用户提供的选项,将调用不同的方法。我可以说一些类似的东西:

Scanner in = new Scanner (System.in);
char choice = in.next().charAt(0);

if(choice == 1)
{
    private static void doAddStudent(Student aStudent) 
    {
        this.theRegistry.addStudent(aStudent);
    }
}

任何帮助将非常感激

4

5 回答 5

6

您当然可以在 if 或 else 块中调用方法。但是您在代码段中尝试的是在块中声明一个方法,这是不可能的。

固定片段:

Scanner in = new Scanner (System.in);
char choice = in.next().charAt(0);

if(choice == 1)
{
    this.theRegistry.addStudent(aStudent);
}

编辑:

我认为您想要的代码如下所示:

public static void main(String[] args) {
    //some code
    Scanner in = new Scanner (System.in);
    char choice = in.next().charAt(0);

    if(choice == 1)
    {
        RegistryInterface.doAddStdent(student);
    }
    //some code
}

RegistryInterface.java

public class RegistryInterface {
    private static void doAddStudent(Student aStudent) {
        this.theRegistry.addStudent(aStudent);
    }
}
于 2013-04-26T12:57:32.727 回答
2

好吧,你可以。

Scanner in = new Scanner (System.in);
char choice = in.next().charAt(0);

if(choice == 1)
    this.theRegistry.addStudent(aStudent);
else if choice == 2)
    this.theRegistry.removeStudent(aStudent);
else
    System.out.println("Please enter a valid choice.");
于 2013-04-26T13:05:02.513 回答
1

是的,首先创建你的方法,然后在if语句中调用它们,像这样:

private static void doAddStudent(Student aStudent) 
        {
            this.theRegistry.addStudent(aStudent);
        }

然后

 if(choice == 1)
    {
        doAddStudent(aStudent) ;////here you call the doAddStudent method

    }
于 2013-04-26T12:58:48.477 回答
1

在您的代码中,您不仅仅是在if语句中调用一个方法——您还试图定义一个新方法。这是非法的。

我猜你想要这样的东西:

Scanner in = new Scanner (System.in);
char choice = in.next().charAt(0);
if(choice == '1') {
    this.theRegistry.addStudent(aStudent);
}

另请注意,您正在char choise与 int进行比较1。我想您想与 char 进行比较'1'

于 2013-04-26T12:58:58.670 回答
1

调用方法是静态的

static TheRegistryClass theRegistry;
static void callingMethod(){
/// Some code here 
Scanner in = new Scanner (System.in);
    char choice = in.next().charAt(0);

    if(choice == 1)
    {
       doAddStudent(aStudent);
    }

//remaining code here 

}

if 块中调用的方法在同一类中但在调用方法之外声明

 private static void doAddStudent(Student aStudent) 
        {
            theRegistry.addStudent(aStudent); // static methods do not have reference to this
        }

如果调用方方法是非静态的 TheRegistryClass theRegistry; void callingMethod(){ /// 这里有一些代码 Scanner in = new Scanner (System.in); 字符选择 = in.next().charAt(0);

    if(choice == 1)
    {
       doAddStudent(aStudent);
    }

//remaining code here 

}



 private static void doAddStudent(Student aStudent) 
        {
            this.theRegistry.addStudent(aStudent); // this is optional
        }
于 2013-04-26T13:02:08.127 回答