DEV Community

Stacy Roll
Stacy Roll

Posted on

Let's build a Dynamic Calculator! 📟

Add a keyboard mannager for users inputs:

cargo add k_board

Add calculator logic inside the program:

use k_board::{Keyboard, Keys};
use std::io;

fn main() {
    let mut result: f64 = 0.0;
    let first: f64 = get_number("first");
    let second: f64 = get_number("second");
    let operation: i8 = get_operation();
    match operation {
        0 => result = first + second,
        1 => result = first - second,
        2 => result = first * second,
        3 => {
            if second != 0.0 {
                result = first / second
            }
        }
        _ => {}
    }
    println!("The result is: {}", result);
}

fn get_number(position: &str) -> f64 {
    let mut input: String = String::new();
    println!("Enter the {} number: ", position);
    io::stdin().read_line(&mut input).expect("Error");
    let number: f64 = match input.trim().parse() {
        Ok(number) => number,
        Err(_) => get_number(position),
    };
    number
}

fn get_operation() -> i8 {
    let mut operation: i8 = 0;
    menu(&mut operation, 0);
    for key in Keyboard::new() {
        match key {
            Keys::Up => menu(&mut operation, -1),
            Keys::Down => menu(&mut operation, 1),
            Keys::Enter => break,
            _ => {}
        }
    }
    operation
}

fn menu(operation: &mut i8, selection: i8) {
    std::process::Command::new("clear").status().unwrap();
    if *operation > 0 || *operation < 3 {
        *operation += selection;
    }
    let mut op = vec![' ', ' ', ' ', ' '];
    for i in 0..4 {
        if i == *operation {
            op[i as usize] = '*';
        }
    }
    println!(
        "{} Add\n{} Subtract\n{} Multiply\n{} Divide",
        op[0], op[1], op[2], op[3]
    );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)