Skip to content

Instantly share code, notes, and snippets.

@zhyunk
Last active April 12, 2023 01:20
Show Gist options
  • Save zhyunk/0f6fbd5758ede22a8bf2750207f6cc6a to your computer and use it in GitHub Desktop.
Save zhyunk/0f6fbd5758ede22a8bf2750207f6cc6a to your computer and use it in GitHub Desktop.
깜짝 미니 과제 2
import java.util.*;
// 23.04.11
// 김지현
public class Main2 {
Position my;
List<Position> list;
public static void main(String[] args) {
Main2 m = new Main2();
m.getPosition();
m.print();
}
// 좌표 입력 받아서 list 채움
private void getPosition() {
long x, y;
int cnt = 0;
my = null;
list = new ArrayList<>();
Scanner scan = new Scanner(System.in);
while (cnt <= 10) {
String sep;
if (cnt == 0) {
sep = "내";
} else {
sep = "임의의";
System.out.printf("%d/10 번째 입력\n", cnt);
}
// x, y 입력받음
x = getXorY(scan, sep, "x");
y = getXorY(scan, sep, "y");
// 중복이면 continue;
if (isDuplicate(list, x, y)) {
continue;
}
if (cnt == 0) {
my = new Position(x, y);
} else {
list.add(new Position(x, y, Math.sqrt(Math.pow(my.x - x, 2) + Math.pow(my.y - y, 2))));
}
cnt++;
}
scan.close();
}
// 결과 출력
private void print() {
// 전체 좌표 출력
for (Position p: list) {
System.out.println(p);
}
Collections.sort(list);
System.out.println("제일 가까운 좌표\t: " + list.get(0)); // 거리가 같으면 먼저 입력된 좌표 출력
System.out.println("내 좌표\t\t\t: " + my);
}
// 중복 값 있는지 검사
private boolean isDuplicate(List<Position> list, long x, long y) {
for (Position p: list) {
if (p.x == x && p.y == y) {
System.out.println("동일한 좌표값이 이미 존재합니다. 다시 입력해 주세요.");
return true;
}
}
return false;
}
// 숫자 입력 요구 출력하고 숫자 받아서 반환
private int getXorY(Scanner scan, String sep, String xORy) {
System.out.printf("%s 좌표 %s값을 입력해 주세요.\n", sep, xORy);
while (true) {
try {
return scan.nextInt();
} catch (Exception e) {
System.out.println("숫자만 입력해주세요!");
scan.next();
}
}
}
private static class Position implements Comparable<Position> {
long x;
long y;
double distance;
public Position(long x, long y) {
this.x = x;
this.y = y;
}
public Position(long x, long y, double distance) {
this.x = x;
this.y = y;
this.distance = distance;
}
@Override
public int compareTo(Position p) {
return Double.compare(this.distance, p.distance);
}
@Override
public String toString() {
return String.format("(%d, %d) => %.6f", x, y, distance);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment