실행코드 ¶
~cpp code
import javax.swing.JOptionPane;
public class NumberBaseBallGame {
private String resultNumber;
private String userNumber;
public static void main(String[] args) {
NumberBaseBallGame game = new NumberBaseBallGame();
game.excute();
}
public void excute() {
// make a result number
createResultNumber();
do {
// input number from user
inputNumber();
// show score
JOptionPane.showMessageDialog(null, checkScore());
} while(checkScore() != "You are correct!");
}
public String inputNumber() {
return userNumber = JOptionPane.showInputDialog(null, "Enter number what you think");
}
public void createResultNumber() {
String fstNum, secNum, trdNum;
do {
fstNum = "" + (Math.random()*10);
secNum = "" + (Math.random()*10);
trdNum = "" + (Math.random()*10);
}while(fstNum.equals(secNum) || secNum.equals(trdNum) || fstNum.equals(trdNum));
resultNumber = fstNum + secNum + trdNum;
}
public String checkScore() {
int numOfStrike = 0;
int numOfBall = 0;
for (int i = 0 ; i < 3 ; i++) {
for (int j = 0 ; j < 3 ; j++) {
if (resultNumber.charAt(i) == userNumber.charAt(j)) {
if (i == j) {
numOfStrike++;
} else {
numOfBall++;
}
}
}
}
if (numOfStrike == 3)
return "You are correct!";
else
return "" + numOfStrike + " Strike, " + numOfBall + " Ball";
}
///////////////////////////////////////////////////////////////
public void setResultNumber(String resultNumber) {
this.resultNumber = resultNumber;
}
public String getUserNumber() {
return userNumber;
}
public String getResultNumber() {
return resultNumber;
}
}
테스트 코드 ¶
~cpp code
import junit.framework.TestCase;
public class NumberBaseBallGameTest extends TestCase {
public NumberBaseBallGame object;
protected void setUp() throws Exception {
object = new NumberBaseBallGame();
}
protected void tearDown() throws Exception {
}
public void testInputNumber() {
String testString = object.inputNumber();
if (testString.charAt(0) == '1' &&
testString.charAt(1) == '2' &&
testString.charAt(2) == '3')
assertTrue(true);
else
assertTrue(false);
}
public void testCreateResultNumber() {
object.createResultNumber();
assertNotSame(object.getResultNumber().charAt(0), object.getResultNumber().charAt(1));
assertNotSame(object.getResultNumber().charAt(1), object.getResultNumber().charAt(2));
assertNotSame(object.getResultNumber().charAt(0), object.getResultNumber().charAt(2));
}
public void testCheckScore() {
object.inputNumber();
object.setResultNumber("132");
assertEquals("1 Strike, 2 Ball", object.checkScore());
}
}
잡담 ¶
- TDD로 만들려고 하니 적응도 안되고 해서 시간이 꽤나 많이 걸리네요^^; 프로그램을 위한 테스트라기 보단 테스트를 위한 프로그램이 되어지는 느낌이 팍팍;;; 하지만 장점이 많은 방법이라 앞으로 더 연습을 해 봐야겠네요~ - 상욱
- 테스트 코드를 갖고 어떻게 해야하는지 잘 모르겠어요. import junit.framework.TestCase 구문이 있던데 이것은 어디서 가져와야 하나요? -_-;; - 문원명
- 내 경험으로는 테스트에 휘둘리기 보다는 테스트를 도구로 여기는 마인드가 중요한 것 같당. 테스트가 우리를 원하는 길로 알아서 인도해주지는 않더라
- JUnit 4.1을 추천합니다. 3~4년 후에는 4.1이 일반화 되어 있겠죠. 사용하다 보니, 4.1은 배열간의 비교까지 Overloading되어 있어서 편합니다. 다음의 예제를 보세요. SeeAlso JUnit in CenterStage --NeoCoin
- 오옷~ 감사해요 상민이형^^ - 상욱
- 오옷~ 감사해요 상민이형^^ - 상욱
- JUnit 4.1을 추천합니다. 3~4년 후에는 4.1이 일반화 되어 있겠죠. 사용하다 보니, 4.1은 배열간의 비교까지 Overloading되어 있어서 편합니다. 다음의 예제를 보세요. SeeAlso JUnit in CenterStage --NeoCoin
~java
package test;
import java.util.Arrays;
import org.junit.Test;
import static org.junit.Assert.*;
public class JUnit41Test {
@Test
public void name() {
String[] actual = { "1", "2", "3" }, expect = { "1", "2", "3" };
Integer[] actual2 = { 1, 2, 3 }, expect2 = { 1, 2, 3 };
assertEquals(Arrays.asList(actual), Arrays.asList(expect));
assertEquals(actual, expect);
assertEquals(actual2, expect2);
}
}
~java
import java.util.Arrays;
import junit.framework.TestCase;
public class JUnit38Test extends TestCase {
public void name() {
String[] actual = { "1", "2", "3" }, expect = { "1", "2", "3" };
Integer[] actual2 = { 1, 2, 3 }, expect2 = { 1, 2, 3 };
assertEquals(Arrays.asList(actual), Arrays.asList(expect));
assertEquals(actual, expect);
assertEquals(actual2, expect2);
}
}
~python
# -*- coding: cp949 -*-
LENGTH,START,END,TURN_LIMIT=3,100,999,8
def Answer():
from random import randint
while True:
answer = str(randint(START,END))
if len(set(answer)) == LENGTH: return answer
def Question():
while True:
try:
question=raw_input('숫자를 입력해 주세요. : ')
if len(question) == LENGTH and len(set(question)) == LENGTH:
return question
else: raise ValueError
except ValueError:
print '--0으로 시작하지 않는, 겹치지 않는 숫자 %d개를 넣어 주세요.--'%LENGTH
def Compare(answer,question):
strike,ball,out=0,0,0
for idx,i in enumerate(question):
if question[idx] == answer[idx]:strike += 1
elif i in answer: ball +=1
else: out+=1
return [strike,ball,out]
def Show(sbo,count, end=True):
if isEnd:print '%d 회 스트라이크 아웃!' % count
else: print '%d 회 %d 스트라이크 %d 볼 %d 아웃' % tuple([count]+sbo)
answer=Answer()
print answer
for count in xrange(1,TURN_LIMIT+1):
sbo = Compare(answer,Question())
isEnd = sbo[0] == LENGTH
Show(sbo,count,isEnd)
if isEnd:break
else:print '%d회 시도 실패하였습니다.' %count
- ㅋ... Python... 요새 조금씩 보고 있지만 쓰기 괜찮은 언어라고 생각이 들더군요^^ - 상욱
- 나는 Python이든, Perl이든 반드시 학습 해야된다고 생각한다. 그래야 다른 언어들을 잘 쓸수 있었다. 예를들어 Java Collection Framework를 알고는 있었지만 잘 손이 안나갔는데, STL과 Python을 익히고 나니까 아주 손쉽게 쓰게 되더구나.
- 이 언어들의 시작점으로는 간단한 계산이 필요할때 계산기보다 열기보다 늘 IDLE나 rib(ruby)를 열어서 계산을 하지. 예를들어서 et-house환급코드 in CenterStage 같은 경우도 그래. 아 그리고 저 코드 군에 있을때 심심풀이 땅콩으로 짜논거. SeeAlso 숫자야구 in CenterStage
- 허나 과거는 잊어버리는 모양이다. 열혈강의 Python을 보니 옆면에 열심히 본 흔적이 있군. Ruby도 SVN history를 보니 흔적이 많이 남아있고.. 어느정도 시간을 투자해야 되는 것 같아. --NeoCoin
- 나는 Python이든, Perl이든 반드시 학습 해야된다고 생각한다. 그래야 다른 언어들을 잘 쓸수 있었다. 예를들어 Java Collection Framework를 알고는 있었지만 잘 손이 안나갔는데, STL과 Python을 익히고 나니까 아주 손쉽게 쓰게 되더구나.
- Python Good~! 요새는 파이썬만 씀.. ㅋ - (namsnag)
JTDStudy/첫번째과제










