자기개발/Java

Chapter 5 배열(Array)

실버블렛 2012. 1. 21. 15:32
반응형

class ArrayEx1
{
 public static void main(String[] args)
 {
  int sum=0;
  float average=0.0f;

  int[] score= {100, 88, 100, 100, 90};

  for(int i=0; i<score.length; i++){
   sum += score[i];
  }
  average = sum/(float)score.length;

  System.out.println("총점 : " + sum);
  System.out.println("평균 : " + average);
 }
}

---------------------------------------------------------------------------------------
class ArrayEx2
{
 public static void main(String[] args)
 {
  int[] score = {79, 88, 91, 33, 100, 55, 95};

  int max = score[0];
  int min = score[0];

  for(int i=1; i<score.length; i++){
   if(score[i]>max){
    max = score[i];
   }
   if(score[i]<min){
    min = score[i];
   }
  } // end of for
  System.out.println("최대값 : " + max);
  System.out.println("최대값 : " + min);
 } //end of main
} // end of class

---------------------------------------------------------------------------------------
class ArrayEx3
{
 public static void main(String[] args)
 {
  int[] number = new int[10];

  for(int i=0; i<number.length; i++){
   number[i] = i;

   System.out.print(number[i]);
  }

  System.out.println();

  for(int j=0; j<100; j++){
   int n = (int)(Math.random()*10);

   int temp = number[0];
   number[0] = number[n];
   number[n] = temp;
  }
  for(int k=0; k<number.length; k++){
  
  System.out.print(number[k]);
  }
 }
}

---------------------------------------------------------------------------------------
class ArrayEx4
{
 public static void main(String[] args)
 {
  int[] ball = new int[45];

  for(int i=0; i<ball.length; i++){
   ball[i] = i+1;
  }

  int temp = 0;
  int n = 0;

  for(int j=0; j<100; j++){
   n = (int)(Math.random()*45);

   temp = ball[0];
   ball[0] = ball[n];
   ball[n] = temp;
  }

  for(int i=0; i<6; i++){
   System.out.print(ball[i] + " ");

  }  
 }
}

---------------------------------------------------------------------------------------
class ArrayEx5
{
 public static void main(String[] args)
 {
  int[] number = new int[10];

  for(int i=0; i<number.length; i++){
   System.out.print(number[i] = (int)(Math.random()*10));
  } //enf of for i

  System.out.println();  

  for(int j=0; j<number.length; j++){

   boolean changed = false;

   for(int k=0; k<number.length-1-j; k++){  

    if(number[k]>number[k+1]){
     int temp = number[k];
     number[k] = number[k+1];
     number[k+1] = temp;
     changed = true;
        }
   } //end of for k
    if(!changed) break;

   for(int i=0; i<number.length; i++){
       System.out.print(number[i]);
    
          }
    System.out.println();
  } //end of for j
 }//end of main
}

---------------------------------------------------------------------------------------
class ArrayEx6
{
 public static void main(String[] args)
 {
  int[] number = new int[10];
  int[] counter = new int[10];

  for(int i=0; i<number.length; i++){
   System.out.print(number[i] = (int)(Math.random()*10));
  } //enf of for i

  System.out.println();
  
  for(int i=0; i<number.length; i++){
   counter[number[i]]++;;
  }

  for(int i=0; i<number.length; i++){
   System.out.println(i + "의 개수 : " + counter[i]);
  }
 }
}

---------------------------------------------------------------------------------------
class ArrayEx7
{
 public static void main(String[] args)
 {
  char[] hex = {'C', 'A', 'F', 'E'};
  String[] binary = {"0000", "0001", "0010", "0011"
                    ,"0100", "0101", "0110", "0111"
           ,"1000", "1001", "1010", "1011"
        ,"1100", "1101", "1110", "1111"};
       
  String result = "";

  for(int i=0; i<hex.length; i++){
   if(hex[i]>='0' && hex[i]<=9){
    result += binary[hex[i]]; // += 를이용하여 문자열을 덮어쓰지 않고 이어서 저장한다.
   } else result += binary[(hex[i]-'A')+10];   
  }

  System.out.println("hex:" + new String(hex));
  System.out.println("binary:" + result);
 }
}

---------------------------------------------------------------------------------------
class ArrayEx8
{
 public static void main(String[] args)
 {
  String src = "ABCDE";

  for(int i=0; i<src.length(); i++){ // src.length()?
   System.out.println("src.charAt(" + i + ") : " + src.charAt(i));
  } 
 }
}

---------------------------------------------------------------------------------------
class ArrayEx9
{
 public static void main(String[] args)
 {
  String source = "SOSHELP";
  String[] morse = {".-", "-...", "-.-.", "-..", "."
               , "..-.", "--.", "....", "..", ".---"
         , "-.-", ".-..", "--", "-.", "---"
      , ".--.", "--.-", ".-.", "...", "-"
      , "..-", "...-", ".--", "-..-", "-.--"
      , "--.." };
        String result ="";
  
  for (int i=0; i < source.length(); i++){
   result += morse[source.charAt(i)-'A']; // chatAt()  로 해당 문자열 중 원하는 문자를 얻는다.
  }
  System.out.println("source:" + source);
  System.out.println("morse:" + result);
 }
}

---------------------------------------------------------------------------------------
class ArrayEx10
{
 public static void main(String[] args)
 {
  int[][] score = {{100, 100, 100}
                  ,{20, 20, 20}
                  ,{30, 30, 30}
                  ,{40 ,40, 40}
                  ,{50, 50, 50}};

        int koreanTotal = 0;
  int englishToal = 0;
  int mathTotal = 0;

  System.out.println("번호  국어  영어  수학  총점  평균");
  System.out.println("===========================================");

  for (int i=0; i<score.length; i++) {
   int sum=0;
   koreanTotal += score[i][0];
      englishToal += score[i][1];
      mathTotal += score[i][2];

   System.out.print(" " + i +" ");

   for (int j=0; j<score[i].length; j++) {
    sum += score[i][j];
    
    System.out.print(score[i][j] + " ");
   } //end of for j
   System.out.println(sum + " " + sum/(float)score[i].length);
  } //end of for i
  System.out.println("===========================================");
  System.out.println(" 총점 : "+ koreanTotal + " " + englishToal + " " +mathTotal);
 }
}

---------------------------------------------------------------------------------------
class ArrayEx11
{
 public static void main(String[] args)
 {
  int[] number = {1, 2, 3, 4, 5};
  int[] newNumber = new int[10];

  for (int i=0; i<number.length; i++) {
   newNumber[i] = number[i];   
  }
  for (int i=0; i<newNumber.length; i++) {
   System.out.print(newNumber[i]);
  }  
 }
}

---------------------------------------------------------------------------------------
class ArrayEx12
{
 public static void main(String[] args)
 {
  char[] abc = {'A', 'B', 'C', 'D'};
  char[] number = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

  System.out.println(new String(abc));
  System.out.println(new String(number));

  // 배열 abc와 number를 붙여서 하나의 배열 (result)로 만든다.
  char[] result = new char[abc.length + number.length];
  System.arraycopy(abc, 0, result, 0, abc.length);
  System.arraycopy(number, 0, result , abc.length, number.length);
  System.out.println(new String(result));
  
  // 배열 abc을 배열 number의 첫 번째 위치부터 배열 abc의 크기만큼 복사
  System.arraycopy(abc, 0, number, 0, abc.length);
  System.out.println(new String(number));

  // number의 인덱스6 위치에 3개를 복사
  System.arraycopy(abc, 0, number, 6, 3);
  System.out.println(new String(number));
 }
}

---------------------------------------------------------------------------------------
class ArrayEx13
{
 public static void main(String[] args)
 {
  System.out.println("매개변수의 개수:" + args.length);
  
  for (int i=0; i<args.length; i++) {
   System.out.println("args[" + i + "] = \"" + args[i] + "\"");
  }
 }
}

---------------------------------------------------------------------------------------
class ArrayEx14
{
 public static void main(String[] args)
 {
  if (args.length != 1) {
   System.out.println("usage: java morseConverter WORD");
   System.exit(0); //프로그램을 종료한다.
  }

  System.out.println("source:" + args[0]);
  String source = args[0].toUpperCase();
  String[] morse = {".-", "-...", "-.-.", "-..", "."
               , "..-.", "--.", "....", "..", ".---"
         , "-.-", ".-..", "--", "-.", "---"
      , ".--.", "--.-", ".-.", "...", "-"
      , "..-", "...-", ".--", "-..-", "-.--"
      , "--.." };
       
  String result = "";
  for (int i=0; i<source.length(); i++) {
   result += morse[source.charAt(i)-'A'];
  }     
  System.out.println(result);  
 }
}

---------------------------------------------------------------------------------------
class  ArrayEx15
{
 public static void main(String[] args)
 {
  if (args.length != 3) {
   System.out.println("usage: java ArrayEx15 NUM1 OP NUM2");
   System.exit(0);
  }
  int num1 = Integer.parseInt(args[0]);
  char op = args[1].charAt(0);
  int num2 = Integer.parseInt(args[2]);

  int result = 0;

  switch (op) {

   case '+':
    result = num1 + num2;
       break;
   case '-':
    result = num1 - num2;
       break;
   case '*':
    result = num1 * num2;
       break;
   case '/':
    result = num1 / num2;
       break;
      default :
    System.out.println("지원되지 않는 연상입니다.");   
  }
  System.out.println("결과:" + result);
 }
}

---------------------------------------------------------------------------------------
import javax.swing.*;  //JOpionPane클래스를 사용하기 위해서 사용.

class ArrayEx16
{
 public static void main(String[] args)
 {
  //1~100사이의 임의의값을 얻어서 answer에 저장한다.
  int answer = (int)(Math.random()*100)+1;
  String temp = ""; // 사용자 입력을 저장할 임시공간.
  int input = 0;   // 사용자 입력을 저장할 공간
  int count = 0;  // 입력횟수를 세기위한 변수 

  do {
   count++;
   temp = JOptionPane.showInputDialog("1~100사이의 숫자를 입력하세요."
                                    + " 끝내려면 -1을 입력하세요.");

   //사용자가 취소버튼을 누르거나 -1을 입력하면 do-while문을 벋어난다.

   if (temp == null || temp.equals("-1")) break;

   input = Integer.parseInt(temp);

   if (input < answer) {
    System.out.println("더 큰 수를 입력하세요.");
   } else if (input > answer) {
    System.out.println("더 작은 수를 입력하세요.");
   } else {
    System.out.println("맞췄습니다.");
    System.out.println("시도횟수는 " + count + "번 입니다.");
    break;
   }
  }
  while (true); //무한반복 
 } //end of main
} //end of class highLow

---------------------------------------------------------------------------------------
import javax.swing.*;

class ArrayEx17
{
 public static void main(String[] args)
 {
  int answer = (int)(Math.random()*100)+1;
  String temp = "";
  int input = 0;
  int count = 0;

  do {
   temp = JOptionPane.showInputDialog("1~100사이의 숫자를 입력하세요."
                                    + " 끝내려면 -1을 입력하세요.");
   count++;

   if (temp == null || temp.equals("-1")){
    break;
   }

   input = Integer.parseInt(temp);

   if (answer > input){
    System.out.println("더 큰 수를 입력하세요.");
   } else if (answer < input){
    System.out.println("더 작은 수를 입력하세요.");
   } else {
    System.out.println("맞췄습니다.");
    System.out.println("시도횟수는 " + count + "번 입니다.");
    break;
   }
   
  }
  while (true);  
 }
}

---------------------------------------------------------------------------------------

반응형

'자기개발 > Java' 카테고리의 다른 글

Chapter 7 객체지향 프로그래밍 2  (0) 2012.01.21
Chapter 6 객체지향 프로그래밍 1  (0) 2012.01.21
Chapter 4 조건문과 반복문  (0) 2012.01.12
Chapter 3 연산자  (0) 2012.01.12
Chapter 2. 변수  (0) 2012.01.12