Presentation is loading. Please wait.

Presentation is loading. Please wait.

5 장 조건과 반복 ②. Contents Counting and Looping [while 문 사용 ] Powers of 2 [while 문 사용 ] More Guessing [do 문 사용 ] Election Day [do 문 사용 ] Finding Maximum &

Similar presentations


Presentation on theme: "5 장 조건과 반복 ②. Contents Counting and Looping [while 문 사용 ] Powers of 2 [while 문 사용 ] More Guessing [do 문 사용 ] Election Day [do 문 사용 ] Finding Maximum &"— Presentation transcript:

1 5 장 조건과 반복 ②

2 Contents Counting and Looping [while 문 사용 ] Powers of 2 [while 문 사용 ] More Guessing [do 문 사용 ] Election Day [do 문 사용 ] Finding Maximum & Minimum Values [for 문 사용 ] Counting Characters [for 문 사용 ] Using the coin class [for 문 사용 ]

3 Counting and Looping // **************************************************************** // LoveCS. java // // while loop 을 사용하여 “I love Computer Science!!” 을 원하는 만큼 // 프린트 하시오. // // **************************************************************** public class LoveCS { public static void main(String[] args) { final int LIMIT = 10; int count = 1; while (count <= LIMIT){ System.out.println("I love Computer Science!!"); count++; }

4 LoveCS.java 를 다음과 같이 수정하시오.  1. 상수 LIMIT 를 사용하여 사용자가 원하는 만큼 메시지를 출력 한다. 변수를 선언하여 사용자의 응답을 저장하고 loop 을 제어한다.  2. 라인과 메시지, 출력횟수를 함께 출력한다. 그림 참조 [ 사용자 가 3 을 입력하였을 때, 다음과 같이 프린트 해야 한다.] Counting and Looping [Cont.] 1 I love Computer Science!! 2 I love Computer Science!! 3 I love Computer Science!! Printed this message 3 times.

5 LoveCS.java 를 다음과 같이 수정하시오.  3. 변수를 하나를 추가하여 메시지 출력 첫째 줄부터 N 번째 줄까지의 합을 계산하여 출력한다.[ 그림 참조 ] Counting and Looping [Cont.] 1 I love Computer Science!! 2 I love Computer Science!! 3 I love Computer Science!! Printed this message 3 times. The sum of the numbers from 1 to 3 is 6.

6 Powers of 2 PowersOf2.java // **************************************************************** // PowersOf2.java// // powers of 2 를 구하는 문제 // **************************************************************** import java.util.Scanner; public class PowersOf2 { public static void main(String[] args) { int numPowersOf2; // 계산되는 powers of 2 의 개수 int nextPowerOf2 = 1; // 현재 power of 2 int exponent; //Exponent for current power of 2 – loop 의 개수 계산 Scanner scan = new Scanner(System.in); System.out.println("How many powers of 2 would you like printed?"); numPowersOf2 = scan.nextInt(); //powers of 2 의 개수를 메시지로 출력 //exponent 초기화 -- the first thing printed is 2 to the what? while ( ) { // 현재 power of 2 를 출력 // 다음 power of 2 를 찾기 -- how do you get this from the last one? // increment exponent }

7 Powers of 2[Cont.] PowersOf2.java 는 사용자로 부터 integer 를 입력 받아 2 의 루승을 구한다.  1. Math.pow 를 사용하지 않는다. 예를 들면 사용자가 4 를 입력하였을 때 다음과 같은 결과가 나와야 한다. Here are the first 4 powers of 2: 1 2 4 8

8 2. 위의 프로그램을 다음과 같은 결과가 나오게끔 수정하시오. Powers of 2[Cont.] Here are the first 4 powers of 2: 2^0 = 1 2^1 = 2 2^2 = 4 2^3 = 8

9 Election Day[ 투표 관리 시스템 ] 두 후보의 선거 결과를 취합하는 프로그램인 Election.java 를 완성하시오. 각 선거구에 대해서 두 후보의 득표수를 입력 받는다.  더 입력할 선거구가 있는지 사용자에게 물어봐서, 더 입력할 선거구가 있는 동안 계속 입력을 받는다. 최종적으로, 전체 득표수와 백분율을 출력한다. 두 후보가 각각 몇 개의 선거구에서 승리했고, 비긴 선 거구는 몇 개인지 출력한다.

10 투표 관리 시스템 (cont.) import java.util.Scanner; public class Election { public static void main (String[] args) { int votesForTom; // 각 선거구에서 Tom 의 득표수 int votesForSusan; // 각 선거구에서 Susan 의 득표수 int totalTom; // Tom 의 전체 득표수 int totalSusan; // Susan 의 전체 득표수 String response; // 선거구가 더 있는지에 대한 질문의 답을 저장할 변수 (y or n) Scanner scan = new Scanner(System.in); System.out.println (); System.out.println ("Election Day Vote Counting Program"); System.out.println (); // 초기화 // 각 선거구에서 투표 결과를 취합 (Loop) // 결과 출력 }

11 최대, 최소값 찾기 하루 동안 매시간마다 온도를 읽어 들여, 그 최대값과 최소값을 찾는 프로그 램인 Temps.java 를 완성하시오. 최대값 구하기  최대값을 저장할 변수 maxTemp 선언  Loop 에 들어가기 전에 아주 작은 값으로 (-1000) 초기화  Loop 안에서 최대값과 현재의 온도를 비교하여, 그 결과에 따라 최대값 갱신  Loop 밖에서 결과 출력 최대값 발생 시간 구하기  온도의 최대값이 발생된 시간을 저장할 변수 timeOfMax 선언  Loop 안에서 적절히 이 값을 갱신  Loop 밖에서 결과 출력 결과 테스트  첫번째로 넣은 값이, 마지막으로 넣은 값이, 중간에 넣은 값이 각각 최대 값으로 잘 적용되는지 테스트한다. 최소값도 위와 마찬가지의 방법으로 구한다.

12 최대, 최소값 찾기 (cont.)  import java.util.Scanner;  public class Temps  {  public static void main (String[] args)  {  final int HOURS_PER_DAY = 24;  int temp; // 읽어들인 온도를 저장할 변수  Scanner scan = new Scanner(System.in);   System.out.println ();  System.out.println ("Temperature Readings for 24 Hour Period");  System.out.println ();   for (int hour = 0; hour < HOURS_PER_DAY; hour++)  {  System.out.print ("Enter the temperature reading at " + hour +  " hours: ");   temp = scan.nextInt(); // 매시간 온도를 읽어들임  }  // 결과를 출력하시오  }  }

13 문자 개수 세기 공백을 비롯한 여러 가지 문자의 개수를 세는 프로그램인 Count.java 를 완성하시오. 공백 개수 세기  읽어 들인 문장에서 한 글자, 한 글자 공백인지 검사한다.  문장 전체를 돌기 위하여 for 문과 length() 메소드를 사용한다.  한글자, 한글자 공백인지 검사하기 위하여 if 문과 charAt() 메소드 를 사용한다. ‘a’, ‘e’, ‘s’, ‘t’ 의 개수 세기  대소문자 구분 없이 모두 센다.  공백을 세기 위해 사용했던 if 문을 switch 문으로 수정한다. 검사를 여러 번 하도록 확장  “quit” 을 입력하기 전까지, 검사가 계속 반복되도록 확장한다.

14 문자 개수 세기 (cont.)  import java.util.Scanner;  public class Count  {  public static void main (String[] args)  {  String phrase; // 검사할 문장  int countBlank; // 공백의 개수  int length; // 문장의 길이  char ch; // 검사할 글자  Scanner scan = new Scanner(System.in);   System.out.println ();  System.out.println ("Character Counter");  System.out.println ();   // 검사할 문장을 읽어들이고, 그 문장의 길이를 구한다.  System.out.print ("Enter a sentence or phrase: ");  phrase = scan.nextLine();  length = phrase.length();   // 공백의 개수 초기화  countBlank = 0;   // 공백의 개수 세기   // 결과 출력  System.out.println ();  System.out.println ("Number of blank spaces: " + countBlank);  System.out.println ();  }  }

15 동전 던지기 동전을 100 회 던져, 연속으로 계속 앞면이 나오는 횟수의 최대값을 구하는 프로그램인 Runs.java 를 완성하시오. 이때, 동전을 던지고 그 결과를 알려주는 Coin 클 래스 (Coin.java) 를 이용한다.

16 동전 던지기 (cont.)  // **************************************************  // Coin.java  //  // 던져질 수 있는 두 면을 갖는 동전을 표현한다.  // **************************************************  public class Coin  {  public final int HEADS = 0;  public final int TAILS = 1;   private int face;   // ---------------------------------  // 초기에 동전을 던져서 동전을 설정한다.  // ---------------------------------  public Coin ()  {  flip();  }   // ----------------------------------  // 상태값을 무작위로 선택함으로써 동전을 던진다.  // ----------------------------------  public void flip()  {  face = (int) (Math.random() * 2);  }   // --------------------------------------  // 동전이 앞면인지 뒷면인지, 정수값으로 리턴한다.  // --------------------------------------public int getFace()  {  return face;  }   // --------------------------------------  // 동전의 현재 상태를 스트링으로 반환한다.  // --------------------------------------  public String toString()  {  String faceName;   if (face == HEADS)  faceName = "Heads";  else  faceName = "Tails";   return faceName;  }  }

17 동전 던지기 (cont.)  // ********************************************************************  // Runs.java  // 동전을 100 회 던져, 앞면이 계속 나오는 횟수의 최대값을 구하는 프로그램  // ********************************************************************  import java.util.Scanner;  public class Runs  {  public static void main (String[] args)  {  final int FLIPS = 100; // 동전을 던지는 횟수   int currentRun = 0; // 현재 연속으로 앞면이 나온 횟수  int maxRun = 0; // 연속으로 앞면이 나온 횟수의 최대값   Scanner scan = new Scanner(System.in);   // Coin 객체를 생성   // 동전을 100 회 던진다.  for (int i = 0; i < FLIPS; i++)  {  // 동전을 던지고, (flip() 이용 )  // 그 결과를 출력한다.(toString() 을 묵시적으로 이용 )   // 연속으로 앞면이 나오고 있는 횟수 갱신  // 연속으로 앞면이 나온 횟수의 최대값 계산  }   // 결과 출력  }  }


Download ppt "5 장 조건과 반복 ②. Contents Counting and Looping [while 문 사용 ] Powers of 2 [while 문 사용 ] More Guessing [do 문 사용 ] Election Day [do 문 사용 ] Finding Maximum &"

Similar presentations


Ads by Google