简体   繁体   English

从另一个类调用方法以在 switch 语句中使用

[英]Calling method from another class to use in switch statement

I'm trying to call a method from my UserController class to my MainController .我试图从我的UserController类调用一个方法到我的MainController However i can't seem to instantiate my method and therefore calling it has proved quite difficult.但是,我似乎无法实例化我的方法,因此调用它已被证明非常困难。

Also the method I'm calling is to be used in a switch statement.此外,我正在调用的方法将在 switch 语句中使用。 Does this affect how i should go about it at all?这会影响我应该如何去做吗?

The createUser method. createUser方法。 The method works code wise (tried having it in MainController ) i just don't know how to instantiate it without doing it through a switch statement.该方法以代码方式工作(尝试在MainController使用它)我只是不知道如何在不通过 switch 语句的情况下实例化它。

  public static void createUser(){


   String username, password, repeatPassword, height, weight, address, email;

               int age, choice;
               double fitnessIndex; 

               String [] rank = {"Guld", "Platinum", "Diamond"};
               String [] sex = {"Mand","Kvinde"};

                System.out.println("Udfyld følgende for at blive oprettet som bruger: \n ");

                System.out.print("Navn:\n");
                username = input.nextLine();

                System.out.println("E-mail:  ");
                email = input.next();


                // Regular expression som presierer hva emailen skal inneholde for å være valid

                while (!email.matches("([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\.\\.]+)\\.([a-zA-Z]{2,5})")) {
                    System.out.print("Ugyldig Email, prøv igjen\n");
                    email = input.next(); }


                System.out.println("Alder:  ");
                age = input.nextInt();



                // Brugeren velger mellom 2 predefinerte koen
                do {
                    System.out.println("Vælg dit koen: ");
                    data.printArray1(sex);
                    choice = input.nextInt();
                } while (choice < 1 || choice > sex.length);



                System.out.println("Hoejde:   ");
                height = input.next();

                System.out.println("Vaegt:  ");
                weight = input.next();

                System.out.println("Adresse:   ");
                address = input.next();

                System.out.println("Kondital:  ");
                fitnessIndex = input.nextDouble();



                // Brugeren velger mellom 3 predefinerte muligheter for medlemsskab

                do {
                    System.out.println("Vælg ranken som passer deg bæst: ");
                    data.printArray(rank);
                    choice = input.nextInt();
                } while (choice < 1 || choice > rank.length);


                //beder brugeren om at vælge og gentage sitt kodeord


                do {
                    System.out.println("Kodeord:  ");
                    password = input.next();

                    System.out.println("Gentag kodeord  ");
                    repeatPassword = input.next();

                    if (!password.equals(repeatPassword)) {
                        System.out.println("Kodeordet er forkert, prøv igen!");
                    }
                } while (!password.equals(repeatPassword));

                User Unapproved = new User(username, password, 1, age, sex[choice-1], height, weight, fitnessIndex, address, email, rank[choice-1]);
                data.getUnapproveds().add(Unapproved);

                System.out.println("\nDu er nu blivet oprettet som medlem og venter på godkenning ");
                System.out.println("Så snart du er godkent vil du kunne logge inn, Velkommen til Motion CBS!🏋️\n");

        } 

Switch statement and me trying to call the method in MainController Switch 语句和我试图调用MainController的方法

            do try {
            choice = input.nextInt();
            input.nextLine();
            switch(choice) {
                case 1:
                    login();
                    break;

                case 2:
                    createUser(); // opret medlemskab
                    break;

                case 3:
                    login();
                    break;

                case 4:
                    onExit();
                    break;

                default:
                    System.out.println("Ugyldigt valg! Prøv igen");
                    break;
            }
        } catch (InputMismatchException eObject) {
            System.out.println("\n Du har indtastet en forkert variabel og bliver nu returnert til stratsiden");
            input.nextLine();
        printStartMenu();
    }

    while (currentUser != null);
}

{
   UserController userController = new UserController();
   userController.createUser();  }

So to clarify once again.所以再次澄清。 The method won't be called, since i don't know how to instantiate the method in UserController first.该方法不会被调用,因为我不知道如何首先在UserController实例化该方法。 So the CreateUser at the very bottom is RED (not working)所以最底部的 CreateUser 是 RED(不工作)

Therefore point 2 in the switch statement doesn't work.因此 switch 语句中的第 2 点不起作用。 Any help and tips are appreciated as i want to understand what i'm missing and why感谢任何帮助和提示,因为我想了解我缺少什么以及为什么

EDIT I understand now that i haven't provided nearly enough information so i'll supplement under here编辑我现在明白我没有提供足够的信息所以我会在这里补充

UserController extends MainController UserController 扩展了 MainController

 public class UserController extends MainController {

/**
 * The class constructor. Initializes the class and
 * its super class with instanses of the {@link MainController#data}
 * and {@link MainController#currentUser} objects.
 *
 * @param data        The instantiated data object.
 * @param currentUser The instantiated currentUser object.
 */
public UserController(Data data, User currentUser) {
    super(data, currentUser);
}

Maincontroller主控制器

protected Scanner input = new Scanner(System.in);

/** An instance of the Data class that holds all of the program data */
protected Data data;

/**
 *  The user currently logged in to the program.
 *  Defaults to null if no user is logged in.
 */
protected User currentUser;

/**
 * Default constructor for the Main Controller.<br>
 * Should <b>ONLY</b> be called from the Main Class, and only once.
 */

public MainController() {
    this.data = new Data();
}

/**
 * Constructor for instantiating when the Main Controller,
 * is the parent of a child controller.
 *
 * @param data          A reference to the instantiated Data object.
 * @param currentUser   A reference to the instantiated User object.
 */
public MainController(Data data, User currentUser) {
    this.data = data;
    this.currentUser = currentUser;
}

Since the createUser method is static, you can call it inside the Main controller using the Class in which the method resides, which in this case is UserController .由于createUser方法是静态的,您可以使用该方法所在的类(在本例中为UserController在主控制器内部调用它。

case 2:
       UserController.createUser(); 
       break;

Edit : The newly added code looks okay.编辑:新添加的代码看起来不错。 Since I do not have the Data and User classes, I am assuming that there is anything wrong but at the same time I can give some points regarding the aspect of the code to clear any problems that you might be facing like with this one.因为我没有 Data 和 User 类,所以我假设有什么问题,但同时我可以就代码方面给出一些观点,以清除您可能遇到的任何问题,比如这个。 You must be knowing most of the things, But just in case to clear any confusion you're facing:您必须知道大部分事情,但以防万一清除您面临的任何困惑:

I have absolutely no idea how to work around override and extends我完全不知道如何解决覆盖和扩展

extends is a keyword used to inherit a class. extends 是用于继承类的关键字。 In the current context UserController is a sub-class/child-class and the MainController is the super-class/parent-class.在当前上下文中UserController是一个子类/子类,而MainController是超类/父类。 Inheritance is forming of a relation between class.继承是形成类之间的关系。 You can use it to inherit the code that was already written in a class(MainController) and so you don't need to type the same thing inside the newly created class(UserController) which need the same properties.您可以使用它来继承已经在类(MainController)中编写的代码,因此您不需要在需要相同属性的新创建的类(UserController)中键入相同的内容。

Eg : My parent is a human being.例如:我的父母是一个人。 I(child) am a human being.我(孩子)是一个人。 I inherited the qualities of a human being from my parent(and my parent inherited their qualities from their parents and so on).我从我的父母那里继承了一个人的品质(我的父母从他们的父母那里继承了他们的品质等等)。

It is important to note that constructors cannot be inherited, which is why in your code inside the UserController constructor you are using super keyword to invoke the MainController constructor and pass the values to it.重要的是要注意构造函数不能被继承,这就是为什么在UserController构造函数内的代码中,您使用super关键字来调用MainController构造函数并将值传递给它。 Fields(except private fields) and methods(Except constructor) can be inherited.可以继承字段(私有字段除外)和方法(构造函数除外)。

I have absolutely no idea how to work around override and extends我完全不知道如何解决覆盖和扩展

Overriding means that you are inheriting something from your parent, but you do not want it as it is and what to modify the implementation.覆盖意味着你从你的父级继承了一些东西,但你不想要它的原样以及修改实现的内容。

Eg : Suppose, you are inheriting a Jewellery shop from your parent.例如:假设您从父母那里继承了一家珠宝店。 But you do not like it and so you chose to modify it in to a tea shop.但是你不喜欢它,所以你选择把它改造成一家茶馆。

A small program would explain it better :一个小程序会更好地解释它:

Parent class父类

public class parent {

public void wakeUp()
{
    System.out.println("I will wake up at 6am");
}

}

This is our parent class and it contains a method named wakeUp.这是我们的父类,它包含一个名为wakeUp 的方法。 Parent will wake up at 6am and so if this parent have a child then by default the parent will make the child also wake up at the same time(6am).父母会在早上 6 点醒来,所以如果这个父母有孩子,那么默认情况下,父母会让孩子在同一时间(早上 6 点)醒来。 In other words the child will inherit the qualities of the parent by default.换句话说,孩子将默认继承父母的品质。 You do not need to write any code inside the child class to get this quality(you just need to inherit the parent).您不需要在子类中编写任何代码来获得这种质量(您只需要继承父类)。 It is like saying this is my parent and so I will get all the properties from my parent by default and here goes the code for that :这就像说这是我的父母,所以默认情况下我将从我的父母那里获取所有属性,这里是代码:

public class Child extends parent{


}

As we can see that we havent written anything inside the child class.正如我们所看到的,我们还没有在子类中写任何东西。 But we have used the extends keyword which is declaring that the class named Child is the child of the class named Parent .但是我们使用了 extends 关键字,它声明名为Child的类是名为Parent的类的子类。

Now, overriding is when the child wants a different implementation.现在,覆盖是当孩子想要不同的实现时。 It is like saying I have different in views as compared to my parents when it comes to certain things.就好像说在某些事情上我和我父母有不同的看法。

Eg :例如:

public class Child extends parent{

@Override
public void wakeUp()
{
    System.out.println("I will wake up at 10am");
}

}

Here, we are definiing the same method inside the child class.在这里,我们在子类中定义了相同的方法。 Wake up is the quality and this child doesn't like to wake up at 6am and so the child had overridden the quality(method) called wakeUp() and provided it's own implementation inside the body of the method.唤醒是质量,这个孩子不喜欢在早上 6 点醒来,所以孩子已经覆盖了称为唤醒()的质量(方法),并在方法体内提供了它自己的实现。 The child modified/overridden the quality that it got from the parent.孩子修改/覆盖了它从父母那里得到的质量。 But the parent's quality haven't changed.但父母的素质并没有改变。 The parent will wake up at 6am and the child will wake up at 10am.父母早上 6 点起床,孩子早上 10 点起床。 I hope this helps you.我希望这可以帮助你。

From this it is clear for us that we don't need to override a method if we want the same implementation/quality.从这里可以清楚地看出,如果我们想要相同的实现/质量,我们不需要覆盖方法。 So whatever is written inside the MainController is inherited by the UserController(with a few exception we have said earlier).因此,在 MainController 中写入的任何内容都由 UserController 继承(除了我们之前所说的一些例外)。

Since you seems to be struggling with inheritance and what you can and can't do from a superclass I would suggest that the best solution for now is to move the method createUser from UserController to MainController and removing static from the declaration and then simply delete the UserController class (of course move any other methods as well).由于您似乎正在为继承而苦苦挣扎,以及您可以从超类中做什么和不能做什么,我建议现在最好的解决方案是将方法createUserUserController移动到MainController并从声明中删除static ,然后简单地删除UserController类(当然也可以移动任何其他方法)。

This will leave you with only one class and you can focus on getting your application to behave as you want.这将使您只剩下一个类,您可以专注于让您的应用程序按您想要的方式运行。 Introducing inheritance just for the sake of it is pointless and over engineering, once you have a running bug free version of your application then you could start considering re-factoring your code.仅仅为了继承而引入继承是没有意义的,而且是过度工程化的,一旦你的应用程序运行了一个没有错误的版本,那么你就可以开始考虑重构你的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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