728x90
300x250

[Java] IceCream - Class 구현

 

아이스크림 클래스를 작성하였습니다.
이해를 돕기 위해서 작성하였습니다.

 


interface IceCream{
     abstract void use();
     abstract void destroy();
}

class Bar implements IceCream{
 
      public void use(){
           System.out.println("맛있는 막대바 아이스크림 섭취");
      }
 
      public void destroy()
      { 
           System.out.println("다 먹음(막대바)"); 
      }
}

 

class Cone implements IceCream{
 
      public void use()
      {
           System.out.println("맛있는 콘 타입 아이스크림 섭취");
      }
 
      public void destroy(){
           System.out.println("다 먹음(콘 타입)");
      }
}

public class Output {
 
     public static void main(String args[])
     {
           Bar iceCreamBar = new Bar();
           Cone iceCreamCone = new Cone();
  
           iceCreamBar.use();
           iceCreamCone.use();
  
           iceCreamBar.destroy();
           iceCreamCone.destroy();
     }

 아이스크림을 추상화함. - Output.java

 

(아이스크림 바, 아이스크림 콘)을 먹을 때 공통적으로 할 수 있는 일

두 가지로 생각해봄.

-> 먹는다(use)

-> 버린다(destroy)

반응형
728x90
300x250

[Eclipse] 자동완성이 안될 때

 

이클립스에서 작업을 하는데 코드 완성 기능이 동작하지 않을 때 아래와 같이 하면 됩니다.

 


1. 소개

Window -> Preferences -> Java -> Editor -> Content Assist -> Advanced

* Java Proposals 체크

 

 

자동완성 기능을 사용하실 수 있습니다.

반응형
728x90
300x250

[Java] 행 바꾸기


자바에서 운영체제 별로 문장 행을 바꾸는 방법입니다.

 


1. 사용 방법

 

1. System.out.println()

2. System.out.print("\n");     // 유닉스 계열

3. System.out.print("\r\n"); // 윈도우 계열

 


2. 맺는말

 

JDK 버전에 따라서 달라질 수도 있습니다.

반응형
728x90
300x250

[Java] Txt 파일 읽기 (Enter키 고려)

 

Java 프로그래밍에서 Txt(이하 Text, 또는 텍스트)를 읽어들일 때, Enter 키를 반영하는 코드를 소개한다.

 

try{
    BufferedReader in = new BufferedReader(new FileReader(Filename));
    while((Put = in.readLine()) != null)
     Data = Data + Put + "\n";
    
    in.close();
   }
   catch(IOException e){

    System.out.println(Data);

}

 

try{ } catch(Exception e){  }을 고려하지 않는다면, enter키를 인식하지 못하기 때문에 두번 입력하라는 의미로 해석된다고 한다.

반응형
728x90
300x250

[JDBC] MySQL - UTF8 Connection

 

JSP 또는 JAVA에서 UTF-8을 허용하는 MySQL Connection입니다.


1. JDBC Connection 작성 예시

 

jdbc:mysql://localhost:3306/{DB명}?useUnicode=true&characterEncoding=utf8
반응형
728x90
300x250

[Java] Eclipse - Tomcat Library 사용하기

 

 

Project에 Properties를 설정하여 수동으로 Library의 JAR를 추가해야 Tomcat이 제공하는 Servlet을 포함한 Api등을 정상적으로 사용할 수 있습니다.

서블릿 등을 사용하는 데, 안 되시는 분들은 이와 같은 방법으로 올려보시기 바랍니다.

반응형

'소프트웨어(SW) > Sun Sys - Java' 카테고리의 다른 글

[Java] 행 바꾸기  (0) 2014.10.24
[Java] Txt 파일 읽기 (Enter키 고려)  (0) 2014.09.27
[JDBC] MySQL - UTF8 Connection  (0) 2014.07.24
[Java] 상속에 관한 방법  (0) 2014.06.24
[Java] Class의 Exception 처리  (0) 2014.06.24
728x90
300x250
[Java] 상속에 관한 방법

 

상속 방법 1)

 

class Account{
     String accountNo;
     String ownerName;
     int balance;
  
     void deposit(int amount){
          balance += amount;
     }
 
     int withdraw(int amount) throws Exception{
  
     if ( balance < amount )
           throw new Exception("잔액이 부족합니다.");
     else
           balance -= amount;
  
     return amount;
     }

 

Account.java

 

class CheckingAccount extends Account{

      String cardNo;
 
      int pay ( String cardNo, int amount ) throws Exception{
      if ( !cardNo.equals(this.cardNo) || (this.balance < amount ) )
           throw new Exception("지불이 불가능합니다.");
      return withdraw(amount);
     

      }

 

CheckingAccount.java

 

class InheritanceExample{                                                                              
                                                                                                    
      public static void main(String args[]) 

     {                                                            

          CheckingAccount obj;

          obj = new CheckingAccount();                                                   
          obj.accountNo = "110-22-333333";                                                          
          obj.ownerName = "홍길동";                                                                     
          obj.cardNo = "5555-6666-7777-8888";                 
          obj.deposit(100000);                                                                           
                                                                                                 
          try{                                                                                           

                 int paidAmount = obj.pay("5555-6666-7777-8888", 47000);
                 System.out.println("지불액:" + paidAmount);                          
                 System.out.println("잔액:" + obj.balance);                 
                                                                                            
          } catch(Exception e)                                                                           
          {                                                                                             
                  System.out.println(e.getMessage());            

 

           }              
                             
      }                                                                                                                                               
}                                                                                                     

 

InheritanceExample.java

 

상속 방법 2)

 

class Account{
      String accountNo;
      String ownerName;
      int balance;
  
      void deposit(int amount){
            balance += amount;
      }
 
      int withdraw(int amount) throws Exception{
  
             if (balance < amount)
                   throw new Exception("잔액이 부족합니다.");
             else
                   balance -= amount;
  
             return amount;

       }
 

 

 

Account.java

 

class CheckingAccount extends Account{

       String cardNo;

       CheckingAccount(String accountNo, String ownerName, int balance, String cardNo){
           this.accountNo = accountNo;
           this.ownerName = ownerName;
           this.balance = balance;
           this.cardNo = cardNo;

      }
 
       int pay(String cardNo, int amount) throws Exception{

 

       if ( !cardNo.equals(this.cardNo) || (this.balance < amount))
                  throw new Exception("지불이 불가능합니다.");
  

       return withdraw(amount);

 

  }
 

 

CheckingAccount.java

 

class InheritanceExample{                                                                                                                                                                                                                                          
     public static void main(String args[])

    {                                                                             
        CheckingAccount obj;

        obj = new CheckingAccount("113-333-333333", "홍길동", 100000, "5555-6666-7777-8888");
                                                                                              
       try {
             int paidAmount = obj.pay("5555-6666-7777-8888",47000);
             System.out.println("지불액:" + paidAmount);
             System.out.println("잔액:" + obj.balance);
       } catch(Exception e) {
             System.out.println(e.getMessage());

       } 
   }
}

 

InheritanceExample.java

반응형
728x90
300x250

[Java] Class의 Exception 처리

 

Case 1) Numbers(클래스)

 

 

arr[] 공간의 길이가 0이기 때문에 해당 코드는 Exception이 발생하게 됩니다.

Arithmetric Exception이 발생하게 되는데,

 

try{

int average = obj.getAverage();

}catch(java.lang.ArithmeticException e){

     // 출력(산술 오류에 관한 메시지)

}

 

이처럼 처리하는 것도 하나의 방안이 될 수 있으나, 가장 좋은 구조는 Arithmetic Exception이 발생하지 않도록 처리하는 것이 가장 좋은 구조가 아닐까 생각해봅니다.

 

Case 2) Account(클래스)

 

class Account{
        String accountNo;
        String ownerName;
        int balance;
 
        Account(String accountNo, String ownerName, int balance){
             this.accountNo = accountNo;
             this.ownerName = ownerName;
             this.balance = balance;
        }
 
       void deposit(int amount){
             balance += amount;
        }
 
        int withdraw(int amount) throws Exception{
  
            if(balance < amount)
                  throw new Exception("잔액이 부족합니다.");
            else
                  balance -= amount;
  
            return amount;
       }
}

 

 

 

1. Try ~ Catch로 예외 처리

 

class Hello{
 
        public static void main(String args[]){
   
            Account obj = new Account("1", "곰", 40);
            obj.deposit(-40);
  
            try {
                 int amount = obj.withdraw(1);
                 System.out.println("인출액:" + amount);
            } catch (Exception e) {
                 System.out.println(e.getMessage());
            }
       }
}

 

2. throws Exception으로 처리 

 

class Hello{
 
      public static void main(String args[]) throws Exception{
  
            Account obj = new Account("1", "곰", 40);
            obj.deposit(-40);
 
            int amount = obj.withdraw(1);
            System.out.println("인출액:" + amount);
     }
}

 

참고 문헌) 뇌를 자극하는 JAVA 프로그래밍 P238~244

반응형

+ Recent posts