https://kiwikiwisae.tistory.com/7
내가 제출한 코드
비교 연산자를 사용한 코드가 더 간결해서 그 부분까지 생각했다면 좋았을 것 같다.
bash
닫기package p2022_06_22;
import java.util.Scanner;
public class homework1 {
public static void main(String[] args) {
/* 키보드로 3개의 정수를 입력 받았을때 최대값과
최소값을 구하는 프로그램을 작성 하세요?
(단, 조건 연산자를 활용해서 작성하세요.) */
System.out.println("정수 3개를 입력하세요.");
int a, b, c, max, min;
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
max = (a>b) ? a : (b>c) ? b : (c>a) ? c : a ;
min = (a<b) ? a : (b<c) ? b : (c<a) ? c : a ;
System.out.println("최대값은"+max+"입니다.");
System.out.println("최소값은"+min+"입니다.");
}
}
선생님이 풀이해 주신 코드
bash
닫기package p2022_06_23;
import java.util.Scanner;
public class Report {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("3개의 정수를 입력 하세요?");
int n1, n2, n3, max, min;
Scanner sc = new Scanner(System.in);
n1 = sc.nextInt(); // n1=20;
n2 = sc.nextInt(); // n2=10;
n3 = sc.nextInt();
// 최대값
max = (n1 > n2) ? n1 : n2;
max = (max > n3) ? max : n3;
// max = (n1>n2 && n1>n3) ? n1 : (n2>n3) ? n2: n3;
// 최소값
min = (n1 < n2) ? n1 : n2;
min = (min < n3) ? min : n3;
// min = (n1<n2 && n1<n3) ? n1 : (n2<n3) ? n2: n3;
System.out.println("max=" + max);
System.out.println("min=" + min);
}
}
'자바' 카테고리의 다른 글
조건문 Switch, 보조 제어문 Break (2022-06-23) (0) | 2022.06.23 |
---|---|
난수 발생 (2022-06-23) (0) | 2022.06.23 |
조건문 if, else, else if (2022-06-22) (0) | 2022.06.22 |
확장 대입 연산자, 증감 연산자 (2022-06-22) (0) | 2022.06.22 |
논리 연산자 (2022-06-22) (0) | 2022.06.22 |