사용자가 입력한 수만큼 동적으로 공간을 할당하고
해당 수만큼 반복하여 숫자를 입력받고 출력하는 기능 구현

예) 크기입력 : 3
     10
     20
     30
     입력한 값 : 10 20 30

 

#include <iostream>
using namespace std;

int main()
{
 int *p;
 int num;

 cout << "크기입력:";
 cin >> num;
  
 p = new int[num]; // num의 크기만큼 int형의 공간 생성

 for(int i=0; i<num; i++)
 {
  cout << "숫자 " << i << " 입력 : ";
  cin >> p[i];  // cin >> *(p + i);
 }

 cout << "사용자가 입력한 값은 ";
 for(int i=0; i<num; i++)
 {
  cout << "\t" << p[i];
 }
 cout << endl;

 delete [] p;

 return 0;
}

비주얼 스튜디오 2008 Express Edition (SP1 포함) 한글판 다운로드 : http://go.microsoft.com/?LinkId=8310629

 

 

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

import javax.swing.*;

public class AcidRainGame extends JFrame implements ActionListener, Runnable {
 static final int WIDTH = 400;
 static final int HEIGHT = 400;
 int life = 10;
 Vector<String> words;
 Vector<Word> viewingWords;
 BufferedReader inputStream;
 Thread t;
 long time;
 
 DropArea da1;
 JTextField t1;
 
 public AcidRainGame() throws IOException {
  // 단어 목록 읽기
  setTitle("산성비");
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  try {
   inputStream = new BufferedReader(new FileReader("words.txt"));
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  words = new Vector<String>();
  viewingWords = new Vector<Word>();
  String w;
  while((w = inputStream.readLine()) != null)
  {
   words.add(w);
  }
  da1 = new DropArea();
  da1.setPreferredSize(new Dimension(WIDTH, HEIGHT));
  add(da1, BorderLayout.CENTER);
  t1 = new JTextField(20);
  t1.addActionListener(this);
  add(t1, BorderLayout.SOUTH);
  
  t = new Thread(this);
  
  pack();
  setVisible(true);
  t.start();
 }
  
 @Override
 public void actionPerformed(ActionEvent e) {
  // TODO Auto-generated method stub
  int index = -1;
  for(Word w : viewingWords) {
   if(t1.getText().equals(w.str))
   {
    index = viewingWords.indexOf(w);
   }
  }
  if(index != -1)
  {
   viewingWords.remove(index);
   repaint();
  }
  t1.selectAll();
 }

 @Override
 public void run() {
  // TODO Auto-generated method stub
  while(true)
  {
   try {
    t.sleep(100);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   time++;
   
   for(Word w : viewingWords)
   {
    w.y += 10;
   } 

   if(!viewingWords.isEmpty())
   {
    if(viewingWords.get(0).y > HEIGHT-50)
    {
     life--;
     viewingWords.remove(0);
    }
   }
   
   if(life <= 0)
   {
    JOptionPane.showMessageDialog(this, "게임종료(게임시간:" + time/10.0 + "초)");
    t.stop();
   }
   
   if(time % 50 == 0)
   {
    viewingWords.add(new Word());
   }

   
   repaint();
   
  }
  
 }
 
 class DropArea extends JComponent
 {
  public void paint(Graphics g)
  {
   g.drawString("life="+life, 10, 10);
   for(Word w: viewingWords)
   {
    g.setColor(Color.BLACK);
    g.drawString(w.str, w.x, w.y);
   }
  }
 }
 
 class Word
 {
  public int x;
  public int y;
  String str;
  
  Word()
  {
   x = (int) (Math.random() * WIDTH - 40);
   y = 0;
   
   str = words.get((int)(Math.random() * words.size()));
  }
 }

 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
  new AcidRainGame();
 }

}

 

words.txt

 

'프로그래밍언어 > JAVA' 카테고리의 다른 글

제너릭 실습  (0) 2015.02.13
Java 패키지 실습 - 로또번호추첨기  (0) 2015.02.11
스윙 컴포넌트 2 실습  (0) 2015.02.09
마우스 이벤트 실습  (0) 2015.02.06
실습  (0) 2015.01.13

 

main.cpp

 

뽑기.cpp

 

뽑기.h

 

상품.cpp

 

상품.h

 

class Rectangle <T extends Number>
{
 T x;
 T y;
 T w;
 T h;
 
 void setX(T x) { this.x = x; }
 void setY(T y) { this.y = y; }
 void setW(T w) { this.w = w; }
 void setH(T h) { this.h = h; }
 T getX() { return x; }
 T getY() { return y; }
 T getW() { return w; }
 T getH() { return h; }
 
 Number calcArea()
 {
  if(w instanceof Integer)
   return w.intValue() * h.intValue();
  else
   return w.doubleValue()*h.doubleValue();
 }
}

public class Test {
 public static void main(String[] args) {
  Rectangle<Integer> r1 = new Rectangle<>();
  Rectangle<Double> r2 = new Rectangle<>();
  
  r1.setH(100);
  r1.setW(200);
  
  r2.setW(123.45);
  r2.setH(456.78);
  
  System.out.println(r1.calcArea());
  System.out.println(r2.calcArea());
  
  
 }
}

 

'프로그래밍언어 > JAVA' 카테고리의 다른 글

산성비 게임 실습  (0) 2015.02.26
Java 패키지 실습 - 로또번호추첨기  (0) 2015.02.11
스윙 컴포넌트 2 실습  (0) 2015.02.09
마우스 이벤트 실습  (0) 2015.02.06
실습  (0) 2015.01.13

 

 

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
 ifstream f;
 string eng, kor, answer;
 int o = 0, x = 0;

 f.open("answer.txt");

 while(!f.eof())
 {
  f >> eng >> kor;
  cout << eng << endl;
  cout << "답 입력 : ";
  cin >> answer;
  if(kor == answer)
  {
   cout << "맞았습니다." << endl;
   o++;
  }
  else
  {
   cout << "틀렸습니다." << endl;
   x++;
  }
 }
 cout << "정답개수 : " << o << ", 오답개수 : " << x << endl;

 f.close();


 return 0;
}
 

 

answer.txt

 

'프로그래밍언어 > C & CPP' 카테고리의 다른 글

Visual Studio 2008 Express 다운로드 링크  (0) 2016.06.04
뽑기 게임 실습  (0) 2015.02.26
C++ 중간정리 실습 - 분산  (0) 2015.02.11
C++ 중간정리 실습 - 용병  (0) 2015.02.11
클래스 최종 실습 - 자판기  (0) 2015.01.10

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class MyFrame {
 public static void main(String[] args) {
  int[] arr = new int[6];
  Random r = new Random();
  
  long t1 = System.currentTimeMillis();
  
  for(int i=0; i<6; i++)
  {
   int num;
   boolean chk;
   
   do {
    chk = false;
    num = r.nextInt(45) + 1;
    for(int j=0; j<i; j++)
    {
     if(arr[j] == num)
      chk = true;
    }
   } while(chk);
   
   arr[i] = num;
  }
  
  Arrays.sort(arr);
  
  for(int i: arr)
   System.out.print(" "+i);
  System.out.println();
   
  Thread.sleep(1000);
  long t2 = System.currentTimeMillis();
  
  System.out.println("총 수행시간은 " + (t2-t1) + "ms");
  
 }
}

 

'프로그래밍언어 > JAVA' 카테고리의 다른 글

산성비 게임 실습  (0) 2015.02.26
제너릭 실습  (0) 2015.02.13
스윙 컴포넌트 2 실습  (0) 2015.02.09
마우스 이벤트 실습  (0) 2015.02.06
실습  (0) 2015.01.13

 

#include <iostream>
using namespace std;

typedef struct {
 int 영어점수;
 int 수학점수;
} 학생;

int main()
{
 int num;

 cout << "학생수 입력 : ";
 cin >> num;

 학생 *p = new 학생[num];

 // 학생의 점수를 입력
 for(int i=0; i<num; i++)
 {
  cout << i+1 << "번째 학생의 점수 입력" << endl;
  cout << "영어점수 : ";
  cin >> p[i].영어점수;
  cout << "수학점수 : ";
  cin >> p[i].수학점수;
 }

 int engSum = 0;
 int matSum = 0;
 // 학생의 총점
 for(int i=0; i<num; i++)
 {
  engSum += p[i].영어점수;
  matSum += p[i].수학점수;
 }

 // 평균
 int engAvg = engSum / num;
 int matAvg = matSum / num;

 // 분산
 int engDis = 0;
 int matDis = 0;
 for(int i=0; i<num; i++)
 {
  engDis += (p[i].영어점수 - engAvg) * (p[i].영어점수 - engAvg);
  matDis += (p[i].수학점수 - matAvg) * (p[i].수학점수 - matAvg);
 }
 engDis = engDis / num;
 matDis = matDis / num;

 cout << "영어점수에 대한 평균 : " << engAvg << ", 분산 : " << engDis << endl;
 cout << "수학점수에 대한 평균 : " << matAvg << ", 분산 : " << matDis << endl;

 delete [] p;

 return 0;

 

 

#include <iostream>
using namespace std;

typedef struct {
 int 체력;
 int 총알개수;
} 용병;

void 초기화(용병 &a);
void 피격(용병 &a);
void 회복(용병 &a);
void 발사(용병 &a);
void 재장전(용병 &a);

int main()
{
 용병 a1;
 
 초기화(a1);

 while(1)
 {
  char ch;
  cin >> ch;
  
  if(ch == 'q')
   break;

  if(ch == '1')
   피격(a1);
  else if(ch == '2')
   회복(a1);
  else if(ch == '3')
   발사(a1);
  else if(ch == '4')
   재장전(a1);
 }

 return 0;
}

void 초기화(용병 &a)
{
 a.체력 = 100;
 a.총알개수 = 2;
 cout << "체력 " << a.체력 << ", 총알개수 " << a.총알개수 << "개로 초기화 되었습니다." << endl;
}

void 피격(용병 &a)
{
 a.체력 -= 10;

 if(a.체력 <= 0)
 {
  cout << "사망했습니다." << endl;
  a.체력 = 100;
 }
 else
 {
  cout << "체력이 10만큼 감소하여 " << a.체력 << "이 되었습니다." << endl;
 }
}

void 회복(용병 &a)
{
 if(a.체력 >= 100)
 {
  cout << "최대체력입니다." << endl;
 }
 else
 {
  a.체력 += 20;
  
  if(a.체력 >= 100)
   a.체력 = 100;

  cout << "체력이 20만큼 회복되어 " << a.체력 << "이 되었습니다." << endl;
 }
}


void 발사(용병 &a)
{
 if(a.총알개수 <= 0)
  cout << "총알이 없습니다. 재장전하십시오." << endl;
 else
 {
  a.총알개수--;
  cout << "현재 총알개수 : " << a.총알개수 << "개" << endl;
 }
}

void 재장전(용병 &a)
{
 a.총알개수 = 2;
 cout << "재장전되었습니다. 현재 총알개수 : " << a.총알개수 << "개" << endl;
}
 

 

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

class MyPanel extends JPanel implements ActionListener, ListSelectionListener, ChangeListener
{
 String[] drinks = {"콜라", "사이다", "환타", "마운틴듀", "레드불"};
 JComboBox combo;
 JList list;
 JSpinner spin;
 
 public MyPanel() {
  combo = new JComboBox(drinks);
  list = new JList(drinks);
  SpinnerListModel model = new SpinnerListModel(drinks);
  spin = new JSpinner(model);
  list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  combo.setSelectedIndex(0);
  list.setSelectedIndex(0);
  combo.addActionListener(this);
  list.addListSelectionListener(this);
  spin.addChangeListener(this);
  
  add(combo);
  add(list);
  add(spin);
 }

 @Override
 public void valueChanged(ListSelectionEvent e) {
  // TODO Auto-generated method stub
  int num = list.getSelectedIndex(); // 리스트에서 인덱스 얻어옴
  combo.setSelectedIndex(num); // 콤보박스에 인덱스 설정
  spin.setValue(list.getSelectedValue());
 }

 @Override
 public void actionPerformed(ActionEvent e) {
  // TODO Auto-generated method stub
  int num = combo.getSelectedIndex(); // 콤보박스에서 인덱스 얻어옴
  list.setSelectedIndex(num); // 리스트에 인덱스 설정
  spin.setValue(combo.getSelectedItem());
 }

 @Override
 public void stateChanged(ChangeEvent e) {
  // TODO Auto-generated method stub
  list.setSelectedValue(spin.getValue(), false);
  combo.setSelectedItem(spin.getValue());
 }
 
 
}


public class MyFrame extends JFrame {
 public MyFrame() {
  setSize(300, 300);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
  add(new MyPanel());
  
  pack();
  setVisible(true);
 }

 public static void main(String[] args) {
  MyFrame t = new MyFrame();
 }

}

'프로그래밍언어 > JAVA' 카테고리의 다른 글

제너릭 실습  (0) 2015.02.13
Java 패키지 실습 - 로또번호추첨기  (0) 2015.02.11
마우스 이벤트 실습  (0) 2015.02.06
실습  (0) 2015.01.13
애니메이션 예제 이미지  (0) 2014.07.31

+ Recent posts