如何在其他Class中使用变量来重复某些事情? (JAVA)

时间:2014-11-05 23:36:19

标签: java class oop variables inheritance

我用Java编程来做一个简单的程序来模拟一些东西作为Facebook菜单来练习面向对象的编程。这就是事情;

在一个名为“决定”的班级中,''用户输入' 0' 0退出,' 1'注册或' 2'登录。

我希望程序在用户注册或登录后返回主菜单,因为在下面的代码中,用户既没有注册也没有登录程序结束。

使用的变量名为''选项''我想我必须在主类中使用它来做我想要的(重复主菜单)。

这是我的代码:

class Decision { // THIS IS THE CLASS FOR ENTER THE OPTION.

    protected byte  option; // THIS IS THE VARIABLE.

    public Decision() {

        boolean aux = true; // THIS IS ONLY FOR VALIDATE WRONG INPUT.
        Scanner sc = new Scanner(System.in);
        do {
            try {
                System.out.println("\n\t\t\t*-------------------------------*");
                System.out.println("\t\t\t\t     FACEBOOK");
                System.out.println("\t\t\t*-------------------------------*\n");
                System.out.println("0.-EXIT FACEBOOK\n");
                System.out.println("1.-SIGN UP\n");
                System.out.println("2.-LOG IN\n");
                option = sc.nextByte();
                aux = true;
                if (option >= 3 || option < 0) {
                    aux = false;
                    System.out.println("\nPLEASE INSERT A VALID OPTION.\n");
                }
                if (option == 0) {
                    System.out.println("\nSEE YOU SOON.\n");
                    aux = true;
                }
            } catch (InputMismatchException exc) {
                aux = false;
                sc.nextLine();
                System.out.println("\nPLEASE INSERT A VALID OPTION.\n");
            }
        } while (aux == false); // I USE THIS FOR VALIDATE THE INPUT, DO NOT
                                // WORRY AT ALL.

    }// CONSTRUCTOR
}// Decision

class Data extends Decision { // THIS IS THE CLASS FOR ENTER DATA (NAME, LAST
                                // NAME, ETC)

    Scanner sc  = new Scanner(System.in);

    public void Title() {
        System.out.println("\n\t\t\t*-------------------------------*");
        System.out.println("\t\t\t\t     FACEBOOK");
        System.out.println("\t\t\t*-------------------------------*\n");
    }// Title

    public void Decision() {

        if (option == 1) {
            // IN THIS PART THE USER IS CREATING A PROFILE AND STUFF.

        } else {
            if (option == 2) {
                // IN THIS PART THE USER ONLY LOG IN AND THE SEE THE INFO.
            }
        }// else

    }// Decision

}// DATA

public class Facebook { // AND THIS IS THE MAIN CLASS

    protected Decision  option;

    public Facebook() {
        option = new Decision();
    }// CONSTRUCTOR

    public static void main(String args[]) {

        Facebook facebook = new Facebook();

    }// main

}// Facebook

1 个答案:

答案 0 :(得分:0)

如果你想在程序中重复一些东西,那么自然的答案应该是你使用一个循环。更改退出条件aux == false(最好是!aux,它等同于更好的编程风格)。例如:

// initialize it to false in case the first iteration of the loop throws an exception
boolean exit = false;
do {
    //...
    exit = option == 0;
while (!exit);