11. for 루프를 사용하여 곱셈표를 인쇄하는 방법을 작성하세요.
/**
*for 루프는 9-9 곱셈표를 인쇄합니다.
*/
publicvoid nineNineMultiTable()
{ for (int i = 1,j = 1; j <= 9; i++) { System.out.print(i+"*" +j+ "="+i*j+" "); if(i==j) { i=0; j++; System.out.println(); } } } 12. java.util.Date 객체가 주어지면 어떻게 "2007-3-22 20:23:22" 형식의 문자열을 변환하려면 /** *날짜를 고정된 형식의 문자열로 변환 *@paramdate *@returnstr */ public String dateToStr(java.util. 날짜 날짜 ) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(date);
return str;
}
13. 어떤 정수가 소수인지 판단할 수 있는 메소드를 작성하세요
/**
*정수가 소수인지 확인
*@paramn
*@returnboolean
*/
publicboolean isPrimes(int n)
{ for (int i = 2; i <= Math.sqrt(n); i++) { if(n%i==0 ) { returnfalse; } } returntrue; } 14. 정수를 입력하고 계승값을 반환하는 메서드를 작성하세요 /** *모든 정수의 계승값을 얻으세요 *@paramn *@returnn! */
publicint Factorial(int n)
{ //재귀적 if(n==1) { return 1; } return n*factorial(n-1); //비재귀적 // int multi = 1; // for (int i = 2; i <= n; i++) { // multi*=i; // } // return multi; } 15. 정수 배열에 정수가 있는지 확인하기 위해 이진 검색을 사용하는 메서드를 작성합니다. , 배열의 인덱스 위치를 반환하고, 존재하지 않으면 -1을 반환합니다. /** *정수 배열에서 특정 정수의 위치에 대한 이진 검색(재귀) *@paramdataset *@paramdata * @parambeginIndex *@paramendIndex * @returnindex */ publicint BinarySearch(int[] 데이터 세트, int 데이터, int startIndex, int endIndex)
{ int midIndex = (beginIndex+endIndex)/2; if(data <dataset[beginIndex]||data>dataset[endIndex]||beginIndex>endIndex)return -1; if(data <dataset[midIndex]) { return BinarySearch (dataset,data,beginIndex,midIndex-1); }elseif(data>dataset[midIndex]) { return binarySearch(dataset,data,midIndex+1,endIndex); }else { return midIndex; } } /** *Biary 정수 배열에서 특정 정수의 위치 찾기(비재귀) *@paramdataset *@paramdata *@returnindex */ publicint BinarySearch(int[] 데이터 세트, int data)
{ int startIndex = 0; int endIndex = 데이터세트.길이 - 1; int midIndex = -1; if(data <dataset[beginIndex]||data>dataset[endIndex]||beginIndex>endIndex)return -1; while(beginIndex <= endIndex) { midIndex = (beginIndex+endIndex)/2; if(data <dataset[midIndex]) { endIndex = midIndex-1; } elseif(data>dataset[midIndex]) { startIndex = midIndex+1; }else { return midIndex; } } return -1; } 16. 사육자가 동물에게 먹이를 주는 예는 JAVA의 객체지향적 사고와 인터페이스(추상 클래스)의 유용성을 반영합니다.
package com.softeem.demo;
/**
*@authorleno
*동물 인터페이스
*/
인터페이스 Animal
{ publicvoid eat(Food food); } /** *@authorleno *동물 클래스: cat */ class Cat Implements Animal { publicvoid eat (음식) { System.out.println("小猫吃"+food.getName()); } } / ** * @authorleno *An Animal 클래스: dog */ class Dog Implements Animal { publicvoid eat (Food food ) { System.out.println("Puppy Chewing"+food.getName()); } } /**
*@authorleno
*Food 추상 클래스
*/
abstractclass Food
{ protected String name; public String getName() { returnname; } publicvoid setName(String name) { this.name = name; } } /** *@authorleno *일종의 food 클래스: fish */ class Fish extends Food { public Fish(String name) { this.name = name; } } /** *@authorleno *A 푸드 클래스: 뼈 */ class Bone extends Food { public Bone(String name) ) { this.name = 이름;
} }
/
**
*@authorleno
*Breeder 클래스
*
*/
class Feeder
{ /** *The breeder는 특정 종류의 동물에게 특정 종류의 음식을 공급합니다 *@paramanimal *@paramfood */ publicvoid Feed(동물 동물,Food food) { Animal.eat(food); } } /** *@authorleno *테스트 피더는 동물에게 음식을 공급합니다 */ publicclass TestFeeder { publicstaticvoid main(String[] args) { Feeder Feeder=new Feeder(); Animal Animal= new Dog (); Food food=new Bone("Meat Bone"); Feeder.feed(animal,food); //개에게 고기뼈를 먹입니다.
Animal=new Cat();
food=new Fish("fish");
Feeder.feed(animal,food); //고양이에게 생선 먹이기
}
}
17. JAVA의 예외 처리 메커니즘을 설명
? 예외가 발생하면 예외 클래스 객체가 자동으로 생성되고 예외 객체가 Java 런타임 시스템에 제출되는 프로세스를 예외 발생이라고 합니다. Java
- Java 런타임 시스템이 예외 객체를 수신하면 해당 예외를 처리할 수 있는 코드를 찾아 처리를 위해 현재 예외 객체를 전달합니다. 이 프로세스를 예외 포착이라고 합니다.
? Java 런타임 시스템이 예외를 포착할 수 있는 메소드를 찾을 수 없으면 런타임 시스템이 종료되고 해당 Java 프로그램이 종료됩니다.
? 프로그래머는 일반적으로 예외(Exception)만 처리할 수 있지만 오류(Error)에 대해서는 아무것도 할 수 없습니다.
18. 모나드 모드 클래스를 만들고 속성 파일
패키지를 한 번만 로드합니다: com.softeem.demo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
*@authorleno
*단일 모드, 구성 속성 파일이 전체 애플리케이션 중에 한 번만 로드되도록 보장
*/
publicclass Singleton { privatestatic Singleton instance; privatestaticfinal String CONFIG_FILE_PATH = "E:\\config.properties"; private Properties config; private Singleton() { config = new Properties(); InputStream is; try { is = new FileInputStream(CONFIG_FILE_PATH); config.load(is); is.close(); } catch (FileNotFoundException e) { // TODO 자동 생성된 catch 블록 e. printStackTrace() ; } catch (IOException e) { // TODO 자동 생성된 catch 블록
e.printStackTrace();
}
}
publicstatic Singleton getInstance()
{ if(instance==null) { 인스턴스 = new Singleton(); } returninstance; } public Properties getConfig() { returnconfig; } publicvoid setConfig(Properties config) { this .config = config; } } l J2SE 19. 지정된 경로에 디렉터리(파일) 복사 /** *지정된 경로에 디렉터리 또는 파일 복사 *@paramsource *@paramtarget */ publicvoid copy(File source,File target ) {
파일 tarpath = new File(target,source.getName());
if(source.isDirectory())
{ tarpath.mkdir(); 파일[] dir = source.listFiles(); for (int i = 0; i < dir.length; i++) { copy(dir[i],tarpath); } }else { try { InputStream is = new FileInputStream(source); OutputStream os = new FileOutputStream(tarpath); 바이트[] buf = newbyte[1024]; int len = 0; while((len = is.read(buf))!=-1) { os.write(buf,0,len);
}
is.close();
os.close();
} catch (FileNotFoundException e) { // TODO 자동 생성된 catch 블록 e.printStackTrace(); } catch(IOException e) { // TODO 자동 생성된 catch 블록 e .printStackTrace(); } } } 20. JAVA의 멀티스레딩을 사용하여 은행 인출 문제 샘플 packagecom.softeem.demo; /** *@authorleno *Account 클래스 * 기본적으로 잔고가 있고 돈을 인출할 수 있음 */ class Account { privatefloatbalance = 1000 ; publicfloat getBalance() { returnbalance; }
publicvoid setBalance(float Balance) { this.balance = Balance; } /** *출금 방법을 동기화해야 합니다 *@parammoney */ publicsynchronizedvoidwithdrawals(float Money) { if(balance>=money) { System.out.println (" Takenaway"+money+"원!"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO 자동 생성된 catch 블록 e.printStackTrace(); } Balance-=money; } 그렇지 않으면 {
System.out.println("죄송합니다. 잔고가 부족합니다!");
}
}
}
/**
*@authorleno
*은행 카드
*/
class TestAccount1 확장 Thread { 개인 계정 계정; public TestAccount1(계정 계정) { this.account = 계정 ; } @Override publicvoid run() { account.withdrawals(800); System.out.println("잔고는:"+account.getBalance()+"yuan!"); } } / ** * @authorleno * Passbook */ class TestAccount2 확장 Thread { 개인 계정 계정; public TestAccount2(계정 계정) {
this.account = account;
}
@Override
publicvoid run() { account.withdrawals(700); System.out.println("잔액은:"+account.getBalance()+"Yuan!"); } } publicclass 테스트 { publicstaticvoid main(String[] args) { 계정 계정 = new Account(); TestAccount1 testAccount1 = new TestAccount1(account); testAccount1.start(); TestAccount2 testAccount2 = new TestAccount2(account); testAccount2.start(); } } 21 .JAVA의 멀티스레딩을 사용하여 기차역 티켓 판매 패키지 샘플 com.softeem.demo; /** *@authorleno *티켓 판매 클래스
*/
class SaleTicket Implements Runnable { inttickets = 100; publicvoid run() { while (tickets > 0) { sale(); // 또는 다음과 같이 구현합니다 // 동기화된 (this) { // if (tickets > 0) { / / System.out.println(Thread.currentThread().getName() + "판매 번호" // + (100 - 티켓 + 1) + "티켓"); // 티켓--; // } // } } } publicsynchronizedvoid sale() { if (티켓 > 0) { System.out.println(Thread.currentThread().getName() + "Sell"
+ (100 - 티켓 + 1) + "티켓");
ticket--;
}
}
}
publicclass TestSaleTicket { publicstaticvoid main(String[] args) { SaleTicket st = new SaleTicket(); new Thread(st, "No. 1 Window").start(); new Thread(st, "창 번호 2").start(); new Thread(st, "창 번호 3").start(); new Thread(st, "창 번호 . 4") ).start(); } } 22. JAVA 패키지 com.softeem.demo; 클래스 Producer 에서 멀티스레딩 예제 생산자 및 소비자 문제 사용 Runnable { private SyncStack 스택; public Producer(SyncStack 스택) { this. 스택 = 스택; }
publicvoid run() { for (int i = 0; i < stack.getProducts().length; i++) { String product = "产product"+i; stack.push(제품); System.out.println("생계: "+제품); 시도 { Thread.sleep(200); } catch(InterruptedException e) { e.printStackTrace(); } } } } 클래스 소비자는 Runnable을 구현합니다. { private SyncStack stack; 공공 소비자(SyncStack 스택) { this.stack = 스택; } 공개공허 실행() {
for(int i=0;i <stack.getProducts().length;i++)
{ String product =stack.pop(); System.out.println("消费了: "+제품); 시도 { Thread.sleep(1000); } catch(InterruptedException e) { e.printStackTrace(); } } } } class SyncStack { private String[] 제품 = new String[10]; 개인 인덱스; publicsynchronizedvoid push(String product) { if(index==product.length()) {
시도 { 대기(); } catch (InterruptedException e) { // TODO 자동 생성된 catch 블록 e.printStackTrace(); } } 통지(); 제품[색인]=제품; 인덱스++; } publicsynchronized String pop() { if(index==0) { try { wait(); } catch (InterruptedException e) { // TODO 자동 생성된 catch 블록 e.printStackTrace(); } } 통지();
색인--;
문자열 제품 = 제품[색인];
제품 반품;
}
공개 문자열[] getProducts() { 반품제품; } } publicclass TestProducerConsumer { publicstaticvoid main(String[] args) { SyncStack stack=new SyncStack(); 생산자 p=새로운 생산자(스택); 소비자 c=새 소비자(스택); 새로운 Thread(p).start(); 새로운 Thread(c).start(); } }