상세 컨텐츠

본문 제목

[java] 클래스(class) 연습문제 #2

java

by ~지우~ 2021. 6. 29. 10:28

본문

728x90

오늘은 「java_an_introduction_to_problem_solving_and_programming_6th_edition」 363페이지 9번 문제를 풀어보겠습니다.

<문제>

출처: java_an_introduction_to_problem_solving_and_programming_6th_edition 

 

팀의 이름과 점수를 입력하면 각 팀의 총 점수와 이기는 팀을 출력하는 코드를 작성해야 합니다.

 

 

package myPackage;

public class BasketBallGame {
	public String firstTeamName, secondTeamName, status;
	public int firstTeamScore, secondTeamScore;
	
	public void onePointToFirstTeam() {
		firstTeamScore +=1;
	}
	public void twoPointToFirstTeam() {
		firstTeamScore +=2;
	}
	public void threePointToFirstTeam() {
		firstTeamScore +=3;
	}
	public void onePointToSecondTeam() {
		secondTeamScore +=1;
	}
	public void twoPointToSecondTeam() {
		secondTeamScore +=2;
	}
	public void threePointToSecondTeam() {
		secondTeamScore +=3;
	}
	
	public void returnScore() {
		System.out.print(firstTeamName + " " + firstTeamScore + ", " + secondTeamName + " " + secondTeamScore + "; ");
	}
	
	public void winningTeam() {
		if (firstTeamScore > secondTeamScore) {
			System.out.println(firstTeamName + " are winning.");
		}
		else if(firstTeamScore < secondTeamScore) {
			System.out.println(secondTeamName + " are winning.");
		}		
	}
	
	public String status() {
		status = "finished" ;
		return status;
	}
}

 

이 클래스를 메인함수에서 실행해보겠습니다.

package myPackage;
import java.util.Scanner;
public class BasketballGameDemo {

	public static void main(String[] args) {
		
		
		BasketBallGame b = new BasketBallGame();
		
		b.firstTeamName = "Cats";
		b.secondTeamName = "Dogs";
		
		while(true) {
			System.out.println("Enter a score: ");
			Scanner keyboard = new Scanner(System.in);
			int inputGrade;
			String inputTeamName;
			
			inputTeamName = keyboard.next();
			inputGrade = keyboard.nextInt();
			
			if(inputTeamName.equals("a")) {
				if(inputGrade == 1) {
					b.onePointToFirstTeam();
				}
				else if(inputGrade == 2) {
					b.twoPointToFirstTeam();
				}
				else if(inputGrade == 3) {
					b.threePointToFirstTeam();
				}
			}
			else if(inputTeamName.equals("b")) {
				if(inputGrade == 1) {
					b.onePointToSecondTeam();
				}
				else if(inputGrade == 2) {
					b.twoPointToSecondTeam();
				}
				else if(inputGrade == 3) {
					b.threePointToSecondTeam();
				}
			}
		
			b.returnScore();
			b.winningTeam();
			
			
			//included the statement that if one team gets 10 score, the game ends.
			if(b.firstTeamScore == 10 || b.secondTeamScore ==10) {
				String currStatus = b.status();
				System.out.println(currStatus);
				break;
			}
		
		}	
		
		
	}

}
728x90

'java' 카테고리의 다른 글

[java] 상속(Inheritance) 연습문제  (0) 2021.07.07
[java] 배열 연습문제 #2  (0) 2021.07.06
[java] 배열 연습문제 #1  (0) 2021.07.05
[java] 클래스(class) 연습문제 #3  (0) 2021.07.03
[java] 클래스(class) 연습문제 #1  (0) 2021.06.28

관련글 더보기

댓글 영역