2023年3月21日 星期二

GPT3 寫的程式

 很不幸,在公司的電腦有許多限制,讓我無法執行這些 GPT3 所寫的程式,故先放在這邊。以下程式都是 GPT3 寫的,我還沒有測試過。


import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import math

# 設定恆星位置
star_pos = np.array([0, 0, 0])

# 設定行星軌道參數
a = 2 # 長軸半徑
b = 1 # 短軸半徑
theta = np.linspace(0, 2 * np.pi, 200) # 軌道角度
x = a * np.cos(theta) # 軌道 x 座標
y = b * np.sin(theta) # 軌道 y 座標

# 計算行星位置
planet_pos = np.array([x, y, np.zeros(len(x))]).T
for i in range(len(planet_pos)):
phi = math.radians(10 * i) # 每次繞行一圈增加 10
rotation_matrix = np.array([[math.cos(phi), -math.sin(phi), 0],
[math.sin(phi), math.cos(phi), 0],
[0, 0, 1]])
planet_pos[i] = rotation_matrix.dot(planet_pos[i]) + star_pos

# 繪製圖形
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(planet_pos[:, 0], planet_pos[:, 1], planet_pos[:, 2])
ax.scatter(star_pos[0], star_pos[1], star_pos[2], c='r', marker='o')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()


===

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

import numpy as np


# 粒子運動軌跡數據

x = [1, 2, 3, 4, 5]

y = [2, 3, 4, 5, 6]

z = [1, 2, 3, 4, 5]


# 繪製三維圖形

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot(x, y, z)


# 設置圖形參數

ax.set_xlabel('X')

ax.set_ylabel('Y')

ax.set_zlabel('Z')


# 顯示圖形

plt.show()


===






2022年11月29日 星期二

下一偵預測程式碼

 # ==================================================

# 彩色版使用生成器
# 不知道為什麼,使用生成器,模型的訓練就不會結束。
# ^找出原因了,我訓練參數沒有按書上寫的設定。此程式目前看起來成功了。
def TMString():

global timeI
global minuteI

if (minuteI == 160 ):
minuteI = minuteI - 60
timeI = timeI + 1
minuteS = str(minuteI)
minute = minuteS[1:3]
else:
minuteS = str(minuteI)
minute = minuteS[1:3]

timeS = str(timeI)
time = timeS[1:3]
minuteI = minuteI + 1
return (time + minute)
##

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as img

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

import io
import imageio
from IPython.display import Image, display
from ipywidgets import widgets, Layout, HBox
import cv2

import os

pathList = ["DropletTestImg0_64/20220407/20220407",
"DropletTestImg0_64/20220408/20220408",
"DropletTestImg0_64/20220409/20220409",
"DropletTestImg0_64/20220410/20220410",
"DropletTestImg0_64/20220411/20220411",
"DropletTestImg0_64/20220412/20220412",
"DropletTestImg0_64/20220413/20220413",
"DropletTestImg0_64/20220414/20220414",
"DropletTestImg0_64/20220415/20220415",
"DropletTestImg0_64/20220416/20220416",
"DropletTestImg0_64/20220417/20220417",
"DropletTestImg0_64/20220418/20220418",
"DropletTestImg0_64/20220419/20220419",
"DropletTestImg0_64/20220420/20220420",
"DropletTestImg0_64/20220421/20220421",
"DropletTestImg0_64/20220422/20220422",
"DropletTestImg0_64/20220423/20220423",
"DropletTestImg0_64/20220424/20220424",
"DropletTestImg0_64/20220425/20220425",
"DropletTestImg0_64/20220426/20220426",
"DropletTestImg0_64/20220427/20220427",
"DropletTestImg0_64/20220428/20220428",
"DropletTestImg0_64/20220509/20220509",
"DropletTestImg0_64/20220510/20220510",
"DropletTestImg0_64/20220511/20220511",
"DropletTestImg0_64/20220516/20220516",
"DropletTestImg0_64/20220517/20220517",
"DropletTestImg0_64/20220518/20220518",
"DropletTestImg0_64/20220519/20220519",
"DropletTestImg0_64/20220617/20220617",
"DropletTestImg0_64/20220618/20220618",
"DropletTestImg0_64/20220619/20220619",
"DropletTestImg0_64/20220620/20220620",
"DropletTestImg0_64/20220621/20220621",
"DropletTestImg0_64/20220622/20220622",
"DropletTestImg0_64/20220623/20220623",
"DropletTestImg0_64/20220624/20220624",
"DropletTestImg0_64/20220625/20220625",
"DropletTestImg0_64/20220626/20220626",
"DropletTestImg0_64/20220627/20220627",
"DropletTestImg0_64/20220628/20220628",
"DropletTestImg0_64/20220629/20220629",
"DropletTestImg0_64/20220630/20220630",
"DropletTestImg0_64/20220701/20220701",
"DropletTestImg0_64/20220702/20220702",
"DropletTestImg0_64/20220703/20220703",
"DropletTestImg0_64/20220705/20220705",
"DropletTestImg0_64/20220706/20220706",
"DropletTestImg0_64/20220707/20220707",
"DropletTestImg0_64/20220709/20220709",
"DropletTestImg0_64/20220710/20220710",
"DropletTestImg0_64/20220711/20220711",
"DropletTestImg0_64/20220713/20220713",
"DropletTestImg0_64/20220714/20220714"]


pen = 900 # <每個資料夾內最多能提供的照片數
frameNumber = 19
# image = np.zeros((frameNumber+1, ImgSize, ImgSize, 3)) # < 原本希望彩色
# img = np.zeros((frameNumber+1,ImgSize,ImgSize))
add = -1

# 把能夠連續 20 張為 1 組的第 0 張照片路徑找出來。
FirstPhoto = [] # <用來存路徑的列表
for i in pathList:
add = -1
j = 0
k = - 1
timeI = 105 # <代表起始 點
minuteI = 100 # <代表起始 分
while j < pen:
path = f"{i}{TMString()}00_11.jpg"
if os.path.isfile(path):
k += 1
if k == 0:
picture0 = path
print(picture0)
else:
k = -1
j += 1
if k == frameNumber:
k = -1
add += 1
FirstPhoto.append(picture0)
print(f"來源資料夾 {path[51:59]},資料數:{add+1}")

np.random.shuffle(FirstPhoto) # <洗牌,這個洗牌的奇怪之處是沒有命名其他變數指向洗過牌的變數列表物件。
print(f"每筆訓練資料都是連續20張圖,共有{len(FirstPhoto)}組,並且已經打亂!")
print("FirstPhoto列表有每組資料的首張圖檔名!")


ImgSize = 64
image = np.zeros((frameNumber+1, ImgSize, ImgSize, 3))

def create_shifted_frames(data):
x = data[:, 0: data.shape[1] - 1, :, :, :]
y = data[:, 1: data.shape[1], :, :, :]
return x, y


def trn_gen():
addMax = 5
while True:
add = 0
image = np.zeros((20, ImgSize, ImgSize, 3))
dataset = np.zeros((addMax, 20, ImgSize, ImgSize, 3))
for i in range(int(len(FirstPhoto)*0.9)):
pathW = FirstPhoto[i]
pathI = pathW[:36]
pathF = pathW[40:]
global timeI
timeI = 100+int(pathW[36:38]) # <代表起始 點
global minuteI
minuteI = 100 + int(pathW[38:40]) # <代表起始 分
#print("訓練名單開頭照片", pathW)

for j in range(20):
path = f"{pathI}{TMString()}{pathF}"
image[j, :, :, :] = img.imread(path)

# while add < addMax:
dataset[add, :, :, :, :] = image
add += 1

if add == addMax:
dataset = dataset / 255
x_train, y_train = create_shifted_frames(dataset)
add = 0
#print("x_train.shape", x_train.shape)
yield (x_train, y_train)


def val_gen():
addMax = 1
while True:
add = 0
image = np.zeros((20, ImgSize, ImgSize, 3))
dataset = np.zeros((addMax, 20, ImgSize, ImgSize, 3))
for i in range(int(len(FirstPhoto)*0.9), len(FirstPhoto)):
pathW = FirstPhoto[i]
pathI = pathW[:36]
pathF = pathW[40:]
global timeI
timeI = 100+int(pathW[36:38]) # <代表起始 點
global minuteI
minuteI = 100 + int(pathW[38:40]) # <代表起始 分
#print("驗證名單開頭照片", pathW)

for j in range(20):
path = f"{pathI}{TMString()}{pathF}"
image[j, :, :, :] = img.imread(path)

# while add < addMax:
dataset[add, :, :, :, :] = image
add += 1

if add == addMax:
dataset = dataset / 255
x_val, y_val = create_shifted_frames(dataset)
add = 0
#print("x_val.shape", x_val.shape)
yield (x_val, y_val)


# =============================================================

# 建構模型
print("準備建模")
inp = layers.Input(shape=(None, ImgSize, ImgSize, 3)) # 因為使用生成器了,所以輸入形狀得先自己訂好。

# inp = layers.Input(shape=(None, *x_train.shape[2:]))
x = layers.ConvLSTM2D(
filters=78,
kernel_size=(5, 5),
padding="same",
return_sequences=True,
activation="relu",
)(inp)
x = layers.BatchNormalization()(x)
x = layers.ConvLSTM2D(
filters=78,
kernel_size=(3, 3),
padding="same",
return_sequences=True,
activation="relu",
)(x)
x = layers.BatchNormalization()(x)
x = layers.ConvLSTM2D(
filters=78,
kernel_size=(1, 1),
padding="same",
return_sequences=True,
activation="relu",
)(x)
x = layers.Conv3D(
filters=3, kernel_size=(3, 3, 3), activation="sigmoid", padding="same"
)(x)

# Next, we will build the complete model and compile it.
model = keras.models.Model(inp, x)

model.compile(
loss=keras.losses.binary_crossentropy, optimizer=keras.optimizers.Adam(),
)
print("編譯完成")

# Define some callbacks to improve training.
early_stopping = keras.callbacks.EarlyStopping(monitor="val_loss", patience=10)
reduce_lr = keras.callbacks.ReduceLROnPlateau(monitor="val_loss", patience=5)

# Define modifiable training hyperparameters.
epochs = 20
# batch_size = 5

# Fit the model to the training data.
print("準備訓練")
model.fit(
trn_gen(),
steps_per_epoch=313,
validation_data=val_gen(),
validation_steps=174,
callbacks=[early_stopping, reduce_lr],
epochs=epochs
)
print("存檔")
model.save('AllSkyColor_01.h5')

# from google.colab import files
# files.download('conv_lstm_AllSkyGray_01.h5')

2022年6月27日 星期一

python 的時間進位程式

因為要處理以日期為名稱的檔案,故寫了一個時間進位的函數,目前我的工作只需要分與時的進位, 在函數中一開始用整數處理,然後變成字串方便我取我要的部份,最後回傳字串。因為這個部落格我也沒在經營了,也沒什麼人來,故不解釋這個程式的邏輯了。

timeI = 114
minuteI = 100


def TMString(): # <以下是時與分的處理函數
global timeI
global minuteI

minuteI = minuteI + 1
if (minuteI == 160 ):
minuteI = minuteI - 60
timeI = timeI + 1
minuteS = str(minuteI)
minute = minuteS[1:3]
else:
minuteS = str(minuteI)
minute = minuteS[1:3]

timeS = str(timeI)
time = timeS[1:3]
return (time + minute)

for i in range(120):
print(TMString())

執行結果

1401
1402
1403
1404
1405
1406
以下略~~



2022年5月29日 星期日

PYTHON GS100

 

# 計數
import pygame
import sys

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)


def main():
pygame.init()
pygame.display.set_caption("first Pygame")
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 80)
tmr = 0

while True:
tmr = tmr + 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
txt = font.render(str(tmr), True, WHITE)
screen.fill(BLACK)
screen.blit(txt, [300, 200])
pygame.display.update()
clock.tick(10)


if __name__ == '__main__':
main()


PYTHON GS001

 

# 入門篇的 4 
import calendar
import datetime

# 4-2

# print(calendar.month(2022,6))
# print(calendar.isleap(2024))

# # 4-3

# print(datetime.date.today())
# print(datetime.date.fromisocalendar(2011, 5, 3))
# print(datetime.datetime.now())

# d = datetime.datetime.now()
# print(d.hour)
# print(d.minute)
# print(d.second)
# # ^ 所以這邊是產了一個名為 d datetime.datetime.now() 物件嗎?
#
# dd = datetime
# print(dd.datetime.now().hour)
# print(dd.datetime.now().minute)
# print(dd.datetime.now().second)
# # ^ 看來我猜得沒錯。

today = datetime.date.today()
birth = datetime.date(1982, 4, 16)
print(today - birth)

# 4-4


2022年5月27日 星期五

PYTHON GS000基本練習

 

# 入門篇基礎
import calendar

# --在 pycharm 上的快捷鍵--
# 範圍選取:[shift]+[上、下、左、右]
# 註解或反註解:[ctrl]+[/] (可搭配範圍選取)
# 整列程式碼上下移動:[ctrl]+[shift]+[上、下] (可搭配範圍選取)
# 執行程式:[shift]+[F10]

"""
多行註解
行1
行2
"""

#2-3
# print(calendar.month(2022, 5))
# ^印出五月的月曆
# print(calendar.prcal(2022))
# ^印出2022年的月曆

# 2-6
# print("輸入名字~~")
# name = input()
# print(f"name:{name}")
# print(input())


# 3-1

# a = ("AB" + "CD") * 2
# print(a*2)
# ^ 字串能相加也能乘整數,但不能相減,也不能除數字。

# 3-2
# card = []
# card.append(1)
# card.append(2)
# card.append("")
# print(card)
# # ^可後先設定空白列表,再使用 .append() 增加元素。
# enemy = ["史萊姆", "骷髏士兵", "魔法師"]
# print(enemy)
# enemy.append("哥布林")
# print(enemy)

# 3-3
# if False:
# print("Hei Jia-Jia")
# ^除了 True False 外,還有運算子 ==, !=, >, <, >=, <=

# life = 0
# if life > 0:
# print("活著~~")
# else:
# print("死了~~")

# 3-4

# for i in range(10):
# print(i)

# for hei in range(10,-1,-3):
# print(hei)
# ^ 10 -1 ,每次加 -3

# hei = 1
# hej = 10
# while hei < hej:
# print(f"{hei} < {hej}")
# hei +=1
# if hei ==5:
# print("要中斷了!")
# break

# 3-5

# def fun1():
# print("執行了函數fun1")


# fun()

# def fun2():
# fun1()
# print("執行了函數fun2")
# ^函數可以呼叫其他函數。

# fun2()

# def fun3(hei):
# print("執行了函數fun3")
# if hei <10:
# hei +=2
# fun3(hei)
# ^函數也可以自己呼叫自己,但要設好條件,不然會跑不完。

# hei = 1
# fun3(hei)

# def fun4(hei,jia):
# return hei + jia
# ^ 有回傳值的函數。


# print(fun4(1, 10))
# print(fun4("", "嘉嘉"))
# ^在這個例子中,送入的參數可以是文字,也可以是數字。

def fun5():
return "黑嘉嘉是我老婆!"
# ^沒有給參數,也可以有回傳值。

print(fun5())

2022年5月21日 星期六

列出某數字以下的所有質數

 這應該是我第三次做這個練習了,每次都用不同的語言,這次是用 C# ,寫起來比 python 方便,據說 Fortran 做數值運算比其他語言有效率,或許可以試看看它有多快。

using System;

namespace PrimeNumber

{

    class Program

    {

        static void Main(string[] args)

        {

            bool u;

            int sum = 0;

            for (int hei = 5; hei < 1000000000; hei += 2)

            {

                u = true;

                for (int hej = 3; hej <= (hei / 2); hej += 2)

                {

                    if (hei % hej == 0)

                    {

                        u = false;

                        break;

                    }

                }

                if (u)

                {

                    Console.Write(hei + " ");

                    sum++;

                }

            }

        }

    }

}





2021年11月28日 星期日

UNITY 設計遊戲雜記

 這篇不是教學,只是記錄我找到的網頁和資訊,未來相同的資訊、心得都會放在這一篇。

最一開始操作 UNITY 遇到的問題是 importing assets 非常慢,問了我買的書的作者,才知道是專案名稱用中文的關係,只要改成英文就好了,預計未來的 UNITY 中文版本會改善這一塊。

然後在此之前,我不知道 C# 的變數可以用中文命名,這點很特別。程式碼的部份,因為我有學過JAVA 並有物件導向的觀念,所以看到書中的範例倒是不會怕。順便請我朋友 Elton 幫我複習了泛型類別的觀念。

成功完成一個範例後,我考慮到的是遊戲中的模型要用個軟體製作,如果用 Blander 做模型,模型可以除了可以用在 UNITY 上,也可以用在 MMD 上,又或者許多用在 MMD 的模型是用 Blander 製作的,而且免費放在網路上給大家用,雖然可能不能用於商業,但練習時總是可以拿來試吧?

https://forum.gamer.com.tw/C.php?bsn=60610&snA=276

2021年9月2日 星期四

JAVA Package 練習

Package 相關類別的集合,這在程式越來越大時,不同的 Package 即使取了相同的變數或方法的名稱也沒有關係,因為 JAVA 可以由 Package 知道我們究竟是指哪一個變數或方法。接下來的範例是主程式引用了 NPC Package,而 NPC Package 的位置就設在 project 下的 src 資料夾中,即在 src 資料夾中設置一個 NPC 資料夾,而 NPC 資料夾內就是 NPC 的相關類別了。

父類別 NPC 共同特徵與方法:下面三行的抽象方法有提醒的功用,其子類別中必須覆寫,不然會出錯。
package NPC;

public abstract class Commn {
public String name, line;

public Commn(String name, String line){
this.name = name;
this.line = line;
}

public abstract void position();
public abstract void say();
public abstract void doing();

}
子類別之行人:
package NPC;

public class Walker extends Commn {

public Walker(String name, String line) {
super(name,line);
this.line = line;
}

public void position(){
System.out.println("【到處亂走!】");
}
public void say(){
System.out.println("台詞:" + line);
}
public void doing(){
System.out.println("== NPC" + name + " 的狀態! ==");
position();
say();
}
}
子類別之商人:
package NPC;

public class Merchant extends Commn{
public Merchant(String name, String line) {
super(name,line);
this.line = line;
}

public void position(){
System.out.println("【停在原地,不移動!】");
}
public void say(){
System.out.println("台詞:" + line);
}
public void doing(){
System.out.println("== NPC" + name + " 的狀態! ==");
position();
say();
}
}
不在 NPC package 中的子類別幽靈:故意測試看看這樣能不能繼承,答案是可以,但要引入。

import NPC.Commn; // 因為此類別不在 NPC 資類夾下,但用到了其中的類別,故需引入。

public class Ghost extends Commn {

public Ghost(String name, String line) {
super(name,line);
this.line = line;
}

public void position(){
System.out.println("【若隱若現的亂飄浮!】");
}
public void say(){
System.out.println("台詞:" + line);
}
public void doing(){
System.out.println("== NPC" + name + " 的狀態! ==");
position();
say();
}
}
主程式:
// 這個程式在試驗 package 的引入。
import NPC.*; // 引入 NPC package 下的所有類別。

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

// 創造各種 NPC,給名字與台詞!
Walker luna = new Walker("露娜", "今晚的月亮(我)很美吧?");
Merchant troy = new Merchant("特洛伊","快來買喔!這些武器都有 CAS 國家認證喔!");
Ghost kate = new Ghost("凱特","我死得好慘啊!");

// 使用各個 NPC doing 方法。
luna.doing();
System.out.println();

troy.doing();
System.out.println();

kate.doing();
System.out.println();
}
}
結果:
== NPC露娜 的狀態! ==
【到處亂走!】
台詞:今晚的月亮(我)很美吧?

== NPC特洛伊 的狀態! ==
【停在原地,不移動!】
台詞:快來買喔!這些武器都有 CAS 國家認證喔!

== NPC凱特 的狀態! ==
【若隱若現的亂飄浮!】
台詞:我死得好慘啊!


Process finished with exit code 0
這可能是最後一個會放上來的 JAVA 練習了,因為書看完了,雖然還有另外買一本,但接下目標是實作了,之後放上來的應該只有成果,不會再有程式碼了。


2021年8月30日 星期一

JAVA 例外處理-02 各種例外

  本程式在 try 區的程式碼只有三種可能會出現的例外,除以 0 、陣列溢位、使用方法的輸入參數不符、物件為 null 的情況,但我 catch 的部份還是多寫了儲存陣列元素型態不符,主要是為了日後查指令時方便。

  主程式中利用亂數決定要用陣列的哪個元素進行轉整數與相除運算,所以每一次出現的情況可能會不同,可能順利的完成,也可能產生例外。

  順道一題, catch 捕捉的物件名稱都一樣,只是型別不同,這跟多載(過載)相同, JAVA 會自動找合適的 catch 去捕捉物件。

程式碼:

public class Main {

// 類別方法,顯示例外訊息。
static void showErr(Exception ecp){
// Exception 是其它例外類別的父類別,所以可以用渣男寫法。
System.out.println("發生例外:" + ecp.getMessage());
//System.out.println("原因如下:");
}

public static void main(String[] args){
String[] text = { null, "44", "22", "11", "0",
"愛未未","恨已已","情深深","仇切切"};

try{ // 這邊寫可能會出現例外的程式碼,執行時若出現例外,會丟出例外物件給 catch

int i,ratio;
double r = Math.random()*10;
i = (int)(r);
System.out.println("亂數 r = " + r + ",小數捨去化為整數 i = " + i);
ratio = Integer.parseInt(text[i])/Integer.parseInt(text[i+1]);
System.out.println("參數比例 = "+ratio);
}
catch (ArithmeticException ecp){ // 捕捉【除以 0 的例外物件】。
showErr(ecp);
}
catch (ArrayIndexOutOfBoundsException ecp){ // 補捉【陣列溢位的例外物件】。
showErr(ecp);
}
catch (ArrayStoreException ecp){ // 捕捉【陣列儲存型態不符的例外物件】。
showErr(ecp);
}
catch (IllegalArgumentException ecp){
// 捕捉【使用的方法時,丟入的參數型態不同的例外物件】。
showErr(ecp);
}
catch (NullPointerException ecp) { // 捕捉【物件值為 null 的例外物件】。
showErr(ecp);
}

finally {
System.out.println("無論有沒有出現例外都會出現這一行!");
}

System.out.println("程式結束了!");

}
}

結果:

亂數 r = 5.228886020103869,小數捨去化為整數 i = 5
發生例外:For input string: "愛未未"
無論有沒有出現例外都會出現這一行!
程式結束了!

Process finished with exit code 0


我手邊的書還有丟出例外與自訂例外類別,暫且就先跳過。執行緒的部份,不想花時間改程式碼以避開著作權,所以決定練習不放上來。

2021年8月26日 星期四

JAVA 例外處理-01 try、catch、finally

例外處理的目的是為了避免程式崩潰,可以處理的例外有數學運算產生的,例如除以 0 、陣列索引在設定之外產生的、儲存陣列元素的型態不符產的、呼叫方法時,參數型態不同產生的、物件值為 null 產生的。

主程式 

public class Main {
public static void main(String[] args){
int i,j;
j=0;

try{
for (i = 2; i > -100; i--){
System.out.println("i= " + i + ",則 10/i = " + 10/i);
j=j+1;
}
// 如果沒有問題的話,程式會跑完迴圈,但這邊故意設了一個會除以 0 的情況,
// 該情況下會出錯,所以 catch 段的程式會執行,而且迴圈只會執行到此斷點。

System.out.println("出現此行,表示迴圈有跑完。");
// 實際上上面這一行不會出現在結果中,因為更前面已經出現例外了。
}
catch (ArithmeticException gg){
// 如果沒有例外,此區塊的程式碼不會被執行。
// 這邊的 gg 是送到 catch 方法裡面的 ArithmeticException 物件名稱,
// 名字可以隨便取。
System.out.println("例外說明:" + gg.getMessage());
// 展示 gg 物件得到的系統訊息。
System.out.println("例外原因:");
gg.printStackTrace();
// 有了上面這一行,出現例外的情況下,程式在執行完後會顯示程式呼叫的執行過程。
}
finally {
System.out.println("例外處理結束!迴圈共跑了 " + j + " 次。");
// 無論有沒有例外,上面這一行都會出現,表示此區程式一定會執行。
}

System.out.println("程式結束!");
}
}

結果:

i= 2,則 10/i = 5
i= 1,則 10/i = 10
例外說明:/ by zero
例外原因:
例外處理結束!迴圈共跑了 2 次。
程式結束!
java.lang.ArithmeticException: / by zero
	at Main.main(Main.java:8)

Process finished with exit code 0

其中 catch 的區塊可以有好幾個,最保險的方式是 try 區塊中的程式可能出現多少種例外,就有多少個 catch 來以確保程式不會崩潰。

2021年8月9日 星期一

c++ 判斷質數練習

  這個是小孩子的作業,其實我以前也用 python 做過類似的練習,那時是找出某個數字以下的所有質數,這次只是判斷一個數字。

======================================================================

#include <iostream>

// 這個程式功用是判斷數字是否為質數,在數字不大的情況下,這應該是簡單度與效率的最好比例了。 

using namespace std;

int main() { 


unsigned int a,b,c,d;

//cout << "請輸入數字 \n";

//cin >> a;

//a=2147483647;

a=4294967291;

b=1;

d= a/2;

c=1;

//cout << c << endl; 

while( b<d and c!=0) 

{

b=b+1;

c=a%b;

}

if(c==0){

cout << "不是質數!\n";

}

else{

cout << "質數!\n";

}

cout << "程式結束!";

    return 0; 

}

================================================================

以下是執行結果:

================================================================

請輸入數字

2147483647

質數!

=================================================================

我對質數有些好奇,但研究的人實在太多了,意即我投入時間研究大概也很難有新發現,但或許未來有空,還是可以探索一下的。所以留下 C++ 讀取與輸出文字檔的範例連結給未來的自己。

讀取:https://shengyu7697.github.io/cpp-read-text-file/

寫入:https://shengyu7697.github.io/cpp-write-text-file/

另外是質數研究的介紹:https://math.ntnu.edu.tw/~horng/letter/hpm16011.pdf

2021年7月22日 星期四

JAVA IO套件-05 讀檔與計算字數

  上次說要做的練習,讀取英文文字檔案並計數裡面出現的每一個字。

讀取類別:將文字檔案讀取後存成一維陣列,

import java.io.*;
public class ReadAsRaw {
String fileName;
int x;

// 字串讀取方法,就是英文單字,這個方法讀取存成一維陣列。
public String[] readStringFile(String fileName,int x) throws IOException{
this.fileName = fileName;
this.x = x;
int total = 0;
String[] stringArry = new String[x];
if( new File(fileName).exists()) {
BufferedReader fileString = new BufferedReader(new FileReader(fileName));
String line;
while ((line = fileString.readLine()) != null) {
String [] unit = line.split("\\W+"); // 用一個或多個非字母字元分割字串。
int size = unit.length;
for (int i = 0; i < size; i++){
stringArry[total + i] = unit[i];
}
total=total+size;
}
fileString.close();
}
else {
System.out.println("沒有 " + fileName + " 登!登!");
}
System.out.println("總字數:"+ total);
return stringArry;
}

}

字數計算類別:計數丟入的一維字串陣列中的每個單字出現次數。

import java.util.HashMap;

public class WordCount {

public void wordsCount(String[] sentence) {
// TODO Auto-generated method stub
String[] words = sentence ;//sentence.split("\\W+");
//新建一個 HashMap
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
int j = 0;
for (int i = 0; i < words.length; i++) {
if (hashMap.get(words[i]) == null) {
hashMap.put(words[i], 1); //如果 hashMap 中沒有那個單詞,設定值為 1
}
else { //如果 hashMap 中有這個單詞,則將該單詞的值加 1
hashMap.put(words[i], hashMap.get(words[i]) + 1);
j++;
}
}
System.out.println(" " + j + " 個不同的單字");
for(int i = 0; i < j; i++) {
System.out.println(words[i] + " ; " + hashMap.get(words[i]));
}

}
}

主程式:事先必須準備好一個文字檔於在專案資料夾中,例如 test.txt 。

public class Main {
public static void main(String[] args) throws Exception{

ReadAsRaw rW = new ReadAsRaw();
String nameString = "test.txt";
int guessTotal=313; // 猜總字數,可以大於等於,不能小於真實的字數。
String[] sArry = rW.readStringFile(nameString, guessTotal);

WordCount cW = new WordCount();
cW.wordsCount(sArry);
//System.out.println(cW.);
}
}

結果:因為太長,所我中間省略了,前面單字,後面數字。

總字數:313
有 137 個不同的單字
Quantum  ;  3
mechanics  ;  8
is  ;  4
a  ;  7
fundamental  ;  1

中間略

are  ;  2
restricted  ;  1
to  ;  7
discrete  ;  1

Process finished with exit code 0

  這邊用分號是因為試算表可以用分號當分隔符號,方便大家後續的操作。這個程式還有一件事情我沒有做,那就是排序。暫時懶得寫。最近有其他目標,下次練習應該是一段時間後了。

  為了完成這個練習,我所找到的程式參考來源:https://www.itread01.com/p/1432610.html;另外還有一個別人已經寫好,放在網路上分享的字數統計工具:https://blog.qqboxy.com/2016/06/english-word-analyze.html