several java class validation input

I have created a program on netbeans using java. The user is prompted to enter a "Number: ". For example, when they enter the number "1" the data from the array list appears "Number: 1" "Name: userA" and "Phone: 2". If i enter a value which isn't on the array list, for example 5 userA's details will appear. How could i enter in validation to check whether or not the number entered is held within the array list? If the number isn't in the array list is there a way of telling the user this and allowing them to try again to enter in the number.

Data Class:

public class Data {

    private final List<DetailsT> DetailsL;

    public Data() {
        DetailsL = new ArrayList<>();
        DetailsL.add(new DetailsT(1, "userA", 2));
        DetailsL.add(new DetailsT(2, "userB", 9);

    }

    public ArrayList<?> getList() {
        return (ArrayList<?>) DetailsL;
    }

Output Class:

//initialize streams so we can send message
    in = new DataInputStream(clientSocket.getInputStream());
    out = new DataOutputStream(clientSocket.getOutputStream());


    Data p = new Data();
    List<DetailsT> DetailsL = (List<DetailsT>) p.getList();     


     for (DetailsTq : detailsT) {      
        int number; 
        while (true) {
            // as soon as a message is being received, print it out!
            number = in.readInt();
            System.out.println("\n" + "Number: " + number);
        }
     }
    }
}

Furthermore, when the user enters -1 into the program the session should end. I have attempted this in my code although when entering "-1", userA's details are still retrieved. All help would be appreciated, thank-you.

Answers


Assuming number is an attribute in DetailsT class, you can write a method in Data class which returns Details object for number by iterating the array list, e.g.:

public DetailsT findByNumber(int number){
    for(DetailsT details : DetailsL){
        if(details.getNumber() == number){
            return details;
        }
    }
    return null;
}

In main, you can call this method, and if it returns null then, you can prompt user to enter the number again, e.g.:

Data data = new Data();
DetailsT details = data.findByNumber(number);
if(details == null){
 //do something
}else{
 //do something else
}

Need Your Help

C++ - Optional arguments by reference

c++ parameters default-value parameter-passing

I have an exam on C++ coming up, and I'm solving a few ones from past years. I have this question in one of them:

How to calculate Packet loss, Jitter and QoS parameters of video over an IP connection?

android video-streaming qos

I came across a mobile application which performs voice and video quality test to give a measure of the quality of voice/video experience over an IP connection. The test calculates the values of Ji...