Java程式碼範例

http://slides.com/wiasliao/deck-5#/

Hello World

class Main{
    public static void main(String[] args){
        System.out.println("Hello World");
    }
}

Data Type

class Main{
    public static void main(String[] args){
        int I = 4;
        System.out.println(I);
        float F = 4.0f;
        System.out.println(F);
        double D = 5.0;
        System.out.println(D);
        char C = 'C';
        System.out.println(C);
        String Str = "GREAT";
        System.out.println(Str);
    }
}

輸入

import java.util.Scanner;

class Main {
    public static void main(String[] argv){
        //命名一個空間 scan 去存放 Scanner 物件
        Scanner scan = new Scanner(System.in);
        //1.取得數入的整數
        int num = scan.nextInt();
        System.out.println(num);
        //2.取得輸入的浮點數
        float flo = scan.nextFloat();
        System.out.println(flo);
        //3.取得輸入的浮點數
        double dd = scan.nextDouble();
        System.out.println(dd);
        //4.取得字串
        String str = scan.nextLine();
        System.out.println(str);
    }
}

If

class Main {
  public static void main(String[] argv){
    int a = 3;
    if(a==1){
      System.out.println("Equal to one");
    }else if(a==2){
      System.out.println("Equal to two");
    }else{
      System.out.println("Equal to nothing");
    }
  }
}

While

class Main {
  public static void main(String[] argv) {
    int counter = 10;

    while(counter>0){
      System.out.println(counter);
      counter--;
    }
  }
}

For

class Main {
  public static void main(String[] argv) {
    for(int i=0;i<10;i++){
      System.out.println(i);
    }
  }
}

Try Catch

class Main {
  public static void main(String[] args) {
    try {
      System.out.println(1 / 0);
    }
    catch (ArithmeticException qqqq) {
      System.out.println("算術錯誤的例外");
    }
    catch (Exception dddd) {
      System.out.println("something wrong");
    }
  }
}

類別class

class Main{
  public static void main(String[] args){
    //build a fish;
    fish f1 = new fish("Jellyfish","White");
    System.out.println(f1.Name);
    System.out.println(f1.Color);
    //movement
    f1.swim();
  }
  public static class fish {
    String Name = "";
    String Color = "";
    //Constructor
    public fish(String Name, String Color){
      this.Name = Name;
      this.Color = Color;
    }
    //Function
    public void swim(){
      System.out.println("splaxh~");
    }
  }
}

網路聊天室

  • GUI
  • 多執行緒
  • 網路連線

GUI

 

import java.awt.*;
import java.awt.event.*;
import java.awt.Container;
import java.awt.Color;
import javax.swing.*;

public class Example2 extends JFrame{
	JLabel Label = new JLabel("Click and plus one");
	JButton Button = new JButton("+1");
	JTextArea Area = new JTextArea("0");
	JPanel p = new JPanel();

	public static void main(String[] args) {
		Example2 main = new Example2();
		main.setSize(500,500);
		main.setVisible(true);
		main.setResizable(true);
		main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		main.setLocationRelativeTo(null);
	}
	Example2(){
		super("GUI test");
		p.setLayout(null);
		//p.setBackground(Color.GRAY);
		p.setOpaque(true);
		Label.setBounds(20,20,200,20);
		Button.setBounds(20,110,200,20);
		Area.setBounds(20,50,30,20);

		Container c = this.getContentPane();
		c.add(Label);
		c.add(Button);
		c.add(Area);
		c.add(p);
	}
}

多執

行緒

 

EX1: 找打手

EX2: 賽馬

class Main {
  public static void main(String[] args) {
    Worker w1 = new Worker();
    w1.start();
    System.out.println("Homework had been finished in main.");
  }
  public static class Worker extends Thread {
    public void run(){
      System.out.println("Homework had been finished in Thread.");
    }
  }
}
class Main {
  public static void main(String[] args) {
    int h1 = 0;
    Horse h2 = new Horse();
    h2.start();
    for(int i=0;i<100;i++){
      h1++;
      System.out.println("H1: "+h1);
    }
  }
  
  public static class Horse extends Thread{
    public void run(){
      int h = 0;
      for(int i=0;i<100;i++){
        h++;
        System.out.println("H2: "+h);
      }
    }
  }
}

網路

連線

import java.net.*;

class Main {
    public static void main(String[] argv) {
        String ip = "127.0.0.1";
        int port = 3000;
        //建立連線
        Socket c1 = new Socket(ip,port);
    }
}

聊天室程式碼

有挖空要自己填坑喔(5個)

import java.io.*; 
import java.net.*;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.*;
import javax.swing.*;

public class Example2 extends JFrame implements ActionListener{
	JLabel iplabel = new JLabel("IP:");
	JTextArea ipArea = new JTextArea();
	JLabel portlabel = new JLabel("Port:");
	JTextArea portArea = new JTextArea();
	JLabel useridlabel = new JLabel("暱稱:");
	JTextArea userid = new JTextArea();
	JButton connect = new JButton("連 線");
	JLabel chatroomlabel = new JLabel("工資館營聊天室");
	JTextArea chatroom = new JTextArea();
	JLabel inputmessagelabel = new JLabel("輸入訊息:");
	JTextArea inputmessage = new JTextArea();
	JButton send = new JButton("傳 送");
	JPanel p = new JPanel() ;
	JScrollPane scroll;
	Socket cl;
	BufferedReader  reader;           
	PrintStream  writer;
	String name="";
	String ip="";
	DataInputStream dis;
	public static void main(String[] args) throws Exception {
		Example2 main = new EXample2(); 
		main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		main.setSize(500,670);
		main.setVisible(true);
		main.setResizable(false);
		main.setLocationRelativeTo(null);
	}
	Example2 (){
		super("GUI Client");
		p.setLayout(null) ;
		p.setBackground(Color.GRAY);
		p.setOpaque(true);
		iplabel.setBounds(20, 20, 30, 20);
		
		ipArea.setBounds(50, 20, 200, 20);
		
		portlabel.setBounds(270, 20, 40, 20);
		
		portArea.setBounds(320, 20, 150, 20);
		
		useridlabel.setBounds(20, 50, 50, 20);
		
		userid.setBounds(70, 50, 180, 20);
		
		connect.setBounds(270, 50, 70, 20);
		connect.setBackground(Color.white);
		connect.setOpaque(true);
		connect.addActionListener(this);
		chatroomlabel.setBounds(20, 80, 100, 20);
		scroll =new JScrollPane(chatroom);
		scroll.setVerticalScrollBarPolicy(
				JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		scroll.setVerticalScrollBarPolicy(
			    ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 
		scroll.setBounds(20, 100, 450, 400);
		
		inputmessagelabel.setBounds(20,510,100,20);
		
		inputmessage.setBounds(20,530,375,50);
		
		send.setBounds(400, 530, 70, 50);
		send.setBackground(Color.white);
		send.setOpaque(true);
		send.addActionListener(this);
		Container c = this.getContentPane();
		c.add(iplabel);
		c.add(ipArea);
		c.add(portlabel);
		c.add(portArea);
		c.add(useridlabel);
		c.add(userid);
		c.add(connect);
		c.add(chatroomlabel);
		//c.add(chatroom);
		c.add(scroll);
		c.add(inputmessagelabel);
		c.add(inputmessage);
		c.add(send);
		c.add(p);
	}
	public class IncomingReader implements Runnable{
		public void run(){
			String message;
			try{
				 while (true){
					 if((message = reader.readLine()) != null) {   
						 chatroom.append(message+'\n');
					 }
					 else {
						 break;
					 }
				 }
				 scroll=new JScrollPane(chatroom);
				
			}catch(Exception ex ){
				ex.printStackTrace();
			}
		}
	} 
	private void EstablishConnection(){
		  try{
		   //請求建立連線
			  ip=ipArea.getText();
			  String port=portArea.getText();
			  int i=Integer.parseInt(port);
			  cl = new Socket(ip,i);   
			  InputStreamReader streamReader =  
					     //取得Socket的輸入資料流
					      new InputStreamReader(cl.getInputStream());  
					   //放入暫存區
					   reader = new BufferedReader(streamReader);    
					   //取得Socket的輸出資料流
					   
					   writer = new PrintStream(cl.getOutputStream());  
			   
		  }catch(Exception ex ){
			  ex.printStackTrace();
		   System.out.println("建立連線失敗");
		  }
	}
	public void actionPerformed(ActionEvent e){
		String str=e.getActionCommand();   
		  //按下設定
		if(str.equals("連 線")){
			ip  = ipArea.getText(); 
			 EstablishConnection();          
			   //建立接收資料執行緒----
			Thread readerThread = new Thread(new IncomingReader());  
			readerThread.start();
			  //按下送出   
			}
		else if(str.equals("傳 送")){    
			   //不可沒有ip及送出空白
			ip  = ipArea.getText(); 
			name=userid.getText();
			if((ip!=null)&&(inputmessage.getText()!="")){
			    try{//送出資料
			    	writer.println((name+":"+inputmessage.getText())); 
			     //刷新該串流的緩衝。
			    writer.flush();         
			    }catch(Exception ex ){
			     System.out.println("送出資料失敗");
			    }
			    //清完輸入欄位
			    inputmessage.setText("");        
		  //按下送出   
			}
		}
	}
}

Setting

  • IP : 140.116.7.193
  • Port : (一二三小) : 9999
  • Port : (四五六小) : 8888

deck

By wiasliao

deck

  • 306