Java – ArrayList przykład

Java lista tablicowa.

Metody:

  • add(Object o) – dodaje element do listy
  • remove(Object o) – usuwa pierwsze wystąpienie podanego obiektu z listy
  • remove(int index ) – usuwa z listy element o wskazanym indeksie
  • size() – odpowiednik własności length w przypadku tablic – zwraca rozmiar listy
  • get(int index ) – pozwala odczytać element o wskazanym indeksie
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;

public class ArrayListEx { 

    public static void main(String[] args) throws IOException { 

        BufferedReader userInput = new BufferedReader
            (new InputStreamReader(System.in));

        ArrayList<String> myArr = new ArrayList<String>();
        myArr.add("napis 1");
        myArr.add("napis 2");
        myArr.add("napis 3");
        myArr.add("napis 4");
        myArr.add("napis 5");

         Collections.sort(myArr);

        for(int i=0; i<myArr.size(); i++)
            System.out.println(myArr.get(i));
    }
} 

Java – współbieżny serwer echa – dla wielu klientów

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
*
* @author Maciej Kuropatwa
*/
public class EchoServer2 extends Thread
{
protected Socket clientSocket;

public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;

try {
serverSocket = new ServerSocket(10008);

while (true)
{
System.out.println ("Oczekiwanie na połączenie");
new EchoServer2 (serverSocket.accept());
}

}
catch (IOException e)
{
System.exit(1);
}
finally
{

serverSocket.close();

}
}

private EchoServer2 (Socket clientSoc)
{
clientSocket = clientSoc;
start();
}

public void run()
{

try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader in = new BufferedReader( new InputStreamReader( clientSocket.getInputStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
{
System.out.println ("Server: " + inputLine);
out.println(inputLine);

if (inputLine.equals("exit"))
break;
}

out.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{

System.exit(1);
}
}
} 

 

import java.io.*;
import java.net.*;

public class EchoClient2 {
public static void main(String[] args) throws IOException {

String serverHostname = "127.0.0.1";

Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;

echoSocket = new Socket(serverHostname, 10008);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));

BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in));
String userInput;

while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);

if (userInput.equals("exit."))
break;

System.out.println("echo: " + in.readLine());
}

out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}

Java – server echa + client

Przykład servera akceptującego połączenie jednego klienta:


import java.net.*;
import java.io.*;

public class ServerEcho
{
 public static void main(String[] args) throws IOException
 {
 ServerSocket serverSocket = null;

try {
 serverSocket = new ServerSocket(10001);
 }
 catch (IOException e)
 {
 System.err.println("Nie można nasłuchiwać na podanym porcie.");
 System.exit(1);
 }

Socket clientSocket = null;
 System.out.println ("Oczekiwanie na połączenie.....");

try {
 clientSocket = serverSocket.accept();
 }
 catch (IOException e)
 {
 System.err.println("Błąd przy próbie akceptacji połączenia.");
 System.exit(1);
 }

System.out.println ("Połączono!");
 System.out.println ("Oczekiwanie na informacje.....");

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
 BufferedReader in = new BufferedReader( new InputStreamReader( clientSocket.getInputStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
 {
 System.out.println ("Server: " + inputLine);
 out.println(inputLine);
 }

out.close();
 in.close();
 clientSocket.close();
 serverSocket.close();
 }
}

Przykład klienta:

import java.io.*;
import java.net.*;

public class ClientEcho {
    public static void main(String[] args) throws IOException {

        String serverHostname = "127.0.0.1";

        System.out.println ("Próba połączenia z hostem " + serverHostname + " na porcie 10001.");

        Socket echoSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        echoSocket = new Socket(serverHostname, 10001);
        out = new PrintWriter(echoSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));

	BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
	String userInput;

        System.out.print ("Dane wejściowe: ");
	while ((userInput = stdIn.readLine()) != null) {
	    out.println(userInput);
	    System.out.println("ECHO: " + in.readLine());
            System.out.print ("Wczytywanie: ");

            if (userInput.equals("exit"))
             break;
	}

	out.close();
	in.close();
	stdIn.close();
	echoSocket.close();
    }
}

Java – Skaner portów

Poniższy program pozwala na skanowanie portów z podanego przedziału liczbowego. Sprawdza każdy port po kolei i wyświetla informację na temat jego zajętości.


import java.net.*;

public class PortScanner

{

public static void main(String args[])
 {
 int startPort=4440;
 int stopPort=4450;
 for(int i=startPort; i <=stopPort; i++)
 {
 try
 {
 Socket socket = new Socket("127.0.0.1",i);

System.out.println("Port jest w uzyciu: " + i );

socket.close();
 }
 catch (Exception e)
 {
 }
 System.out.println("Port nie jest w uzyciu: " + i );
 }
 }
}

11349 – Symmetric Matrix – UVA solution

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

int size;
bool symmetric;
long long matrix[105][105];

void is_symmetric ()
{
 if ( !symmetric ) return;

 for ( int i = 0; i < size; i++ ) {
 for ( int j = 0; j < size; j++ ) {
 if ( matrix [i] [j] != matrix [size - 1 - i] [size - 1 - j] ) { symmetric = false; return; }
 }
 }
}

int main()
{
 int cases;
 scanf ("%d", &cases);

 int temp = 0;

 while(cases--)
 {
 char znaki[100];

 cin >> znaki[0];
 cin >> znaki [1];
 scanf ("%d", &size);

 symmetric = true;

 for ( int i = 0; i < size; i++ ) {
 for ( int j = 0; j < size; j++ ) {
 cin >> matrix [i] [j];
 if ( matrix [i] [j] < 0 ) symmetric = false;
 }
 }

 printf("Test #%d: ", ++temp);

 if ( !symmetric ) {
 printf ("Non-symmetric.\n");
 continue;
 }

 is_symmetric ();

 if ( symmetric ) printf ("Symmetric.\n");
 else printf ("Non-symmetric.\n");

 }

 return 0;
}

Photoshop – efekt rozdartego papieru

Rozdzielczość: 1680×1096
Format: PSD
Rozmiar: 2.04 MB
Autor: Free PSD Files

DOWNLOAD

Java – konwersja z Integer na String

Możemy w łatwy sposób przekonwertować integer na string za pomocą metody toString().

Przykład:

int i = 12;
String str = Integer.toString(i);

Lub:

 String str = "" + i

Java – Tworzenie screenshot’a – zrzut ekranu

Poniższy kod, jest kodem źródłowym programu za pomocą którego możemy zrobić zrzut ekranu.

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Screenshooter {

    public static void main(String[] args) throws AWTException, IOException {

            Robot robot = new Robot();
            BufferedImage bi=robot.createScreenCapture(new Rectangle(600,600));
            ImageIO.write(bi, "jpg", new File("D:/screenTest.jpg"));

       }
}

Java – silnia wielkich liczb – BigInteger

Aby rekurencyjnie policzyć silnię w javie wystarczy kod podobny do poniższego:

import java.util.*;

public class Main {
    public static int factorial(int n){
        if (n == 0) return 1;
        else return n * factorial(n - 1);
    }

    public static void main(String args[]){
        int n;
        System.out.println("Podaj liczbe do policzenia silni: ");
        Scanner wejscie=new Scanner(System.in);
        n = wejscie.nextInt();
        System.out.println(n+"! = "+ factorial(n));
    }
}

Jednakże taki program nie zadziała dla większych liczb. Warto w tym celu użyć klasy BigInteger.

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
public static BigInteger factorial(int n){
    BigInteger product = BigInteger.ONE;

    if (n < 0){
        System.out.println ("Factorial Error! n = "+n);
        return new BigInteger ("-1");
    }

    for (int c = n; c > 0; c --){
        product = product.multiply(BigInteger.valueOf(c));
    }

    System.out.println ("Factorial "+n+"! = "+product);

    return product;
}

    public static void main(String[] args) {
         int n;
        System.out.println("Podaj do policzenia silni: ");
        Scanner wejscie=new Scanner(System.in);
        n = wejscie.nextInt();
        factorial(n);
    }

}

Java – tworzenie okienka z zakładkami, czyli Tabbed Pane

Java Tabbed Pane odpowiednio grupuje komponenty. Po kliknięciu w odpowiednią zakładkę wyświetlane są odpowiednie elementy z danej grupy. Bardzo przydatne i proste rozwiązanie.

Powyższy efekt osiągniemy za pomocą poniższego kodu źródłowego.

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class OkienkoZZakladkami extends JFrame {

    public OkienkoZZakladkami() {

        setTitle("Okienko z zakładkami");
        JTabbedPane jtp = new JTabbedPane();
        getContentPane().add(jtp);
        JPanel jp1 = new JPanel();
        JPanel jp2 = new JPanel();
        JLabel label1 = new JLabel();
        label1.setText("Zawartość obszaru pierwszej zakładki");
        JLabel label2 = new JLabel();
        label2.setText("Zawartość obszaru drugiej zakładki");
        jp1.add(label1);
        jp2.add(label2);
        jtp.addTab("Zakładka 1", jp1);
        jtp.addTab("Zakładka 2", jp2);

    }
    public static void main(String[] args) {

        OkienkoZZakladkami tp = new OkienkoZZakladkami();
        tp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        tp.setVisible(true);

    }
}