全面的程式語言代碼參考
深入了解多種程式語言的實用範例與應用
關鍵要點
- 多樣化的程式語言範例涵蓋基礎與進階應用
- 每種語言均提供實用的「Hello, World!」及功能性程式碼
- 豐富的學習資源與參考鏈接助您深入掌握
程式語言概覽
在現代軟體開發中,掌握多種程式語言是提升技能的重要途徑。以下將介紹十種常見程式語言的基本範例,涵蓋從簡單輸出到函數定義、條件判斷、迴圈結構等多方面應用。
Python
基本範例
# Hello, World!
print("Hello, World!")
變數與輸出
name = "Tom"
age = 25
print(f"Hello, {name}! You are {age} years old.")
條件判斷
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
迴圈
for i in range(5):
print(i)
函數定義
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
JavaScript
基本範例
// Hello, World!
console.log("Hello, World!");
變數宣告
let name = "Tom";
const age = 25;
函數定義
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Bob"));
陣列操作
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => {
console.log(num);
});
物件操作
let person = {
name: "Tom",
age: 25,
sayHello() {
console.log(`Hello, I'm ${this.name}`);
}
};
person.sayHello();
Java
基本範例
// Hello, World!
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
變數與資料型態
String name = "Tom";
int age = 25;
System.out.println("Hello, " + name + "! You are " + age + " years old.");
條件判斷
if (age >= 18) {
System.out.println("You are an adult");
} else {
System.out.println("You are a minor");
}
迴圈
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
函數定義
public class Calculator {
public static void main(String[] args) {
int result = addNumbers(5, 3);
System.out.println("兩數相加的結果是: " + result);
}
public static int addNumbers(int a, int b) {
return a + b;
}
}
C++
基本範例
// Hello, World!
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
變數宣告與輸出
string name = "Tom";
int age = 25;
cout << "Hello, " << name << "! You are " << age << " years old." << endl;
條件判斷
if (age >= 18) {
cout << "You are an adult" << endl;
} else {
cout << "You are a minor" << endl;
}
迴圈
for(int i = 0; i < 5; i++) {
cout << i << " ";
}
函數定義
int addNumbers(int a, int b) {
return a + b;
}
int main() {
int result = addNumbers(5, 3);
cout << "兩數相加的結果是: " << result << endl;
return 0;
}
資料結構
int numbers[5] = {1, 2, 3, 4, 5};
for(int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
C#
基本範例
// Hello, World!
using System;
class Program {
static void Main() {
Console.WriteLine("Hello, World!");
}
}
變數宣告與輸出
string name = "Tom";
int age = 25;
Console.WriteLine($"Hello, {name}! You are {age} years old.");
條件判斷
if (age >= 18) {
Console.WriteLine("You are an adult");
} else {
Console.WriteLine("You are a minor");
}
迴圈
for(int i = 0; i < 5; i++) {
Console.WriteLine(i);
}
函數定義
static int AddNumbers(int a, int b) {
return a + b;
}
static void Main() {
int result = AddNumbers(5, 3);
Console.WriteLine($"兩數相加的結果是: {result}");
}
Go
基本範例
// Hello, World!
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
變數宣告與輸出
package main
import "fmt"
func main() {
name := "Tom"
age := 25
fmt.Printf("Hello, %s! You are %d years old.\n", name, age)
}
條件判斷
if age >= 18 {
fmt.Println("You are an adult")
} else {
fmt.Println("You are a minor")
}
迴圈
for i := 0; i < 5; i++ {
fmt.Println(i)
}
函數定義
func greet(name string) string {
return fmt.Sprintf("Hello, %s!", name)
}
func main() {
fmt.Println(greet("Alice"))
}
Ruby
基本範例
# Hello, World!
puts "Hello, World!"
變數宣告與輸出
name = "Tom"
age = 25
puts "Hello, #{name}! You are #{age} years old."
條件判斷
if age >= 18
puts "You are an adult"
else
puts "You are a minor"
end
迴圈
5.times do |i|
puts i
end
函數定義
def greet(name)
"Hello, #{name}!"
end
puts greet("Alice")
Rust
基本範例
// Hello, World!
fn main() {
println!("Hello, World!");
}
變數宣告與輸出
fn main() {
let name = "Tom";
let age = 25;
println!("Hello, {}! You are {} years old.", name, age);
}
條件判斷
fn main() {
let age = 25;
if age >= 18 {
println!("You are an adult");
} else {
println!("You are a minor");
}
}
迴圈
fn main() {
for i in 0..5 {
println!("{}", i);
}
}
函數定義
fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
fn main() {
println!("{}", greet("Alice"));
}
Swift
基本範例
// Hello, World!
import Swift
print("Hello, World!")
變數宣告與輸出
let name = "Tom"
let age = 25
print("Hello, \(name)! You are \(age) years old.")
條件判斷
if age >= 18 {
print("You are an adult")
} else {
print("You are a minor")
}
迴圈
for i in 0..<5 {
print(i)
}
函數定義
func greet(name: String) -> String {
return "Hello, \(name)!"
}
print(greet(name: "Alice"))
Kotlin
基本範例
// Hello, World!
fun main() {
println("Hello, World!")
}
變數宣告與輸出
fun main() {
val name = "Tom"
val age = 25
println("Hello, $name! You are $age years old.")
}
條件判斷
fun main() {
val age = 25
if (age >= 18) {
println("You are an adult")
} else {
println("You are a minor")
}
}
迴圈
fun main() {
for (i in 0 until 5) {
println(i)
}
}
函數定義
fun greet(name: String): String {
return "Hello, $name!"
}
fun main() {
println(greet("Alice"))
}
功能比較表
| 功能/語言 | Python | JavaScript | Java | C++ | C# | Go | Ruby | Rust | Swift | Kotlin |
|---|---|---|---|---|---|---|---|---|---|---|
| 語法簡潔性 | 高 | 中 | 中 | 中 | 中 | 高 | 高 | 中 | 高 | 高 |
| 主要應用領域 | 數據分析、AI、網頁開發 | 前端、後端開發 | 企業應用、Android開發 | 系統程式、遊戲開發 | Windows應用、遊戲開發 | 高效能應用、網路服務 | 網頁開發、腳本編寫 | 系統程式、嵌入式系統 | iOS、macOS應用 | Android開發、跨平台應用 |
| 學習曲線 | 平緩 | 平緩 | 陡峭 | 陡峭 | 中等 | 中等 | 平緩 | 中等 | 平緩 | 平緩 |
| 社群支援 | 廣泛 | 廣泛 | 廣泛 | 廣泛 | 廣泛 | 成長中 | 活躍 | 活躍 | 成長中 | 快速增長 |
進階應用示例
除了基本的語法和結構,進階應用能夠展示各種語言在實際開發中的強大功能。以下將提供一些進階範例,如資料庫連接、網路應用、物件導向設計等。
資料庫連接
Python 與 SQLite
import sqlite3
# 連接到 SQLite 資料庫
conn = sqlite3.connect('example.db')
c = conn.cursor()
# 創建表
c.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
# 插入資料
c.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice", 30))
# 確認修改
conn.commit()
# 查詢資料
c.execute("SELECT * FROM users")
print(c.fetchall())
# 關閉連接
conn.close()
JavaScript 與 Node.js 連接 MongoDB
// 安裝必要套件: npm install mongodb
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db('testdb');
const collection = database.collection('users');
// 插入文件
const doc = { name: "Bob", age: 25 };
const result = await collection.insertOne(doc);
console.log(`A document was inserted with the _id: ${result.insertedId}`);
// 查詢文件
const users = await collection.find().toArray();
console.log(users);
} finally {
await client.close();
}
}
run().catch(console.dir);
Java 與 MySQL 連接
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MySQLExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";
try {
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
// 創建表
String sql = "CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)";
stmt.executeUpdate(sql);
// 插入資料
sql = "INSERT INTO users (name, age) VALUES ('Charlie', 28)";
stmt.executeUpdate(sql);
// 查詢資料
sql = "SELECT * FROM users";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
System.out.println("ID: " + rs.getInt("id") +
", Name: " + rs.getString("name") +
", Age: " + rs.getInt("age"));
}
conn.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
物件導向設計
C++ 的物件導向範例
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {}
void introduce() {
cout << "Hello, I'm " << name << " and I'm " << age << " years old." << endl;
}
};
int main() {
Person p("Dave", 40);
p.introduce();
return 0;
}
Java 的物件導向範例
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void introduce() {
System.out.println("Hello, I'm " + name + " and I'm " + age + " years old.");
}
public static void main(String[] args) {
Person p = new Person("Eve", 35);
p.introduce();
}
}
高效學習資源
掌握多種程式語言需要豐富的學習資源與工具。以下是一些優質的線上資源,幫助您深入了解並實踐各種程式語言:
- Codecademy - 提供多種程式語言的互動課程
- freeCodeCamp - 免費程式設計學習平台
- GeeksforGeeks - 深入的編程教程與問題解答
- W3Schools - 網頁開發與前端技術教程
- Java Documentation - 官方Java文檔
- Rust Learn - Rust語言學習資源
- Kotlin Documentation - 官方Kotlin文檔
- Swift Documentation - 官方Swift文檔
線上編譯器與實驗環境
實際編寫與測試程式碼是學習的關鍵。以下是一些方便的線上編譯器與開發環境:
結論
掌握多種程式語言能夠大幅提升您的開發能力與職場競爭力。通過上述範例與進階應用,您可以深入了解每種語言的特點與應用場景。此外,利用豐富的線上資源與實驗環境,持續練習與學習,將有助於您快速成長為多語言的全能開發者。
參考資料
以下是一些有用的資源鏈接,供您進一步學習與參考:
Last updated January 23, 2025