mrScarlett

Array of Objects

Jan 19th, 2017
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. class Example
  4. {
  5. public static void main (String[] args){
  6. Scanner input= new Scanner(System.in);
  7. // to declare an array of objects
  8. //declare a regular array: int [] nums = new int[10];
  9. Car [] cars = new Car[2];// really array of reference variables not really objects
  10. String temp,temp2;
  11. //assigning values
  12. //cars[0] = new Car(); // we could do the same for every reference in the array
  13.  
  14. //instead for loop
  15.  
  16. for (int i=0; i<cars.length; i++){
  17. System.out.println("enter car model");
  18. temp=input.next();
  19. cars[i]=new Car();
  20. cars[i].setModel(temp);
  21. System.out.println("enter car colour");
  22. temp2= input.next();
  23. cars[i].setColour(temp2);
  24. }
  25. for (int i =0; i<cars.length; i++){
  26. System.out.println("Model: "+cars[i].getModel());
  27. System.out.println("Colour: "+cars[i].getColour());
  28. }
  29.  
  30. System.out.println("Search for a car colour");
  31. String search=input.next();
  32. for (int x=0; x<cars.length; x++){
  33. String res = cars[x].getColour();
  34. if (res.equals(search)){
  35. System.out.println("A "+cars[x].getColour()+" "+cars[x].getModel()+" found");
  36.  
  37. }
  38. }
  39. }
  40. }
Add Comment
Please, Sign In to add comment