从if / if else语句中调用方法

时间:2013-04-26 12:54:22

标签: java if-statement methods call

是否可以在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);
    }
}

任何帮助将不胜感激

5 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分: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.");

答案 2 :(得分:1)

是的,首先创建您的方法,然后在if语句中调用它们,如下所示:

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

然后

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

    }

答案 3 :(得分: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'

进行比较

答案 4 :(得分: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 

}

如果在同一个类中但在调用方法

之外的块声明,则调用该方法
 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);         char choice = 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
        }