控制台IO #

一、标准输出 #

1.1 print和println #

julia
print("Hello")
print(" ")
print("World")
println()
println("Hello, Julia!")

1.2 printstyled #

julia
printstyled("Error!", color=:red, bold=true)
printstyled("Warning!", color=:yellow)
printstyled("Success!", color=:green)

1.3 show #

julia
show(stdout, "Hello")
show(stdout, [1, 2, 3])

1.4 display #

julia
display([1, 2, 3])
display(Dict(:a => 1, :b => 2))

二、格式化输出 #

2.1 Printf #

julia
using Printf

@printf("Integer: %d\n", 42)
@printf("Float: %.2f\n", 3.14159)
@printf("String: %s\n", "Julia")
@printf("Width: %10d\n", 42)
@printf("Left: %-10d|\n", 42)

2.2 格式化字符串 #

julia
using Printf

s = @sprintf("Value: %.2f", 3.14159)

2.3 格式说明符 #

说明符 描述
%d 整数
%f 浮点数
%.Nf N位小数
%s 字符串
%x 十六进制
%o 八进制
%e 科学计数法

三、标准输入 #

3.1 readline #

julia
print("Enter your name: ")
name = readline()
println("Hello, $name!")

3.2 读取数字 #

julia
print("Enter a number: ")
num = parse(Int, readline())
println("You entered: $num")

3.3 读取多行 #

julia
println("Enter lines (empty line to stop):")
lines = String[]
while true
    line = readline()
    isempty(line) && break
    push!(lines, line)
end
println("You entered $(length(lines)) lines")

3.4 read #

julia
print("Enter a character: ")
c = read(stdin, Char)
println("You entered: $c")

四、标准错误 #

4.1 stderr #

julia
println(stderr, "This is an error message")
print(stderr, "Error: ")
println(stderr, "Something went wrong")

4.2 @warn, @info, @error #

julia
@info "Information message"
@warn "Warning message"
@error "Error message"

五、实践练习 #

5.1 练习1:交互式计算器 #

julia
function interactive_calculator()
    println("Simple Calculator (type 'quit' to exit)")
    
    while true
        print("\nEnter expression (e.g., 1 + 2): ")
        input = readline()
        
        lowercase(input) == "quit" && break
        
        try
            parts = split(input)
            if length(parts) == 3
                a = parse(Float64, parts[1])
                op = parts[2]
                b = parse(Float64, parts[3])
                
                result = if op == "+"
                    a + b
                elseif op == "-"
                    a - b
                elseif op == "*"
                    a * b
                elseif op == "/"
                    b == 0 ? error("Division by zero") : a / b
                else
                    error("Unknown operator")
                end
                
                println("Result: $result")
            else
                println("Invalid format. Use: number operator number")
            end
        catch e
            println("Error: $e")
        end
    end
    
    println("Goodbye!")
end

5.2 练习2:进度显示 #

julia
function show_progress(total)
    for i in 1:total
        percent = round(Int, i / total * 100)
        bar_length = round(Int, i / total * 50)
        bar = "█"^bar_length * " "^(50 - bar_length)
        print("\r[$bar] $percent%")
        sleep(0.05)
    end
    println()
end

show_progress(100)

5.3 练习3:表格输出 #

julia
function print_table(headers, rows)
    widths = [maximum(length.(col)) for col in eachcol(hcat([[string(x) for x in row] for row in [headers, rows...]]))]
    
    function print_row(row, widths)
        println("| " * join([lpad(string(x), w) for (x, w) in zip(row, widths)], " | ") * " |")
    end
    
    print_row(headers, widths)
    println("|" * join(["-"^(w + 2) for w in widths], "|") * "|")
    for row in rows
        print_row(row, widths)
    end
end

headers = ["Name", "Age", "City"]
rows = [["Alice", 25, "NYC"], ["Bob", 30, "LA"]]
print_table(headers, rows)

六、总结 #

本章我们学习了:

  1. 标准输出:print、println、printstyled
  2. 格式化输出:Printf宏
  3. 标准输入:readline、read
  4. 标准错误:stderr和日志宏

接下来让我们学习Julia的文件操作!

最后更新:2026-03-27