简体   繁体   中英

What code should i add to print out “seat already taken” if user input seats that are taken already or input the same seat?

I am trying to make seat reservation or assignment using one dimensional array. A user input choose 2 sections whether economy class or first class but i dont wanna go that far since i dont understand yet the algorithm. Lets assume user inputs first class and choose seats from seat 1, the user input must be saved in the array. If user inputs the same seat again, it must print out seat already taken. how can i work printing out 'seat already taken' if user inputs seats that are taken or inputs the same seat?

int arr[] = new int[10];


    for(int i=0;i<arr.length;i++)
    {
        System.out.println ("(1)First Class \n(2)Economy Class");
        int section = input.nextInt();

        if(section == 1)
        {
            System.out.println ("Welcome to First Class");
            System.out.println ("Choose Seat from 1-2");
            arr[i] = input.nextInt();

            if(arr[i] == 1)
            {
                            arr[0]=1;
                System.out.println ("Seat #1");
            }
            else if(arr[i] == 2)
            {
                arr[1]=2;
                System.out.println ("Seat #2");
            }
            else if(arr[i] == arr[0] || arr[i]==arr[1])
            {
                System.out.println ("Seat already taken");
            }

        }

I don't seem to understand the relation between the code you've provided and the problem you're trying to solve.

If I understand you correctly, you're trying to see if the array already contains an element which is input by a user. For that, you could do something like this

int a[] = new int[10];
for(int i=0;i<10;i++){
    boolean seatTaken = false;
    int seat = input.nextInt();
    for(int j=0;j<i;j++){
        if(a[j]==seat){
            seatTaken = true;
            break;
        }
    }
    if(seatTaken){
        System.out.println("The Seat has already been taken");
        i = i - 1;
    }else{
       a[i] = seat;
    }
}

Of course, this could be made a lot more efficient by using a HashSet which has a constant lookup time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM