gb-java-devel/sources-draft/notebook.ipynb

1813 lines
48 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Оставшиеся темы из ООП"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Seasons"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"enum Season { WINTER, SPRING, SUMMER, AUTUMN }"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Season current = Season.SPRING; \n",
"System.out.println(current);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Season[] seasons = Season.values(); \n",
"for (Season s : seasons) { \n",
" System.out.printf(\"s \", s); \n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"System.out.println(current.ordinal())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"System.out.println(Seasons.ordinal())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Colors"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"enum Color {\n",
" RED(\"#FF0000\"), GREEN(\"#00FF00\"), BLUE(\"#0000FF\");\n",
" String code;\n",
" Color (String code) {\n",
" this.code = code;\n",
" }\n",
" String getCode() {\n",
" return code;\n",
" }\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for (Color c : Color.values()) {\n",
" System.out.printf(\"%s(%s) \", c, c.getCode());\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Nested Classes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Создадим апельсин"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"public class Orange {\n",
" public void squeezeJuice() {\n",
" System.out.println(\"Squeeze juice ...\");\n",
" }\n",
" class Juice {\n",
" public void flow() {\n",
" System.out.println(\"Juice dripped ...\");\n",
" }\n",
" } \n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Orange orange = new Orange(); \n",
"Orange.Juice juice = orange.new Juice(); \n",
"orange.squeezeJuice(); \n",
"juice.flow();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Изменим апельсин"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"public class Orange {\n",
" private Juice juice; \n",
" public Orange() {\n",
" this.juice = new Juice();\n",
" }\n",
" public void squeezeJuice(){\n",
" System.out.println(\"Squeeze juice ...\"); \n",
" juice.flow();\n",
" }\n",
" private class Juice {\n",
" public void flow() {\n",
" System.out.println(\"Juice dripped ...\");\n",
" }\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Orange orange = new Orange(); \n",
"orange.squeezeJuice(); "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Локальный класс"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"public class Animal {\n",
"\n",
" void performBehavior(boolean state) {\n",
" class Brain {\n",
" void sleep() {\n",
" if(state) {\n",
" System.out.println(\"Sleeping\");\n",
" } else {\n",
" System.out.println(\"Not sleeping\");\n",
" }\n",
" }\n",
" }\n",
" Brain brain = new Brain();\n",
" brain.sleep();\n",
" }\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Animal animal = new Animal();\n",
"animal.performBehavior(true);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Статические вложенные классы"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"public class Cat {\n",
" private String name, color;\n",
" private int age;\n",
"\n",
" public Cat() { }\n",
" public Cat(String name, String color, int age) {\n",
" this.name = name;\n",
" this.color = color;\n",
" this.age = age;\n",
" }\n",
"\n",
" static class Voice {\n",
" private final int volume;\n",
" public Voice(int volume) { this.volume = volume; }\n",
" public void sayMur() {\n",
" System.out.printf(\n",
" \"A cat purrs with volume %d\\n\", volume);\n",
" }\n",
" }\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Cat.Voice voice = new Cat.Voice(100);\n",
"voice.sayMur();"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for (int i = 0; i < 4; i++) {\n",
" Cat.Voice voice = new Cat.Voice(100 + i);\n",
" voice.sayMur();\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Исключения"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"private static int div0() {\n",
" return 1 / 0;\n",
"}\n",
"private static int div1() {\n",
" return div0();\n",
"}\n",
"private static int div2() {\n",
" return div1();\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"div2();"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"private static int div0(int a, int b) {\n",
" return a / b;\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"private static int div0(int a, int b) {\n",
" if (b != 0) {\n",
" return a / b;\n",
" }\n",
" return /* ??? */;\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"private static int div0(int a, int b) {\n",
" if (b == 0) {\n",
" throw new RuntimeException(\"parameter error\");\n",
" }\n",
" return a / b;\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"System.out.println(div0(1,2));\n",
"System.out.println(div0(1,0));"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"int[] arr = {1};\n",
"System.out.println(arr[2])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"public void methodB() throws IOException {\n",
" throw new IOException();\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"public void methodA() {\n",
" RuntimeException e = new RuntimeException();\n",
" //throw e;\n",
" methodB();\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class TestStream implements Closeable {\n",
" TestStream() throws Exception {\n",
"// System.out.println(\"construct OK\");\n",
" throw new Exception();\n",
" }\n",
" int read() throws FileNotFoundException {\n",
" new FileInputStream(\"file.txt\");\n",
" System.out.println(\"read OK\");\n",
" return 1;\n",
" }\n",
" public void close() throws IOException {\n",
" System.out.println(\"close OK\");\n",
" throw new IOException();\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"TestStream stream = null;\n",
"try {\n",
" stream = new TestStream();\n",
" int i = stream.read();\n",
"} catch (FileNotFoundException fnfe) {\n",
" System.out.println(\"read NOT OK\");\n",
"} catch (IOException e) {\n",
" System.out.println(\"close NOT OK\");\n",
"} catch (Exception e) {\n",
" System.out.println(\"construct NOT OK\");\n",
"} finally {\n",
" if (stream != null)\n",
" stream.close();\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try (TestStream stream = new TestStream()) {\n",
" int a = stream.read();\n",
"} catch (IOException e) {\n",
" new RuntimeException(e);\n",
"}\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Файлы"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"File file = new File(\"file.txt\");"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"File folder = new File(\".\");\n",
"for (File file : folder.listFiles()) {\n",
" System.out.println(file.getName());\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"System.out.println(\"Is it a folder - \" + folder.isDirectory());\n",
"System.out.println(\"Is it a file - \" + folder.isFile());\n",
"File file = new File(\"./Dockerfile\");\n",
"System.out.println(\"Length file - \" + file.length());\n",
"System.out.println(\"Absolute path - \" + file.getAbsolutePath());\n",
"System.out.println(\"Total space on disk - \" + folder.getTotalSpace());\n",
"System.out.println(\"File deleted - \" + file.delete());\n",
"System.out.println(\"File exists - \" + file.exists());\n",
"System.out.println(\"Free space on disk - \" + folder.getFreeSpace());"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import java.io.File;\n",
"import java.io.IOException;\n",
"import java.nio.charset.StandardCharsets;\n",
"import java.nio.file.Files;\n",
"import java.nio.file.Path;\n",
"import java.nio.file.Paths;\n",
"import java.util.Arrays;\n",
"import java.util.List;"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"List<String> lines = Arrays.asList(\n",
" \"The cat wants to play with you\", \n",
" \"But you don't want to play with it\");\n",
"\n",
"Path file = Files.createFile(Paths.get(\"cat.txt\"));\n",
"\n",
"if(Files.exists(file)) {\n",
" Files.write(file, lines, StandardCharsets.UTF_8);\n",
" lines = Files.readAllLines(\n",
" Paths.get(\"cat.txt\"), StandardCharsets.UTF_8);\n",
"\n",
" for (String s : lines) {\n",
" System.out.println(s);\n",
" }\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Files.delete(file);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import java.io.ByteArrayInputStream;\n",
"import java.io.ByteArrayOutputStream;\n",
"import java.io.File;\n",
"import java.io.FileInputStream;\n",
"import java.io.FileNotFoundException;\n",
"import java.io.FileOutputStream;\n",
"import java.io.IOException;\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ByteArrayOutputStream out = new ByteArrayOutputStream();\n",
"\n",
"out.write(1);\n",
"out.write(-1);\n",
"out.write(0);\n",
"\n",
"ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());\n",
"\n",
"int value = in.read();\n",
"System.out.println(\"First element is - \" + value);\n",
"\n",
"value = in.read();\n",
"System.out.println(\"Second element is - \" + value + \n",
" \". If (byte)value - \" + (byte)value);\n",
"\n",
"value = in.read();\n",
"System.out.println(\"Third element is - \" + value);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"byte[] bytesToWrite = {0, 10, 12, 14, 55, 13, 23};\n",
"byte[] bytesToRead = new byte[10];\n",
"File file = new File(\"bytes.txt\");\n",
"\n",
"try {\n",
" System.out.println(\"Begin\");\n",
" FileOutputStream outFile = new FileOutputStream(file);\n",
" outFile.write(bytesToWrite); outFile.close();\n",
" System.out.println(\"Bytes written\");\n",
"\n",
" FileInputStream inFile = new FileInputStream(file);\n",
" int bytesAvailable = inFile.available();\n",
" System.out.println(\"Ready to read \" + bytesAvailable + \" bytes\");\n",
"\n",
" int count = inFile.read(bytesToRead, 0, bytesAvailable);\n",
" for (int i = 0; i < count; i++) \n",
" System.out.print(\" \" + bytesToRead[i]);\n",
"\n",
" System.out.println(); inFile.close();\n",
" System.out.println(\"Input stream closed\");\n",
"\n",
"} catch (FileNotFoundException e) {\n",
" System.out.println(\"Unable to write data to file - \" + file.getName());\n",
"} catch (IOException e) {\n",
" System.out.println(\"Error input/output: \" + e.toString());\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try {\n",
" String fileName = \"test.txt\";\n",
" InputStream inStream = null;\n",
" OutputStream outStream = null;\n",
"\n",
" long timeStart = System.currentTimeMillis();\n",
" outStream = new BufferedOutputStream(new FileOutputStream(fileName));\n",
" for (int i = 1000000; --i >= 0;) { outStream.write(i); }\n",
"\n",
" long time = System.currentTimeMillis() - timeStart;\n",
" System.out.println(\"Writing time: \" + time + \" millisec\");\n",
" outStream.close();\n",
"\n",
" timeStart = System.currentTimeMillis();\n",
" inStream = new FileInputStream(fileName);\n",
" while (inStream.read() != -1) { }\n",
"\n",
" time = System.currentTimeMillis() - timeStart;\n",
" inStream.close();\n",
" System.out.println(\"Direct read time: \" + (time) + \" millisec\");\n",
"\n",
" timeStart = System.currentTimeMillis();\n",
" inStream = new BufferedInputStream(new FileInputStream(fileName));\n",
" while (inStream.read() != -1) { }\n",
"\n",
" time = System.currentTimeMillis() - timeStart;\n",
" inStream.close();\n",
" System.out.println(\"Buffered read time: \" + (time) + \" millisec\");\n",
" \n",
"} catch (IOException e) {\n",
" System.out.println(\"IOException: \" + e.toString());\n",
" e.printStackTrace();\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"String fileName = \"test.txt\";\n",
"InputStream inStream = null;\n",
"OutputStream outStream = null;"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try {\n",
" long timeStart = System.currentTimeMillis();\n",
" outStream = new BufferedOutputStream(new FileOutputStream(fileName));\n",
" for (int i = 1000000; --i >= 0;) { outStream.write(i); }\n",
"\n",
" long time = System.currentTimeMillis() - timeStart;\n",
" System.out.println(\"Writing time: \" + time + \" millisec\");\n",
" outStream.close();\n",
"} catch (IOException e) {\n",
" System.out.println(\"IOException: \" + e.toString());\n",
" e.printStackTrace();\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try {\n",
" long timeStart = System.currentTimeMillis();\n",
" InputStream inStream = new FileInputStream(fileName);\n",
" while (inStream.read() != -1) { }\n",
"\n",
" long time = System.currentTimeMillis() - timeStart;\n",
" inStream.close();\n",
" System.out.println(\"Direct read time: \" + (time) + \" millisec\");\n",
"} catch (IOException e) {\n",
" System.out.println(\"IOException: \" + e.toString());\n",
" e.printStackTrace();\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try {\n",
" long timeStart = System.currentTimeMillis();\n",
" inStream = new BufferedInputStream(new FileInputStream(fileName));\n",
" while (inStream.read() != -1) { }\n",
"\n",
" long time = System.currentTimeMillis() - timeStart;\n",
" inStream.close();\n",
" System.out.println(\"Buffered read time: \" + (time) + \" millisec\"); \n",
"} catch (IOException e) {\n",
" System.out.println(\"IOException: \" + e.toString());\n",
" e.printStackTrace();\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import java.io.ByteArrayInputStream;\n",
"import java.io.ByteArrayOutputStream;\n",
"import java.io.DataInputStream;\n",
"import java.io.DataOutputStream;\n",
"import java.io.InputStream;\n",
"\n",
"ByteArrayOutputStream out = new ByteArrayOutputStream();"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try {\n",
" DataOutputStream outData = new DataOutputStream(out);\n",
"\n",
" outData.writeByte(128);\n",
" outData.writeInt(128);\n",
" outData.writeLong(128);\n",
" outData.writeDouble(128);\n",
" outData.close();\n",
"} catch (Exception e) {\n",
" System.out.println(\"Impossible IOException occurs: \" + e.toString());\n",
" e.printStackTrace();\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try {\n",
" byte[] bytes = out.toByteArray();\n",
" InputStream in = new ByteArrayInputStream(bytes);\n",
" DataInputStream inData = new DataInputStream(in);\n",
"\n",
" System.out.println(\"Reading in the correct sequence: \");\n",
" System.out.println(\"readByte: \" + inData.readByte());\n",
" System.out.println(\"readInt: \" + inData.readInt());\n",
" System.out.println(\"readLong: \" + inData.readLong());\n",
" System.out.println(\"readDouble: \" + inData.readDouble());\n",
" inData.close();\n",
"} catch (Exception e) {\n",
" System.out.println(\"Impossible IOException occurs: \" + e.toString());\n",
" e.printStackTrace();\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try {\n",
" byte[] bytes = out.toByteArray();\n",
" InputStream in = new ByteArrayInputStream(bytes);\n",
" DataInputStream inData = new DataInputStream(in);\n",
"\n",
" System.out.println(\"Reading in a modified sequence:\"); \n",
" System.out.println(\"readInt: \" + inData.readInt());\n",
" System.out.println(\"readDouble: \" + inData.readDouble());\n",
" System.out.println(\"readLong: \" + inData.readLong());\n",
" \n",
" inData.close();\n",
"} catch (Exception e) {\n",
" System.out.println(\"Impossible IOException occurs: \" + e.toString());\n",
" e.printStackTrace();\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import java.io.IOException;\n",
"import java.io.RandomAccessFile;\n",
"import java.nio.ByteBuffer;\n",
"import java.nio.channels.FileChannel;"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try (RandomAccessFile catFile = new RandomAccessFile(\"cat.txt\", \"rw\")) {\n",
" FileChannel inChannel = catFile.getChannel();\n",
" ByteBuffer buf = ByteBuffer.allocate(100);\n",
" int bytesRead = inChannel.read(buf);\n",
"\n",
" while (bytesRead != -1) {\n",
" System.out.println(\"Read \" + bytesRead + \" bytes\");\n",
" // Set read mode\n",
" buf.flip();\n",
" while (buf.hasRemaining()) {\n",
" System.out.print((char) buf.get());\n",
" }\n",
"\n",
" buf.clear();\n",
" bytesRead = inChannel.read(buf);\n",
" }\n",
"} catch (IOException e) { e.printStackTrace(); }"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import java.nio.charset.StandardCharsets;\n",
"\n",
"String s1 = \"Java\";\n",
"String s2 = new String(\"Home\");\n",
"String s3 = new String(new char[] { 'A', 'B', 'C' });\n",
"String s4 = new String(s3);\n",
"String s5 = new String(new byte[] { 65, 66, 67 });\n",
"String s6 = new String(new byte[] { 0, 65, 0, 66 }, StandardCharsets.UTF_16);\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"String a1 = \"Hello \";\n",
"String a2 = \"World\";\n",
"String a3 = a1 + a2;\n",
"\n",
"System.out.println(a3);\n",
"\n",
"String b1 = \"Number 10: \";\n",
"int b2 = 10;\n",
"String b3 = b1 + b2;\n",
"\n",
"System.out.println(b3);\n",
"\n",
"String c1 = \"Home\";\n",
"String c2 = \"[\" + c1 + \"] = \" + 1;\n",
"\n",
"System.out.println(c2);\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"String str0 = \"Fifty five is \" + 50 + 5;\n",
"System.out.println(str0);\n",
"String str1 = 50 + 5 + \" = Fifty five\";\n",
"System.out.println(str1);\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"String s = \"Example\";\n",
"long timeStart = System.nanoTime();\n",
"for (int i = 0; i < 100_000; ++i) { s = s + i; }\n",
"double deltaTime = (System.nanoTime() - timeStart) * 0.000000001;\n",
"System.out.println(\"Delta time (sec): \" + deltaTime);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"StringBuilder sb = new StringBuilder(\"Example\");\n",
"long timeStart = System.nanoTime();\n",
"for (int i = 0; i < 100_000; ++i) { sb = sb.append(i); }\n",
"double deltaTime = (System.nanoTime() - timeStart) * 0.000000001;\n",
"System.out.println(\"Delta time (sec): \" + deltaTime);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"String cat0 = \"BestCat\";\n",
"String cat1 = \"BestCat\";\n",
"String cat2 = \"Best\" + \"Cat\";\n",
"String cat30 = \"Best\";\n",
"String cat3 = cat30 + \"Cat\";\n",
"\n",
"System.out.println(\"cat0 equal to cat1? \" + (cat0 == cat1));\n",
"System.out.println(\"cat0 equal to cat2? \" + (cat0 == cat2));\n",
"System.out.println(\"cat0 equal to cat3? \" + (cat0 == cat3));\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Семинар 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Здесь создана переменная. Она будет загружена в память после выполнения этой ячейки и будет оставаться там всё время, пока идёт работа над кодом в следующих ячейках, или пока весь ноутбук целиком не будет перезапущен."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"int a = 10;\n",
"String fmt = \"Your number is %d\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Далее следует ячейка, где используется переменная, созданная выше. Мы можем сколько угодна вести работу над кодом в этой ячейке, важно помнить, что изменив значение этой переменной все последующие запуски ячейки будут обращаться к новому значению, а не инициализационному."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"System.out.printf(fmt, a);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Написать метод, возвращающий количество чётных элементов массива.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"int countEvens(int[] arr) {\n",
" int counter = 0;\n",
" for (int i = 0; i < arr.length; ++i) {\n",
" if (arr[i] % 2 == 0) {\n",
" counter++;\n",
" }\n",
" }\n",
" return counter;\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"System.out.println(countEvens(new int[]{2, 1, 2, 3, 4}));//3\n",
"System.out.println(countEvens(new int[]{2, 2, 0}));//3\n",
"System.out.println(countEvens(new int[]{1, 3, 5}));//0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Написать функцию, возвращающую разницу между самым большим и самым маленьким элементами переданного не пустого массива."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"int spread(int[] arr) {\n",
" int min = arr[0];\n",
" int max = arr[0];\n",
" for (int i = 1; i < arr.length; ++i) {\n",
" if (arr[i] < min) min = arr[i];\n",
" if (arr[i] > max) max = arr[i];\n",
" }\n",
" return max - min;\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"System.out.println(spread(new int[]{2, 1, 2, 3, 4}));//3\n",
"System.out.println(spread(new int[]{2, 2, 0}));//3\n",
"System.out.println(spread(new int[]{1, 3, 5}));//0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Написать функцию, возвращающую истину, если в переданном массиве есть два соседних элемента, с нулевым значением."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"boolean zero2(int[] arr) {\n",
" for (int i = 0; i < arr.length - 1; ++i) {\n",
" if (arr[i] == 0 && arr[i + 1] == 0)\n",
" return true;\n",
" }\n",
" return false;\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"System.out.println(zero2(new int[]{2, 1, 0, 0, 4}));//3\n",
"System.out.println(zero2(new int[]{2, 2, 0}));//3\n",
"System.out.println(zero2(new int[]{1, 3, 5}));//0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Семинар 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"String caesar(String in, int key, boolean encrypt) {\n",
" if (in == null || in.isEmpty())\n",
" return null;\n",
"\n",
" final int len = in.length();\n",
" char[] out = new char[len];\n",
" for (int i = 0; i < len; ++i) {\n",
" out[i] = (char) (in.charAt(i) + ((encrypt) ? key : -key));\n",
" }\n",
" return new String(out);\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"System.out.println(caesar(\"Hello\", 5, true));\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"private static void shifter(int[] a, int n) {\n",
" n %= a.length;\n",
" int shift = a.length + n;\n",
" shift %= a.length;\n",
"\n",
" for (int i = 0; i < shift; i++) {\n",
" int temp = a[a.length - 1];\n",
" System.arraycopy(a, 0, a, 1, a.length - 1);\n",
" a[0] = temp;\n",
" }\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"int[] arr = {1,2,3,4,5};\n",
"System.out.println(Arrays.toString(arr));\n",
"shifter(arr, 2);\n",
"System.out.println(Arrays.toString(arr));\n",
"shifter(arr, -2);\n",
"System.out.println(Arrays.toString(arr));\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"int[] add(int[] arr, int current, int value) {\n",
" if (current == arr.length) {\n",
" int[] temp = new int[arr.length * 2];\n",
" System.arraycopy(arr, 0, temp, 0, arr.length);\n",
" arr = temp;\n",
" }\n",
" arr[current++] = value;\n",
" return arr;\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"int[] array = {1,2};\n",
"int size = 2;\n",
"\n",
"System.out.println(size + \" = \" + Arrays.toString(array));\n",
"array = add(array, size++, 6);\n",
"System.out.println(size + \" = \" + Arrays.toString(array));\n",
"array = add(array, size++, 6);\n",
"System.out.println(size + \" = \" + Arrays.toString(array));\n",
"array = add(array, size++, 6);\n",
"System.out.println(size + \" = \" + Arrays.toString(array));\n",
"array = add(array, size++, 6);\n",
"System.out.println(size + \" = \" + Arrays.toString(array));\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Семинар 5"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Создать пару-тройку текстовых файлов. Для упрощения (чтобы не разбираться с кодировками) внутри файлов следует писать текст только латинскими буквами"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import java.io.File;\n",
"import java.nio.file.Files;\n",
"import java.nio.file.Path;\n",
"import java.io.FileInputStream;\n",
"import java.io.FileOutputStream;\n",
"import java.io.IOException;\n",
"import java.util.Random;\n",
"import java.util.Scanner;\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"private static final Random rnd = new Random();\n",
"private static final int CHAR_BOUND_L = 65;\n",
"private static final int CHAR_BOUND_H = 90;\n",
"private static final int FILES_AMOUNT = 10;\n",
"private static final int WORDS_AMOUNT = 5;\n",
"private static final int WORD_LENGTH = 10;\n",
"private static final String WORD_TO_SEARCH = \"geekbrains\";\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"String[] fileNames = new String[FILES_AMOUNT];\n",
"for (int i = 0; i < fileNames.length; i++)\n",
" fileNames[i] = \"file_\" + i + \".txt\";"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"private static String generateSymbols(int amount) {\n",
" StringBuilder sequence = new StringBuilder();\n",
" for (int i = 0; i < amount; i++)\n",
" sequence.append((char) (CHAR_BOUND_L + rnd.nextInt(CHAR_BOUND_H - CHAR_BOUND_L)));\n",
" return sequence.toString();\n",
"}\n",
"\n",
"private static void writeFileContents(String fileName, int length) throws IOException {\n",
" FileOutputStream fos = new FileOutputStream(fileName);\n",
" fos.write(generateSymbols(length).getBytes());\n",
" fos.flush();\n",
" fos.close();\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"private static void writeFileContents(String fileName, int words, int length) throws IOException {\n",
" FileOutputStream fos = new FileOutputStream(fileName);\n",
" for (int i = 0; i < words; i++) {\n",
" if(rnd.nextInt(WORDS_AMOUNT) == WORDS_AMOUNT / 2)\n",
" fos.write(WORD_TO_SEARCH.getBytes());\n",
" else\n",
" fos.write(generateSymbols(length).getBytes());\n",
" fos.write(' ');\n",
" }\n",
" fos.flush();\n",
" fos.close();\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"private static void concatenate(String file_in1, String file_in2, String file_out) throws IOException {\n",
" FileOutputStream fos = new FileOutputStream(file_out);\n",
" int ch;\n",
" FileInputStream fis = new FileInputStream(file_in1);\n",
" while ((ch = fis.read()) != -1)\n",
" fos.write(ch);\n",
" fis.close();\n",
"\n",
" fis = new FileInputStream(file_in2);\n",
" while ((ch = fis.read()) != -1)\n",
" fos.write(ch);\n",
" fis.close();\n",
"\n",
" fos.flush();\n",
" fos.close();\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"private static boolean isInFile(String fileName, String search) throws IOException {\n",
" FileInputStream fis = new FileInputStream(fileName);\n",
" byte[] searchSequence = search.getBytes();\n",
" int ch;\n",
" int i = 0; // geekgeekbrains\n",
" while ((ch = fis.read()) != -1) {\n",
" if (ch == searchSequence[i])\n",
" i++;\n",
" else {\n",
" i = 0;\n",
" if (ch == searchSequence[i]) i++;\n",
" }\n",
" if (i == searchSequence.length) {\n",
" fis.close();\n",
" return true;\n",
" }\n",
" }\n",
" fis.close();\n",
" return false;\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"private static boolean fileScanner(String fileName, String word) throws IOException {\n",
" Scanner sc = new Scanner(new FileInputStream(fileName));\n",
" word = word.toLowerCase(); // \\n\n",
" while (sc.hasNext()) {\n",
" String line = sc.nextLine();\n",
" line = line.toLowerCase();\n",
" if (line.contains(word)) return true;\n",
" }\n",
" return false;\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"private static String[] searchMatch(String[] files, String search) throws IOException {\n",
" String[] list = new String[files.length];\n",
" int count = 0;\n",
" File path = new File( new File(\".\").getCanonicalPath() );\n",
" File[] dir = path.listFiles();\n",
" for (int i = 0; i < dir.length; i++) {\n",
" if (dir[i].isDirectory()) continue;\n",
" for (int j = 0; j < files.length; j++)\n",
" if (dir[i].getName().equals(files[j]))\n",
" if (isInFile(dir[i].getName(), search)) {\n",
" list[count] = dir[i].getName();\n",
" count++;\n",
" break;\n",
" }\n",
" }\n",
" return list;\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try {\n",
" //#1\n",
" for (int i = 0; i < fileNames.length; i++)\n",
" if (i < 2)\n",
" writeFileContents(fileNames[i], 100);\n",
" else\n",
" writeFileContents(fileNames[i], WORDS_AMOUNT, WORD_LENGTH);\n",
" System.out.println(\"First task results are in file_0 and file_1.\");\n",
"}\n",
"catch (Exception ex) { throw new RuntimeException(ex); }\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try {\n",
" //#2\n",
" concatenate(fileNames[0], fileNames[1], \"FILE_OUT.txt\");\n",
" System.out.println(\"Second task result is in FILE_OUT.\");\n",
"}\n",
"catch (Exception ex) { throw new RuntimeException(ex); }\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"private static boolean isInFile(String fileName, String search) throws IOException {\n",
" try (FileInputStream fis = new FileInputStream(fileName)) {\n",
" int ch;\n",
" StringBuilder sb = new StringBuilder();\n",
" while ((ch = fis.read()) != -1 && sb.length() < search.length()) {\n",
" sb.append((char) ch);\n",
" }\n",
"\n",
" do {\n",
" if (sb.toString().equals(search))\n",
" return true;\n",
" sb.deleteCharAt(0);\n",
" sb.append((char) ch); \n",
" } while ((ch = fis.read()) != -1);\n",
" } catch (IOException e) {\n",
" throw new RuntimeException(e);\n",
" }\n",
" return false;\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try {\n",
" //#3\n",
" // Here we can use Scanner to ask user for a word. \n",
" // I decided to use it as a constant, because \n",
" // it's enough to show the flexibility of a searching method.\n",
" //\n",
" // Scanner sc = new Scanner(System.in);\n",
" // String WORD_TO_SEARCH = sc.next();\n",
" // sc.close();\n",
" System.out.println(\"Check result in file_2 for third task is: \" + isInFile(fileNames[2], WORD_TO_SEARCH));\n",
"}\n",
"catch (Exception ex) { throw new RuntimeException(ex); }\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try {\n",
" //#4\n",
" System.out.println(\"And here's the result of the fourth task. Go ahead and check it!\");\n",
" String[] result = searchMatch(fileNames, WORD_TO_SEARCH);\n",
" for (int i = 0; i < result.length; i++)\n",
" if (result[i] != null)\n",
" System.out.println(\"File '\" + result[i] + \"' contains the searched word '\" + WORD_TO_SEARCH + \"'\");\n",
"}\n",
"catch (Exception ex) { throw new RuntimeException(ex); }\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"int[] ar0 = {1,2,3,4,5,6,7,8,0,8,7,6,5,4,3};\n",
"final int DIGIT_BOUND = 48;\n",
"\n",
"FileOutputStream fos = new FileOutputStream(\"save.out\");\n",
"fos.write('[');\n",
"for (int i = 0; i < ar0.length; i++) {\n",
" fos.write(DIGIT_BOUND + ar0[i]);\n",
" if (i < ar0.length - 1) fos.write(',');\n",
"}\n",
"fos.write(']');\n",
"fos.flush();\n",
"fos.close();"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4, 5, 6, 7, 8, 0, 8, 7, 6, 5, 4, 3]\n"
]
}
],
"source": [
"int[] ar00 = new int[15];\n",
"final int DIGIT_BOUND = 48;\n",
"\n",
"FileInputStream fis = new FileInputStream(\"save.out\");\n",
"fis.read(); // '['\n",
"for (int i = 0; i < ar00.length; i++) {\n",
" ar00[i] = fis.read() - DIGIT_BOUND;\n",
" fis.read(); // ','\n",
"}\n",
"fis.close();\n",
"\n",
"System.out.println(Arrays.toString(ar00));"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"// assuming 0 is divider\n",
"int[] ar1 = {1,2,3,4,5,6,7,8,0,8,7,6,5,4,3};\n",
"\n",
"FileOutputStream fos = new FileOutputStream(\"save0.out\");\n",
"for (int i = 0; i < ar0.length; i++) {\n",
" fos.write(ar0[i]);\n",
" fos.write(0);\n",
"}\n",
"fos.flush();\n",
"fos.close();"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"int[] ar10 = new int[15];\n",
"// assuming 0 is divider\n",
"\n",
"FileInputStream fis = new FileInputStream(\"save0.out\");\n",
"int b;\n",
"int i = 0;\n",
"while ((b = fis.read()) != -1) {\n",
" if (b != 0) {\n",
" ar10[i++] = b;\n",
" }\n",
"}\n",
"fis.close();\n",
"\n",
"System.out.println(Arrays.toString(ar10));"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"int[] ar2 = {0,1,2,3,0,1,2,3,0};\n",
"\n",
"FileOutputStream fos = new FileOutputStream(\"save1.out\");\n",
"for (int b = 0; b < 3; b++) { // write to 3 bytes\n",
" byte wr = 0;\n",
" for (int v = 0; v < 3; v++) { // write by 3 values in each\n",
" wr += (byte) (ar2[3 * b + v] << (v * 2));\n",
" }\n",
" fos.write(wr);\n",
"}\n",
"fos.flush();\n",
"fos.close();"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"int[] ar20 = new int[9];\n",
"\n",
"FileInputStream fis = new FileInputStream(\"save1.out\");\n",
"int b;\n",
"int i = 0;\n",
"while ((b = fis.read()) != -1) {\n",
" for (int v = 0; v < 3; ++v) { // 3 values of four possible\n",
" ar20[i++] = b >> (v * 2) & 0x3;\n",
" }\n",
"}\n",
"fis.close();\n",
"\n",
"System.out.println(Arrays.toString(ar20));"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"FileInputStream fis = new FileInputStream(\"Main.java\");\n",
"int i;\n",
"char what = ',';\n",
"char to = '!';\n",
"FileOutputStream fos = new FileOutputStream(\"Main.java.new\");\n",
"\n",
"while ((i = fis.read()) != -1) {\n",
" if (i == what)\n",
" fos.write(to);\n",
" else\n",
" fos.write(i);\n",
"}\n",
"\n",
"fos.close();\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"String search = \"Hello\";\n",
"String l = \"Goodbye\";\n",
"FileInputStream fis = new FileInputStream(\"Main.java\");\n",
"FileOutputStream fos = new FileOutputStream(\"Main.java.new\");\n",
" \n",
"int ch;\n",
"StringBuilder sb = new StringBuilder();\n",
"while ((ch = fis.read()) != -1) {\n",
" sb.append((char) ch);\n",
" if (sb.length() == search.length()) {\n",
" if (sb.toString().equals(search)) {\n",
" fos.write(l.getBytes());\n",
" sb.delete(0, search.length());\n",
" } else {\n",
" fos.write(sb.charAt(0));\n",
" sb.deleteCharAt(0);\n",
" }\n",
" }\n",
"}\n",
"fos.write(sb.toString().getBytes());"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"./file_7.txt\n",
"./file_6.txt\n",
"./file_4.txt\n",
"./file_5.txt\n",
"./file_1.txt\n",
"./.DS_Store\n",
"./save1.out\n",
"./save0.out\n",
"./file_0.txt\n",
"./Icon\n",
"./file_2.txt\n",
"./file_3.txt\n",
"./FILE_OUT.txt\n",
"./Sample.zip\n",
"./Makefile\n",
"./notebook.ipynb\n",
"./Main.java.new\n",
"./Main.java\n",
"./save.out\n",
"./test.txt\n",
"./Main.class\n",
"./cat.txt\n",
"./file_8.txt\n",
"./bytes.txt\n",
"./file_9.txt\n",
"./sources-draft.iml\n"
]
}
],
"source": [
"int count = 0;\n",
"File path = new File( new File(\".\").getPath() );\n",
"File[] dir = path.listFiles();\n",
"for (int i = 0; i < dir.length; i++) {\n",
" if (dir[i].isDirectory()) continue;\n",
" System.out.println(dir[i]);\n",
"}\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"void printContents(String path) throws IOException {\n",
" int count = 0;\n",
" File fullPath = new File(new File(path).getCanonicalPath() );\n",
" File[] dir = fullPath.listFiles();\n",
" for (int i = 0; i < dir.length; i++) {\n",
" if (dir[i].isDirectory()) printContents(dir[i].toString());\n",
" System.out.println(dir[i]);\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"printContents(\".\");"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"import java.util.stream.Stream;\n",
"import java.nio.file.DirectoryStream;\n",
"import java.nio.file.Paths;\n",
"\n",
"import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;\n"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"Files.createDirectory(Path.of(\"./bkp\"));\n",
"\n",
"DirectoryStream<Path> dir = Files.newDirectoryStream(Path.of(\".\"));\n",
"for (Path file : dir) {\n",
" if (Files.isDirectory(file)) continue;\n",
" Files.copy(file, Path.of(\"./bkp/\" + file.toString()));\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"No file with name 'a.txt'"
]
}
],
"source": [
"String[] a = {\"Main.java\", \"a.txt\"};\n",
" \n",
"for (String fileName : a) {\n",
" Path file = Path.of(fileName);\n",
" if (Files.exists(file)) {\n",
" Files.move(file, Paths.get(\"pre_\" + file), REPLACE_EXISTING);\n",
" } else {\n",
" System.out.printf(\"No file with name '%s'\", fileName);\n",
" }\n",
"}"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Java",
"language": "java",
"name": "java"
},
"language_info": {
"codemirror_mode": "java",
"file_extension": ".jshell",
"mimetype": "text/x-java-source",
"name": "java",
"pygments_lexer": "java",
"version": "11.0.15.1+2-LTS"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}