Dindi Rave Dindi Rave - 4 months ago 8
Java Question

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

I am calling the method

findRoom()
which is in the class
myClass
from the
main
method:

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
myClass
is as follows:

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.

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. =)

Answer

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

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

If you need so simple example, try to use static modifier on field count:

static int count = 0;

Edit findRoom method:

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

Edit myMethod method:

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