java 从另一个方法调用一个方法,其中两个方法都在同一个类中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38412280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:22:45  来源:igfitidea点击:

Calling a method from another method in which both are in the same class

javaarraysmethodsmethod-call

提问by Dinz_N

I am calling the method findRoom()which is in the class myClassfrom the mainmethod:

我正在从方法findRoom()中调用类myClass中的main方法:

int room[]= {1,2,3,4,5,6,7,8,9,10};
String customer[] = {"","Shay","","Yan","Pan","","","Xiao","Ali",""};
    myClass m = new myClass();
    m.findRoom(customer, room);         

The class myClassis as follows:

myClass如下:

class myClass {

int count = 0;

public void findRoom(String customerName[], int roomNo[]) {

    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter Customer's Name");

    String name = sc.next();

    for (int i = 0; i < 10; i++) {

        if (customerName[i].equalsIgnoreCase(name)) {
            System.out.println(roomNo[i]);
            count++;
            break;
        } else {
            count++;

        }
    }
    myMethod(customerName, roomNo);
}

public void myMethod(String cusName[], int rooms[]) {
    myClass m = new myClass();
    if (m.count == 10) {
        System.out.println("Please check the name again");
        m.count = 0;
        m.findRoom(cusName, rooms);
    }
}
}

I want the program to prompt the user to enter the customer's name again, if the name entered by the user is not found in the array customer[]. So I created the method myMethod()which will ask the user to re-enter customer's name.

如果在数组中找不到用户输入的名称,我希望程序提示用户再次输入客户的名称customer[]。所以我创建了一个方法myMethod(),它会要求用户重新输入客户的姓名。

The program runs fine if user enters a name that is already in the array, but doesn't work the other way around when user enters a name that is not found in the array. The method myMethod()is not being called. What could be the possible reason for this? Is it a problem with the parameter passing? Any help is appreciated. =)

如果用户输入的名称已经在数组中,则程序运行良好,但当用户输入的名称不在数组中时,程序将无法正常工作。myMethod()没有调用该方法。这可能是什么原因?是不是参数传递有问题?任何帮助表示赞赏。=)

回答by Aleksandr Podkutin

Your mistake is that, when you go into myMethod, you create new myClassobject and this object has countfield, but value of this filed is zero, because this is new object. But all your work and changing countfield going in another object that you create in mainmethod:

你的错误是,当你进入时myMethod,你创建了一个新myClass对象,这个对象有count字段,但是这个字段的值为零,因为这是新对象。但是你所有的工作和变化的count领域都在你在main方法中创建的另一个对象中:

myClass m = new myClass();
m.findRoom(customer, room); 

If you need so simple example, try to use staticmodifieron field count:

如果您需要如此简单的示例,请尝试在 field上使用static修饰符count

static int count = 0;

Edit findRoommethod:

编辑findRoom方法:

    myClass.count++;
    break;
} else {
    myClass.count++;

Edit myMethodmethod:

编辑myMethod方法:

if (myClass.count == 10) {
    System.out.println("Please check the name again");
    myClass.count = 0;
    m.findRoom(cusName, rooms);
}

回答by Lasitha Yapa

First of all I suggest you to learn more about objects and classes. In your code in method myMethod()first statement is for creating a new object of myClass. When you create that it's like you are taking a fresh copy of your class's attributes. (If they are not static) So always it will give you variable count with the value you gave it, that is 0.
If your code has to remember the values given to class variables not depending on the objects you create you have to make them static. Then you can call those variables without creating objects.

首先,我建议你学习更多关于对象和类的知识。在方法中的代码中,myMethod()第一条语句用于创建myClass. 当您创建它时,就像您正在获取类属性的新副本。(如果它们不是静态的)所以它总是会给你变量计数你给它的值,那就是 0。
如果你的代码必须记住赋予类变量的值而不取决于你创建的对象,你必须让它们静止的。然后您可以在不创建对象的情况下调用这些变量。

myClass.count;

So what you have to do is just replace int count=0;with static int count=0;and few more things to improve your coding.

所以,你必须做的就是替换一下int count=0;static int count=0;和一些事情来改善你的编码。

  • Start class names with capital letters (this is not a rule, but a good practice)
  • Learn more about difference between static and non-static methods/variables.
  • Normally class variables are used with privateaccess modifier. (for encapsulation)
  • 以大写字母开头类名(这不是规则,而是一种好习惯)
  • 详细了解静态和非静态方法/变量之间的区别。
  • 通常类变量与private访问修饰符一起使用。(用于封装)

回答by Lasitha Yapa

Something like this should do the trick:

像这样的事情应该可以解决问题:

import java.util.Scanner;
public class MyClass {


    static int[] room;
    static String[] customer;



    public static void main(String[] args) {

        room = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        customer = new String[]{"", "Shay", "", "Yan", "Pan", "", "", "Xiao", "Ali", ""};

        MyClass mc = new MyClass();
        mc.findRoom(customer, room);

    }



    public void findRoom(String customerName[], int roomNo[]){

        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the Customer's name.");
        String name = sc.next();

        int count = 0;


        for(int i = 0; i < customerName.length; i++){
            if(customerName[i].equalsIgnoreCase(name)){

                System.out.println(name + " is in room number " + roomNo[i]);
                break;
            }
            else{
                count++;
            }
        }

        //##### RECURSION STARTS HERE #####
        if(count == customerName.length){

            count = 0;
            System.out.println("Name not found, please try again.\n");
            findRoom(customerName, roomNo);
        }

    }

}

Recursion (method calling on itself), saves you from having to create two methods, also using arrayName.length within the 'if statement' will avoid you having to hard code the condition if you decide to have a bigger set of arrays.

递归(调用自身的方法)使您不必创建两个方法,并且在“if 语句”中使用 arrayName.length 将避免您在决定拥有更大的数组集时必须对条件进行硬编码。