JAVA Programming for Beginners...

JAVA, 초보

카드덱을 구성해 볼까요?

ArrayList

지난 시간에 카드 클래스를 만들었습니다. 카드 한 장을 의미하는 것이죠. 카드 한 장을 가지고는 게임을 진행 할 수 없습니다.

그 카드를 가지고있는 카드덱을 만들어야지요..

가지고 있다멤버 변수이지요?

CardDeck 클래스에는 카드가 20장 필요합니다. 카드 20...

Card card1 = new Card("", 1);

Card card2 = new Card("", 1);

Card card3 = new Card("", 2);

Card card4 = new Card("", 3);

...

Card card20 = new Card("", 10);

--> 이런식으로 만드는 것은 아닙니다.. 안될건 없지만... ~ 아니올시다~ 입니다.

 

다들 아시겠지만 그래서 나온 것이 배열입니다.

얘기 했는가 모르겠는데 자바에서는 배열도 객체입니다.(자바에서는 모든게 객체라고 했지요??)

Card[] cardDeck = new Card[20]; // 카드객체가 만들어 지는게 아니라.. 카드에 대한 배열객체가 만들어집니다..

요런 식으로 배열을 만들어서 사용하시면 됩니다.

이건 머.. c랑 똑같잖아!!  자반데... 뭐 없어요?? 하시는 분들이 계실껍니다..

그래.. 자반데...

그래서 ArrayList를 제공합니다.

자바5에 들어와서 C와는 확연하게 차이를 보이며, 편해진 기능(클래스)가 바로 ArrayList입니다.

크기를 지정해서 사용하지 않으며, 개체를 추가하거나, 삭제, 길이를 알아본다거나 마음대로 섞고, 정렬할 수도 있습니다. Java API를 참고하세요.. (java.util.ArrayList)

이 ArrayList는 굉장히 많이 쓰입니다. 정말..정말.. 많이 쓰이므로 사용법을 확실하게 알아두세요!!

(안드로이드 프로그램을 공부하실 때에도 많이 쓰인답니다...) 

ArrayList를 사용하시려면, java.util패키지의 ArrayList를 포함 시켜야 합니다.

자바파일 맨 위에 import java.util.ArrayList; 라고 임포트문을 넣으셔야 합니다.

안그러면 ArrayList라는 클래스를 찾지 못하게 됩니다.

패키지 작성법도 나중에 다~ 배우게 될 겁니다.. ㅎㅎ

ArrayList<Card> myCardDeck;              // Card객체를 담을 수 있는 myCardDeck을 ArrayList로 만듭니다.

myCardDeck = new ArrayList<Card>(); // 새로운 ArrayList<Card>객체를 생성하셔서 인스턴스 변수에 연결하면.. 끝!

myCardDeck.add(Card one);               // 추가하거나

myCardDeck.remove(Card one); 혹은 myCardDeck.remove(int index);  // 삭제하면서 사용!

이렇게 쓰시면 됩니다.

이 카드덱을 가지고 있는(멤버 변수) 클래스를 만듭니다... -> 문서화 잊지마세요..

  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. /**
  4. * CardDeck클래스 일반적인 카드덱을 의미합니다. <br />
  5. * CardDeck은 추상클래스로 인스턴스화 하지 못합니다. <br />
  6. * 이 카드덱을 확장하여(상속받아) 구체적인 카드덱을 생성하도록 할 것입니다. <br />
  7. * 이 카드덱으로 트럼프, 화투 등의 여러 가지 구체적인 카드덱을 생성할 수 있습니다.
  8. * @author 내이름
  9. * @version 1.0
  10. * @see Card
  11. */
  12. public abstract class CardDeck {
  13.      private ArrayList<Card> deck; // 멤버로 Card클래스를 담는 ArrayList인 deck을 가지고 있네요!!
  14. /**
  15. * 각각의 메소드에 대한 설명.. 잊지 마세요!!! 나중에 하려면 귀찮아 집니다..
  16. */
  17.  
  18. /**
  19. * 생성자들..도 각각 설명을 자세하게 주석을 달아주세요!!!
  20. */
  21.      public CardDeck(){
  22.            deck = new ArrayList<Card>();
  23.      }
  24.      public CardDeck(ArrayList<Card> setDeck){
  25.            deck = new ArrayList<Card>();
  26.            deck = setDeck;
  27.      }
  28.      public CardDeck(String[] aShape, int[] aNum){
  29.            deck = new ArrayList<Card>();
  30.            Card addCard = new Card();
  31.            for(String shape:aShape){ // 재미있는 for문이 나왔지요? 요런형태로 배열을 순회합니다.
  32.                  for(int num:aNum){
  33.                        addCard = new Card(shape, num);
  34.                        deck.add(addCard);
  35.                  }
  36.            }
  37.      }
  38. /**
  39. * shuffle메소드는 Collections객체의 static클래스를 가져다 사용합니다.
  40. */
  41.      public void shuffle(){
  42.            Collections.shuffle(deck); // 요셔플 때문에 Collections클래스를 임포트
  43.      }
  44.      public Card getOne(){
  45.            Card rtnCard=null;;
  46.            if(deck.size()!=0){
  47.                  rtnCard = deck.remove(0);
  48.            }
  49.            return rtnCard;
  50.      }
  51.      public int size(){
  52.            return deck.size();
  53.      }
  54.      public boolean add(Card one){
  55.            return deck.add(one);

댓글

댓글 본문
  1. aafreen
    If you eagerly wanted to know what is amazon prime video then the answer is amazing. It is more than a fast delivery option. Amazon Prime is a subscription service provided by the https://amazoncom-mytvcode.com with unlimited entertainment with lots of other benefits.
  2. aafreen
    Follow the below-stated steps to activate Amazon Prime Video on your Smart TV now: GO to https://code-amazon.com the home page of the Smart TV and search for Amazon Prime Video. Amazon App will open in front of you. Here you will find “Register https://code-amazon.com/mytv on the Amazon Website” and “Sign in and Start”.
  3. aafreen
    Amazon Prime through https://tv-amazon.com is accessible to owners of streaming platforms and devices like https://tv-amazon.com/mytv Chromecast, Fire TV, Amazon TV, and Roku, among others.
  4. aafreen
    Please enter the code displayed on your TV. Contact Us. If you are human, leave this field blank. Registration code * Register https://primevideocom-mytv.com Device. How to watch Amazon Prime Video on Different Devices: Complete Guide . Amazon Prime Video https://amazonmytv-code.com is one of the best platforms to watch movies and TV shows continuously on the internet
  5. aafreen
    Follow the below-stated steps to activate Amazon Prime Video on your Smart TV now: GO to https://primevideo-amazon.com/mytv the home page of the Smart TV and search for Amazon Prime Video. Amazon App will open in front of you. Here you will find “Register https://primevideo-amazon.com/mytv on the Amazon Website” and “Sign in and Start”.
  6. aafreen
    Search your Smart TV’s app store or the Amazon Prime app. Download https://amazon-mytvcode.com and add it to the channel. Open the app and click https://primevideo-amazon.com on amazon my tv the ‘Register on the Amazon website’ link.
  7. aafreen
    Begin with downloading, introducing, and actuating https://sites.google.com......ce/ utilizing a legitimate item key. Additionally locate the key highlights of all Office variants.
  8. aafreen
    the antivirus protection in Norton solutions uses advanced machine learning and emulation to determine whether files are good or bad, but Norton device security also has more ways https://sites.google.com......to/ to help protect your computer beyond antivirus.
  9. aafreen
    AVG Retail Card is an alpha-numeric code set and combination that enables users to enable, access and run avg antivirus on the device. To trigger the avg product the code is needed. User will trigger avg retail card on the url: https://sites.google.com......il/ website. They should be able to access and update Avg antivirus into their device afterwards.
  10. aafreen
    create Hulu account: https://sites.google.com......lu/ After that, get the device’s Hulu activation code.To complete the activation process, the activation code is required. You will receive your favorite channels, shows, films, web shows online in one location with Hulu after the activation has been completed.
  11. aafreen
    Roku provides the simplest way to stream entertainment to your TV. On https://sites.google.com......nk/ your terms. With thousands of available channels to choose from.
  12. aafreen
    Install Webroot at https://sites.google.com......t/- Internet is the basic need in this modern world of technology for getting various information, even for transactions, shopping, and much more. Theexcess use of the internet invites various malware and inferior elements into the system.
  13. aafreen
    McAfee Security Scan icon on your computer screen is the virus scanning tool downloaded while you downloaded McAfee antivirus from https://sites.google.com......ee/ card on your device
  14. aafreen
    Norton antivirus is an industry-leading IT and commercial program that works https://sites.google.com......up/ to eradicate harmful virus on your windows, mac system.All Norton users fight the security of phishing versus component malware in real time.
  15. aafreen
    office.com/setup will help you to deploy the office setup successfully on your device. Here are easy steps to download, install https://sites.google.com......up/ and activate office setup. Visit office setup now.
  16. aafreen
    To reset your password using the Apple Support app on a friend or family member's device, the device owner will need to download https://sites.google.com......id/ the Apple Support app
  17. aafreen
    There is 2 way to install & activate Webroot Security. Kindly read each section and find out which process is suitable for you. Activation Process for Windows / MAC Computers: – (If Webroot Security is already installed on your computer) 1:- Kindly check your Order https://sites.google.com......on/ Confirmation email and copy or make a note of the Product License Key.
  18. aafreen
    A McAfee 25 digit code is on your McAfee retail card if you purchased your McAfee from https://sites.google.com......ey/ an offline store like Bestbuy, staples, or any other offline store. You need to check the back of your retail card and you need to peel that place where the activation code is written.
  19. aafreen
    AVG internet security license key 2020 Technologies is a favorite amongst customers searching for https://sites.google.com......il/ efficient solutions to shield their computer systems in opposition to all famous varieties of malware, including viruses, Trojans, worms, rootkits, dialers, spyware, and spyware.
  20. aafreen
    If you want to activate Hulu on Roku TV, you will have to obtain the Hulu https://sites.google.com......lu/ Roku activation code or the Hulu plus Roku activation code. Once you have the code, you can use it to activate https://sites.google.com......ce/ any other device that supports Hulu.
  21. aafreen
    Submit the activation code at https://sites.google.com......up/ to connect the device to your account. If the device fails to link a second time, unplug the power cord and wait five to 10 seconds. Connect the power cord again to reboot the device. If the device still does not link https://sites.google.com......ce/ to your Roku account, reset it to factory defaults
  22. aafreen
     Enter your email address and keycode to register your product. 2. Click https://sites.google.com......ot/ NEXT. 3. Follow the instructions on the next page to install your product on the device you’re currently using.
  23. aafreen
     If you are staying at the same version, you can go ahead and purchase https://sites.google.com......fe/ the new key code from Webroot at any time, but do NOT activate https://sites.google.com......ot/ it. Once you have the new key code do NOT activate it.
  24. aafreen
    Mcafee Enter Product Key Code Setup mcafee antivirus by visiting https://sites.google.com......ee/ and mcafee enter product key code. This Mcafee Activation Code https://sites.google.com......ee/ is 25-digit alphanumeric unique code.
graphittie 자세히 보기