🔖

2023/06/27に公開

# while

``````public class SumFrom1To100Example {
public static void main(String[] args) {
int sum = 0;
int i=1;

while(i<=100) {
sum+=i;
i++;
}
System.out.println("1~" + (i-1) + "의 합 : " + sum);
}
}
``````
``````import java.util.Scanner;

public class KeyControlExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean run = true;
int speed = 0;

while(run) {
System.out.println("---------------------------");
System.out.println("1. 증속 | 2. 감속 | 3. 중지");
System.out.println("---------------------------");
System.out.println("선택 :");

String strNum = scanner.nextLine();

if(strNum.equals("1")) {
speed++;
System.out.println("현재 속도 = " + speed);
}else if(strNum.equals("2")){
speed--;
System.out.println("현재 속도 = " + speed);
}else if(strNum.equals("3")) {
run=false;
}
}
scanner.close();
}
}

``````

# do-while

do-whileはまず、ブロックの内部を実行してから条件式を判別する。

``````do{  1. 実行
}
while(2. 条件式);
``````

do-whileを活用する際には、whileの条件の後にセミコーロンを付ける。

``````import java.util.Scanner;

public class DoWhileExample {
public static void main(String[] args) {
System.out.println("메세지를 입력하세요.");
System.out.println("프로그램을 종료하려면 q를 입력하세요.");

Scanner scanner = new Scanner(System.in);
String inputString;

do {
System.out.println(">");
inputString = scanner.nextLine();
System.out.println(inputString);
}
while(!inputString.equals("q"));

System.out.println();
System.out.println("프로그램을 종료");;
scanner.close();
}

``````

# break

``````
Label: for(...) {

for(...){

break Label;
}
}

``````
``````public class BreakOutterExample {
public static void main(String[] args) {
Outter: for(char upper ='A'; upper <='Z';upper++) {
for(char lower = 'a'; lower <= 'z'; lower++) {
System.out.println(upper + "-" +lower);
if(lower=='g')
break Outter;
}
}
}
}

``````