JAVA
[JAVA] 조건문과 반복문
신지아
2024. 4. 20. 16:14
*실수 형태일 때 switch문을 사용하는 건 적절하지 않음
if문
package study;
import java.util.Scanner; // 스캐너 호출 (input 역할)
// 메인 class
public class javastudy {
// method, 동작 담당
public static void main(String[] args) {
Scanner score = new Scanner(System.in);
System.out.print("학점을 입력하시오: ");
float userScore = score.nextFloat(); // 입력받은 score를 userScore에 저장함
score.nextLine(); // 개행문자 제거
if (4.0 < userScore && userScore <= 4.5) {
System.out.print("A+");
}
else if (3.5 < userScore && userScore <= 4.0) {
System.out.print("A");
}
else if (3.0 < userScore && userScore <= 3.5) {
System.out.print("B+");
}
else if (2.5 < userScore && userScore <= 3.0) {
System.out.print("B");
}
else {System.out.print("걍 자퇴해라..");
}
}
}
while, if-else if-else (중첩)
package study;
import java.util.Scanner; // 스캐너 호출 (input 역할)
// 메인 class
public class javastudy {
// method, 동작 담당
public static void main(String[] args) {
int hit = 0;
while (hit < 5) {
Scanner answer = new Scanner(System.in);
System.out.println("때리시겠습니까? (Y/N)");
String userAnswer = answer.nextLine();
if (userAnswer.equals("Y")) {
System.out.println("퍽");
hit++;
if (hit == 4) {
System.out.println("프로그램을 종료합니다.");
System.out.println("너무 많이 때렸어요.. ㅠ");
System.exit(0);
}
}
else if (userAnswer.equals("N")) {
System.out.println("떄리기를 종료합니다.");
System.out.println("프로그램을 종료합니다.");
System.exit(0);
}
else {
System.out.println("잘못된 입력입니다.");
System.out.println("프로그램을 종료합니다.");
System.exit(0);
}
}
}
}
while 무한 루프
package study;
// 메인 class
public class javastudy {
// method, 동작 담당
public static void main(String[] args) {
while(true) {
System.out.println("무한루프에 빠져버렸다!");
}
}
}이클립스의 경우에는 ctrl c 말고 빨간색 네모 버튼을 눌러 주면 프로그램이 종료된다.