기록
[JAVA] 조건문과 반복문 본문
<Boolean>
- Boolean expression
: 결과가 true 혹은 false인 expression
비교연산자의 결과 (==, !=, >, >=, <, <=)
논리연산자의 결과 (&&, ||, !)
- Boolean Type
: Boolean 변수는 Boolean 연산식 결과를 저장
'true' 또는 'false'로 저장 (리터럴 변수)
<조건문>
- if문
String str = "";
char ch = ' ';
if(ch == ' ' || ch == '\t') {...}
if(ch == 'c' || ch == 'C') {...}
if(str == "C" || str == "C") {...}
if(str.equals("c") || str.equals("C")) {...}
if (str.equalsIgnoreCase("c")) {...}
<Strings 비교 - equals>
- 연산자 == : String 비교에 사용할 수 없음.
- equals, equalsIgnoreCase를 사용하여 String의 내용을 비교.
String s1 = new String("JAVA");
String s2 = new String("JAVA");
String s3 = new String("java");
if(s1 == s2) //s1과 s2의 인스턴스 주소값이 같은지
if(s1.equals(s2)) //true
if(s1.equalsIgnoreCase(s3)) //true
if("Hello".equalsIgnoreCase("hello")) //true
<Branching Statements>
- if - else
- switch
<Loop>
- while statement
- do-while statement
public static void main(String[] args) {
int n = 1;
int result = 0;
do {
result += n;
n++;
} while(n <= 100);
System.out.println("The sum of 1 ~ 100 is " + result);
}
}
|
cs |
<Break for nested loop>
- 반복문 사용
- JAVA에서는 반복문에 label을 지정할 수 있는데, nested loop을 탈출할 때 유용하다.
public class TestBreakContinue{
public static void main(String[] args)
{
AA:
for (int i = 0; i < 3; i++)
{
for(int j = 0; j < 5; j++)
{
if (j == 3) break AA;
System.out.println("Value of i is " + i + ", value of j is " + j);
}
}
}
}
|
cs |
☆ c에서는 반복문 라벨 정하는게 안됨.
<난수 생성>
- Math.random()
: Math 클래스에 정의된 난수 발생메서드, 0.0과 1.0 사이의 double값을 반환함.
- 활용 예시
int score = (int)(Math.random()*10)+1; //1~10 사이의 난수 발생
'공부 > JAVA' 카테고리의 다른 글
[JAVA] 메서드 (0) | 2020.07.06 |
---|---|
[JAVA] 변수 (0) | 2020.07.05 |
[JAVA] 생성자 (0) | 2020.07.04 |
[JAVA] 클래스와 객체 (0) | 2020.07.04 |
[JAVA] 자바 개요 (0) | 2020.07.04 |
Comments