Java) Enter 입력 후 10초에 가까운 사람이 승리하는 게임

kys·2022년 9월 19일
0

Java

목록 보기
1/4

import java.util.Calendar;
import java.util.Scanner;

class Timeset {
	private int a, result1;
	private String name;

	public Timeset(String name) {
		this.name = name;

		System.out.print(name + "시작 <Enter>키>>");

		get_second(); // 초를 받는 알고리즘
	}

	// 종료 후 몇 초인지 계산하는 메소드
	public void result(int s, int f, int a, int b) {
		int result = 0;
		int count = 0;

		if(s == f) { // 시작한 분(minute)이 종료한 분(minute) 같으면
			// 시작한 초(second)에서 종료한 초(second)를 뺀다
			result = Math.abs(a - b);; 
		}else { // 그게 아니면 1분 이상이 지났기 때문에
			count = f - s; // 종료한 분(minute)에서 시작한 분(minute)을 빼준 값을
			b += 60 * count; // 곱해주어 종료한 초에 더해준다 
			result = Math.abs(a - b); // 계산
		}

		this.result1 = result; // 결과 값 저장
	}

	public int result1() { // 결과 리턴
		return result1;
	}

	public void get_second() { // 초를 받는 알고리즘
		Scanner sc = new Scanner(System.in);
		String str;
		int s_second, f_second, s_min, f_min, result_second, count1, count2;
		
		str = sc.nextLine(); // Enter 입력

		while(true) {
			s_second = a_second(); // Enter 이후 시작시간 초(second)를 입력받는 메소드
			s_min = a_min(); // Enter 이후 시작시간 분(minute)을 입력받는 메소드

			System.out.println("현재 초 시간 = " + s_second);
			System.out.print("10초 예상 후 <Enter>키>>");
			str = sc.nextLine(); // Enter 입력
			
			f_second = a_second(); // Enter 이후 종료시간 초(second)를 입력받는 메소드
			f_min = a_min(); // Enter 이후 시작시간 분(minute)을 입력받는 메소드

			System.out.println("현재 초 시간 = " + f_second);

			// 종료 후 몇 초인지 계산하는 메소드
			result(s_min, f_min, s_second, f_second);

			break;
		}
	}

	public int a_second() { // Enter 이후 시작시간 초(second)를 입력받는 메소드
		int a;
		Calendar now = Calendar.getInstance();
		a = now.get(Calendar.SECOND); // a에 초(second)를 입력

		return a;
	}

	public int a_min() {
		int a;
		Calendar now = Calendar.getInstance();
		a = now.get(Calendar.MINUTE); // a에 분(minute)를 입력

		return a;
	}

}

public class hh {
	public static void main(String ar[]) {
		int result, name1_result, name2_result = 0;

		System.out.println("10초에 가까운 사람이 이기는 게임입니다.");

		Timeset name1 = new Timeset("황기태");
		Timeset name2 = new Timeset("이재문");

		name1_result = name1.result1();
		name2_result = name2.result1();

		if(Math.abs(name1_result - 10) < Math.abs(name2_result - 10) ) {
			System.out.println("황기태의 결과 " + name1.result1() + ", 이재문의 결과 "
	                  + name2.result1() + ", 승자는 황기태 ");
		}else {
			System.out.println("황기태의 결과 " + name1.result1() + ", 이재문의 결과 "
	                  + name2.result1() + ", 승자는 이재문 ");
		}
	}
}


  • Enter 이후 시작시간 초(second)를 입력받는 것에서 시간이 지나도 같은 초만 나오는 오류가 있었는데, 한 메소드 안에서 get(Calendar.SECOND); 를 실행시키면 그 메소드를 실행한 시간 초를 계속 리턴하는 것 같다.
    그 해결방안으로 get(Calendar.SECOND);를 따로 메소드를 만들어서 진행하니 해결되었다.
  • 1분 이상이 지나도 초(second) 값을 계산하는 것을 코딩하기에 어려움을 겪었다.

결국 해결 완료 :)


profile
:)

0개의 댓글