1

I have two arrayList in a class, one which stores cars and another who stores vans.

I want to have an option to display all the info from a specific array. For example, press 1 for cars or press 2 for vans.

I managed to make something but it's not working properly, after I choose 2, it shows me all the vans but instead of proceeding with next line it and ask which model to rent, it asks again to " press 1 for cars, press 2 for vans".

Here is the code, I hope u understand my question

List<Van> vanlist = new ArrayList();
    vanlist.add(new Van("Mercedes", "Van2", "VBC842", 300, 500));
    vanlist.add(new Van("Mercedes", "Van3", "VBC489", 300, 500));
    vanlist.add(new Van("Mercedes", "Van1", "VBC970", 300, 500));
    vanlist.add(new Van("Mercedes", "Van4", "VBC153", 300, 500));

    Scanner input = new Scanner(System.in);
    System.out.print("Type 1 for cars; Type 2 for vans; Type 3 for trucks \n");
    int vop = input.nextInt();  
    for(Van van: vanlist) {
        if (vop == 2) {
            System.out.println(van);
        }  
    }

    System.out.print("Type 1 for cars; Type 2 for vans; Type 3 for trucks \n");
    int opt = input.nextInt();  
    for(Car car: carlist) {
        if (opt == 1) {
            System.out.println(car);

        }       
    }

    System.out.print("Enter model to rent: ");
    String model = input.nextLine();
Regolith
  • 2,944
  • 9
  • 33
  • 50
enjustice
  • 11
  • 2
  • You are asking it again see second `System.out.print("Type 1 for cars; Type 2 for vans; Type 3 for trucks \n");` . Your code is working fine. I didn't get the fact that why are you using two variables, `vop and opt` when you can use one with `SWITCH CASE`. – Lalit Fauzdar Aug 10 '17 at 12:11

1 Answers1

0

You can use this code.

List<Van> vanlist = new ArrayList();
    vanlist.add(new Van("Mercedes", "Van2", "VBC842", 300, 500));
    vanlist.add(new Van("Mercedes", "Van3", "VBC489", 300, 500));
    vanlist.add(new Van("Mercedes", "Van1", "VBC970", 300, 500));
    vanlist.add(new Van("Mercedes", "Van4", "VBC153", 300, 500));

    Scanner input = new Scanner(System.in);
    System.out.print("Type 1 for cars; Type 2 for vans; Type 3 for trucks \n");
    int vop = input.nextInt();  
    Switch(vop){
    case 1:
    for(Van van: vanlist)             
            System.out.println(van);         
    break;

    case 2:     
    for(Car car: carlist)
            System.out.println(car);  
    break;
    default:
    System.out.println("Invalid Choice");
    break;
    }
    System.out.print("Enter model to rent: ");
    String model = input.nextLine();

See here, you don't have to use two variables. This will work for you.

Lalit Fauzdar
  • 5,953
  • 2
  • 26
  • 50
  • Thanks a lot, it fixed my problem. However, now, the program terminates after that last line. What can be the issue ?[The program terminates after String model = input.nextLine();][1] [1]: https://i.stack.imgur.com/Yp53c.png – enjustice Aug 22 '17 at 06:56