Java系统不止一次打印println

时间:2016-03-14 17:10:14

标签: java arraylist system.out

有谁知道为什么"错误!!!"打印6次?这与我的数组列表有关,因为它包含6个人的票证详细信息。 提前谢谢你......

public class Method1 {

public static void main(String[] arg) {
        Method1 sc = new Method1();
        sc.run();
    }

    private void run() {
        PersonData p = new PersonData();
        List<PersonType> personDetailsList = (List<PersonType>) p.getList();
        int input;
        try {
            do {
                Scanner in = new Scanner(System.in);
                System.out.println("Enter person ticket number");
                input = in.nextInt();
                for (PersonType q : personDetailsList) {
                    if (q.getPersonNumber() == input) {
                        System.out.println("Person Ticket Number: " + q.getPersonNumber() + "\n" 
                                + "Person Ticket Name: " + q.getPersonName() + "\n");
                        break;
                    }

                    else if (q.getPersonNumber() != input) {
                    System.out.println("Wrong!!!");     

                    }
                }
            } while (input != -1);
            System.out.println("Bye");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个

private void run() {
        PersonData p = new PersonData();
        List<PersonType> personDetailsList = (List<PersonType>) p.getList();
        int input;
        boolean flag = false;
        try {
            do {
                Scanner in = new Scanner(System.in);
                System.out.println("Enter person ticket number");
                input = in.nextInt();
                for (PersonType q : personDetailsList) {
                    if (q.getPersonNumber() == input) {
                        System.out.println("Person Ticket Number: " + q.getPersonNumber() + "\n" 
                                + "Person Ticket Name: " + q.getPersonName() + "\n");
                        flag=true;                           
                        break;
                    }
                }
                if(!flag){
                    System.out.println("Wrong!!!");     
                }
            } while (input != -1);
            System.out.println("Bye");
        } catch (Exception e) {
            System.out.println(e);
        }
    }