BIT HELPER UOM

ads header

Search This Blog

Monday 10 June 2024

Assignment 2 PHP Answer | source code |UOM

 admin.php


<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "WaterBills";


$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error) {

  die("Connection failed: " . $conn->connect_error);

}


if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $id = $_POST['id'];

    $range_start = $_POST['range_start'];

    $range_end = $_POST['range_end'];

    $energy_charge = $_POST['energy_charge'];

    $fixed_charge = $_POST['fixed_charge'];


    $sql = "UPDATE water_bill_units SET range_start='$range_start', range_end='$range_end', energy_charge='$energy_charge', fixed_charge='$fixed_charge' WHERE id='$id'";


    if ($conn->query($sql) === TRUE) {

      echo "<div class='alert alert-success'>Record updated successfully</div>";

    } else {

      echo "<div class='alert alert-danger'>Error: " . $sql . "<br>" . $conn->error . "</div>";

    }

}


$result = $conn->query("SELECT * FROM water_bill_unit");


$conn->close();

?>


<!DOCTYPE html>

<html>

<head>

    <title>Admin Panel</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <style>

        body {

            background-color: #f8f9fa;

            padding-top: 20px;

        }

        .table th, .table td {

            vertical-align: middle;

            text-align: center;

        }

        .form-control {

            display: inline-block;

            width: auto;

        }

        .btn-primary {

            margin-top: 10px;

        }

        .card {

            margin-top: 20px;

            margin-bottom: 20px;

        }

    </style>

</head>

<body>


<div class="container">

    <h2 class="text-center">Admin Panel</h2>


    <table class="table table-sm table-bordered table-hover mt-4">

        <thead class="thead-light">

            <tr>

                <th>ID</th>

                <th>Range Start</th>

                <th>Range End</th>

                <th>Energy Charge</th>

                <th>Fixed Charge</th>

                <th>Action</th>

            </tr>

        </thead>

        <tbody>

        <?php while($row = $result->fetch_assoc()) { ?>

            <tr>

                <td><?php echo $row['id']; ?></td>

                <td><?php echo $row['range_start']; ?></td>

                <td><?php echo $row['range_end']; ?></td>

                <td><?php echo $row['energy_charge']; ?></td>

                <td><?php echo $row['fixed_charge']; ?></td>

                <td>

                    <form method="post" class="form-inline">

                        <input type="hidden" name="id" value="<?php echo $row['id']; ?>">

                        <input type="text" name="range_start" class="form-control mb-2 mr-sm-2" value="<?php echo $row['range_start']; ?>">

                        <input type="text" name="range_end" class="form-control mb-2 mr-sm-2" value="<?php echo $row['range_end']; ?>">

                        <input type="text" name="energy_charge" class="form-control mb-2 mr-sm-2" value="<?php echo $row['energy_charge']; ?>">

                        <input type="text" name="fixed_charge" class="form-control mb-2 mr-sm-2" value="<?php echo $row['fixed_charge']; ?>">

                        <input type="submit" class="btn btn-primary mb-2" value="Update">

                    </form>

                </td>

            </tr>

        <?php } ?>

        </tbody>

    </table>


    <div class="card mx-auto w-50">

        <div class="card-body">

            <h5 class="card-title">New Admin Registration</h5>

            <p class="card-text">Register a new admin for the system.</p>

            <center>

                <button class="btn btn-primary" onclick="location.href='adminregistration.php'">Register</button>

            </center>

        </div>

    </div>

</div>


</body>

</html>





adminlogin.php



<!DOCTYPE html>

<html>

<head>

    <title>ADMIN LOGIN</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <style>

        body {

            background-color: #f8f9fa;

            display: flex;

            justify-content: center;

            align-items: center;

            height: 100vh;

            margin: 0;

        }

        .login-container {

            background-color: white;

            padding: 30px;

            border-radius: 10px;

            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

            width: 100%;

            max-width: 400px;

        }

        h2 {

            margin-bottom: 20px;

        }

        .input-group {

            margin-bottom: 15px;

        }

        .input-group label {

            width: 100%;

        }

        .input-group input {

            width: 100%;

        }

        button {

            width: 100%;

        }

    </style>

</head>

<body>


<div class="login-container">

    <h2 class="text-center">Login</h2>

    <form method="post">

        <div class="input-group">

            <label for="username">Username:</label>

            <input type="text" name="username" class="form-control" required>

        </div>

        <div class="input-group">

            <label for="password">Password:</label>

            <input type="password" name="password" class="form-control" required>

        </div>

        <button type="submit" class="btn btn-primary">Login</button>

    </form> 

</div>


<div>

    <?php

    session_start();


    // Database configuration

    $servername = "localhost";

    $username = "root"; // Replace with your MySQL username

    $password = ""; // Replace with your MySQL password

    $dbname = "WaterBills"; // this is your database name


    // Create connection

    $conn = new mysqli($servername, $username, $password, $dbname);


    // Check connection

    if ($conn->connect_error) {

        die("Connection failed: " . $conn->connect_error);

    }


    // Function to check login credentials

    function check_login($conn, $username, $password) {

        $stmt = $conn->prepare("SELECT password FROM admin WHERE username = ?");

        $stmt->bind_param("s", $username);

        $stmt->execute();

        $stmt->store_result();


        $hashed_password = $password;

        

        if ($stmt->num_rows > 0) {

            $stmt->bind_result($hashed_password);

            $stmt->fetch();

            if (password_verify($password, $hashed_password)) {

                return true;

            }

        }

        return false;

    }


    // Handle login form submission

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $username = $_POST['username'];

        $password = $_POST['password'];

        // $password = password_hash($_POST['password'], PASSWORD_BCRYPT);

        

        if (check_login($conn, $username, $password)) {

            $_SESSION['username'] = $username;

            header("Location: admin.php");

            exit();

        } else {

            echo "<div class='alert alert-danger mt-3'>Invalid username or password.</div>";

        }

    }


    $conn->close();

    ?>

</div>


</body>

</html>



adminregistration.php



<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "WaterBills";


// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);


// Check connection

if ($conn->connect_error) {

  die("Connection failed: " . $conn->connect_error);

}


if(isset($_POST['submit'])){

    $username = $_POST['username'];

    $password = password_hash($_POST['password'], PASSWORD_BCRYPT);


    $sql = "INSERT INTO admin (username, password) VALUES ('$username', '$password')";


    if ($conn->query($sql) === TRUE) {

        header("Location: adminlogin.php");

    } else {

      echo "Error: " . $sql . "<br>" . $conn->error;

    }

}


$conn->close();

?>


<!DOCTYPE html>

<html>

<head>

    <title>Admin Register Form</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <style>

        body {

            background-color: #f8f9fa;

            display: flex;

            justify-content: center;

            align-items: center;

            height: 100vh;

            margin: 0;

        }

        .register-container {

            background-color: white;

            padding: 30px;

            border-radius: 10px;

            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

            width: 100%;

            max-width: 500px;

        }

        h2 {

            margin-bottom: 20px;

        }

    </style>

</head>

<body>


<div class="register-container">

    <h2 class="text-center">Admin Register</h2>

    <hr>

    <form action="" method="post">

        <div class="form-group row">

            <label for="username" class="col-sm-3 col-form-label"><b>Username:</b></label>

            <div class="col-sm-9">

                <input type="text" class="form-control" name="username" required>

            </div>

        </div>

        <div class="form-group row">

            <label for="password" class="col-sm-3 col-form-label"><b>Password:</b></label>

            <div class="col-sm-9">

                <input type="password" class="form-control" name="password" required>

            </div>

        </div>

        <button type="submit" class="btn btn-primary btn-block" name="submit">Register</button>

    </form>

</div>


</body>

</html>



dashboard.php


<!DOCTYPE html>

<html>

<head>

    <title>Dashboard</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <style>

        body {

            background-color: #f8f9fa;

            padding-top: 50px;

        }

        .container {

            max-width: 600px;

            background-color: white;

            padding: 30px;

            border-radius: 10px;

            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

        }

        h1 {

            margin-bottom: 20px;

        }

        footer {

            margin-top: 30px;

        }

        footer .card {

            margin: 10px 0;

            padding: 10px;

            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

        }

        .btn-primary {

            width: 100%;

        }

    </style>

</head>

<body>

<div class="container">

    <h1>Enter Water Usage</h1>

    <form method="post">

        <div class="form-group">

            <label for="month">Month:</label>

            <input type="month" class="form-control" name="month" required>

        </div>

        <div class="form-group">

            <label for="units">Units:</label>

            <input type="number" class="form-control" name="units" required>

        </div>

        <button type="submit" class="btn btn-primary" name="submit">Submit</button>

    </form>

</div>


<div class="container mt-5">

    <?php

    $servername = "localhost";

    $username = "root";

    $password = "";

    $dbname = "WaterBills";


    // Create connection

    $conn = new mysqli($servername, $username, $password, $dbname);


    // Check connection

    if ($conn->connect_error) {

        die("Connection failed: " . $conn->connect_error);

    }


    session_start();

    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {

        $customer_id = $_SESSION['customer_id'];

        $month = $_POST['month'];

        $units = $_POST['units'];


        // Calculate Bill

        $sql = "SELECT * FROM water_bill_unit ORDER BY range_start ASC";

        $result = $conn->query($sql);


        $total_energy_charge = 0;

        $fixed_charge = 0;

        $remaining_units = $units;


        while ($row = $result->fetch_assoc()) {

            if ($row['range_end'] === NULL || $remaining_units <= ($row['range_end'] - $row['range_start'] + 1)) {

                $total_energy_charge += $remaining_units * $row['energy_charge'];

                $fixed_charge = $row['fixed_charge'];

                break;

            } else {

                $units_in_range = $row['range_end'] - $row['range_start'] + 1;

                $total_energy_charge += $units_in_range * $row['energy_charge'];

                $fixed_charge = $row['fixed_charge'];

                $remaining_units -= $units_in_range;

            }

        }


        $total_charge = $total_energy_charge + $fixed_charge;

        $vat = $total_charge * 0.18;

        $final_bill = $total_charge + $vat;


        // Insert water usage and total charge into database

        $sql = "INSERT INTO water_usage (customer_id, month, units, total) VALUES ('$customer_id', '$month', '$units', '$final_bill')";

        if ($conn->query($sql) === TRUE) {

            echo "<div class='alert alert-success'>Usage and bill recorded successfully</div>";

        } else {

            echo "<div class='alert alert-danger'>Error: " . $sql . "<br>" . $conn->error . "</div>";

        }


        echo "<div class='alert alert-info'>";

        echo "Total Charge: " . $total_charge . " LKR<br>";

        echo "VAT (18%): " . $vat . " LKR<br>";

        echo "Final Bill: " . $final_bill . " LKR<br>";

        echo "</div>";

    }


    $conn->close();

    ?>

</div>


<footer>

    <div class="container">

        <div class="card text-center">

            <p><b>Water Usage History:</b></p>

            <button class="btn btn-secondary" onclick="location.href='history.php'">History</button>

        </div>

        <div class="card text-center">

            <form method="get" action="logout.php">

                <button class="btn btn-danger" type="submit">Logout</button>

            </form>

        </div>

    </div>

</footer>


<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</body>

</html>



history.php



<?php


$servername = "localhost";

$username = "root";

$password = "";

$dbname = "WaterBills";


// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);


// Check connection

if ($conn->connect_error) {

  die("Connection failed: " . $conn->connect_error);

}


session_start();

if (!isset($_SESSION['customer_id'])) {

    header("Location: login.php");

    exit();

}


$customer_id = $_SESSION['customer_id'];

$sql = "SELECT * FROM water_usage WHERE customer_id = ?";

$stmt = $conn->prepare($sql);

$stmt->bind_param("i", $customer_id);

$stmt->execute();

$result = $stmt->get_result();

?>


<!DOCTYPE html>

<html>

<head>

    <title>Usage History</title>

    <!-- Bootstrap CSS -->

    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom CSS -->

    <style>

        body {

            background-color: #f8f9fa;

            margin: 20px;

        }

        h1 {

            margin-bottom: 20px;

        }

        table {

            width: 80%;

            margin: 0 auto;

            border-collapse: collapse;

        }

        th, td {

            padding: 10px;

            text-align: center;

            border: 1px solid #dee2e6;

        }

        th {

            background-color: #007bff;

            color: white;

        }

        tr:nth-child(even) {

            background-color: #f2f2f2;

        }

        .btn-secondary {

            margin-top: 20px;

        }

    </style>

</head>

<body>

    <div class="container">

        <h1 class="text-center">Your Water Usage History</h1>

        <hr>

        <center>

        <table class="table table-striped table-bordered">

            <thead class="thead-dark">

                <tr>

                    <th>Month</th>

                    <th>Units Used</th>

                    <th>Amount</th>

                </tr>

            </thead>

            <tbody>

                <?php while ($row = $result->fetch_assoc()) { ?>

                    <tr>

                        <td><?php echo htmlspecialchars($row['month']); ?></td>

                        <td><?php echo htmlspecialchars($row['units']); ?></td>

                        <td><?php echo htmlspecialchars($row['total']); ?></td>

                    </tr>

                <?php } ?>

            </tbody>

        </table>

        <form method="get" action="dashboard.php">

            <button class="btn btn-secondary" type="submit">Back</button>

        </form>

        </center>

    </div>

</body>

</html>


<?php

$stmt->close();

$conn->close();

?>



login.php


<!DOCTYPE html>

<html>

<head>

    <title>LOGIN</title>

    <!-- Bootstrap CSS -->

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <style>

        body {

            background-color: #f8f9fa;

            display: flex;

            justify-content: center;

            align-items: center;

            height: 100vh;

        }

        .login-container {

            background-color: white;

            padding: 30px;

            border-radius: 10px;

            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

            width: 300px;

        }

        h2 {

            text-align: center;

            margin-bottom: 20px;

        }

        .input-group {

            margin-bottom: 15px;

        }

        .input-group label {

            width: 100%;

            margin-bottom: 5px;

        }

        .btn {

            width: 100%;

        }

    </style>

</head>

<body>

<div class="login-container">

    <h2>Login</h2>

    <form method="post">

        <div class="input-group">

            <label for="username">Username:</label>

            <input type="text" class="form-control" name="username" required>

        </div>

        <div class="input-group">

            <label for="password">Password:</label>

            <input type="password" class="form-control" name="password" required>

        </div>

        <button type="submit" class="btn btn-primary">Login</button>

    </form>

    <div>

        <?php

        $servername = "localhost";

        $username = "root";

        $password = "";

        $dbname = "WaterBills";


        $conn = new mysqli($servername, $username, $password, $dbname);


        if ($conn->connect_error) {

            die("Connection failed: " . $conn->connect_error);

        }


        session_start();


        if ($_SERVER["REQUEST_METHOD"] == "POST") {

            $username = $_POST['username'];

            $password = $_POST['password'];


            $sql = "SELECT * FROM customers WHERE username='$username'";

            $result = $conn->query($sql);


            if ($result->num_rows > 0) {

                $row = $result->fetch_assoc();

                if (password_verify($password, $row['password'])) {

                    $_SESSION['customer_id'] = $row['id'];

                    header("Location: dashboard.php");

                } else {

                    echo '<br><div class="alert alert-danger" role="alert">Invalid password</div>';

                }

            } else {

                echo '<br><div class="alert alert-danger" role="alert">No user found with that username</div>';

            }

        }


        $conn->close();

        ?>

    </div>

</div>


<!-- Bootstrap JS and dependencies -->

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</body>

</html>



logindashboard.php


<!DOCTYPE html>

<html>

<head>

    <title>Login Dashboard</title>

    <!-- Bootstrap CSS -->

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <style>

        body {

            background-color: #f8f9fa;

            display: flex;

            justify-content: center;

            align-items: center;

            height: 100vh;

        }

        .row {

            width: 80%;

        }

        .card {

            margin-bottom: 20px;

        }

        .card-body {

            text-align: center;

        }

        #center_button button {

            width: 100%;

        }

    </style>

</head>

<body>

<div class="row">

  <div class="col-md-6">

    <div class="card">

      <div class="card-body">

        <h5 class="card-title">Admin Panel</h5>

        <p class="card-text">Admin only Access - go to login page</p>

        <div id="center_button"><button class="btn btn-primary" onclick="location.href='adminlogin.php'">Admin</button></div>

      </div>

    </div>

  </div>

  <div class="col-md-6">

    <div class="card">

      <div class="card-body">

        <h5 class="card-title">Customer Registration</h5>

        <p class="card-text">New Registration and login page</p>

        <div id="center_button"><button class="btn btn-success" onclick="location.href='registration.php'">Register</button></div><br>

        <p class="card-text">Login page</p>

        <div id="center_button"><button class="btn btn-secondary" onclick="location.href='login.php'">Login</button></div>

      </div>

    </div>

  </div>

</div>


<!-- Bootstrap JS and dependencies -->

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</body>

</html>



logout.php


<?php

session_start();

session_unset();

session_destroy();

header("Location: login.php");

exit();

?>



registration.php


<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "WaterBills";


// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);


// Check connection

if ($conn->connect_error) {

  die("Connection failed: " . $conn->connect_error);

}


// if ($_SERVER["REQUEST_METHOD"] == "POST") 

if(isset($_POST['submit'])){

    $name = $_POST['name'];

    $address = $_POST['address'];

    $email = $_POST['email'];

    $water_bill_number = $_POST['water_bill_number'];

    $username = $_POST['username'];

    $password = password_hash($_POST['password'], PASSWORD_BCRYPT);


    $sql = "INSERT INTO customers (name, address, email, water_bill_number, username, password)

    VALUES ('$name', '$address', '$email', '$water_bill_number', '$username', '$password')";


    if ($conn->query($sql) === TRUE) {

        header("Location: login.php");

      // echo "New record created successfully";

      //echo '<script> location.replace("login.php")</script>';  


    } else {

      echo "Error: " . $sql . "<br>" . $conn->error;

    }

}


$conn->close();

?>


<!DOCTYPE html>

<html>

<head>

    <title>Register Form</title>

    <!-- Bootstrap CSS -->

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <style>

        body {

            background-color: #f8f9fa;

        }

        .form-container {

            margin-top: 50px;

            padding: 20px;

            background-color: #fff;

            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

            border-radius: 5px;

        }

    </style>

</head>

<body>


<div class="container">

    <div class="row justify-content-center">

        <div class="col-md-8">

            <div class="form-container">

                <h2 class="text-center mt-3">Register</h2>

                <hr>


                <form action="" method="post">

                    <div class="form-group">

                        <label for="name"><b>Name:</b></label>

                        <input type="text" name="name" required class="form-control">

                    </div>


                    <div class="form-group">

                        <label for="address"><b>Address:</b></label>

                        <input type="text" name="address" required class="form-control border-danger">

                    </div>


                    <div class="form-group">

                        <label for="email"><b>Email:</b></label>

                        <input type="email" name="email" required class="form-control border-danger">

                    </div>


                    <div class="form-group">

                        <label for="water_bill_number"><b>Water Bill Number:</b></label>

                        <input type="text" name="water_bill_number" required class="form-control border-danger">

                    </div>


                    <div class="form-group">

                        <label for="username"><b>Username:</b></label>

                        <input type="text" name="username" required class="form-control border-danger">

                    </div>


                    <div class="form-group">

                        <label for="password"><b>Password:</b></label>

                        <input type="password" name="password" required class="form-control border-danger">

                    </div>


                    <button type="submit" name="submit" class="btn btn-primary">Register</button>

                    <br><br>

                    <div id="center_button">

                        <button type="button" class="btn btn-secondary" onclick="location.href='login.php'">Login</button>

                    </div>

                </form>

            </div>

        </div>

    </div>

</div>


<!-- Bootstrap JS and dependencies -->

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</body>

</html>


Wednesday 15 May 2024

Activity 10 PHP

Saturday 17 February 2024

01.ITE 2132 - Object Oriented Programming 2023S1 [Week 02]

Wednesday 10 January 2024

Advantages of Modular Programming in Java




 A genuine issue is complicated and huge. On the off chance that a solid arrangement is created it represents these issues :

  • Challenging to compose, test and execute one major program
  • Changes after the eventual outcome is conveyed is near unimaginable
  • Upkeep of program undeniably challenging
  • One blunder can stop the entire framework


To defeat these issues, the arrangement ought to be partitioned into more modest parts called modules. The strategy of separating one major arrangement into more modest modules for simplicity of advancement, execution, adjustment and support is called particular procedure of programming or programming improvement.


The following are some of the benefits of modular programming:

  •  Facilitates faster development because each module can be developed in parallel 
  •  Allows for the reuse of modules 
  •  Facilitates faster and more robust testing 
  •  Easier debugging and maintenance of the entire program 
  •  Modules are smaller and less complex, making them simple to comprehend

Because there isn't one right way to identify software modules, it's a difficult task. Here are a few pointers to recognizing modules −

  • Assuming information is the main component of the framework, make modules that handle related information.
  • In the event that help given by the framework is different, separate the framework into utilitarian modules.
  • When in doubt, separate the framework into legitimate modules according to how you might interpret the framework during prerequisite get-together stage.

For coding, every module must be again separated into more modest modules for simplicity of programming. This should again be possible utilizing the three hints shared above, joined with explicit programming rules. For instance, for an item situated programming language like C++ and Java, each class with its information and techniques could shape a solitary module.


Methods

A Java technique is an assortment of proclamations that are gathered to play out an activity. At the point when you call the System.out.println() technique, for instance, the framework really executes a few assertions to show a message on the control center.

You will now understand how to use method abstraction in program design, how to create your own methods with or without return values, how to invoke a method with or without parameters.

Strategy definition comprises of a technique header and a strategy body.
modifier − It characterizes the entrance sort of the technique and it is discretionary to utilize.
returnType − Strategy might return a worth.

nameOfMethod: The method's name here. The technique signature comprises of the strategy name and the boundary list.
Boundary Rundown − The rundown of boundaries, it is the sort, request, and number of boundaries of a technique. These are discretionary, strategy might contain zero boundaries.
strategy body − The technique body characterizes how the technique manages the assertions.


Example: 
modifier returnType nameOfMethod (Parameter List) {
   // method body
}


public static int methodName(int a, int b) {
   // body
}








Creating Method and Method Calling


Here is the source code of the above characterized technique called min(). This method takes two parameters, n1 and n2, and returns the difference between them that is the smallest. A method can be called either "method returns a value" or "method returns nothing" (no return value).

The course of strategy calling is straightforward. When a program calls a method, control of the program is given to the called method. This called technique then returns control to the guest in two circumstances, when −
the return proclamation is executed.
it arrives at the strategy finishing shutting support.


Example:
public class ExampleMinNumber {
   
   public static void main(String[] args) {
      int a = 11;
      int b = 6;
      int c = minFunction(a, b);
      System.out.println("Minimum Value = " + c);
   }

   /** returns the minimum of two numbers */
   public static int minFunction(int n1, int n2) {
      int min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
}



/** the snippet returns the minimum between two numbers */

public static int min(int n1, int n2) {
   int min;
   if (n1 > n2)
      min = n2;
   else
      min = n1;

   return min; 
}




The Void Keyword :

Here is the source code of the above characterized technique called min(). This method takes two parameters, n1 and n2, and returns the difference between them that is the smallest. A method can be called either "method returns a value" or "method returns nothing" (no return value).

The course of strategy calling is straightforward. When a program calls a method, control of the program is given to the called method. This called technique then returns control to the guest in two circumstances, when −
  • the return proclamation is executed.
  • it arrives at the strategy finishing shutting support.

public class ExampleVoid {

   public static void main(String[] args) {
      methodRankPoints(255.7);
   }

   public static void methodRankPoints(double points) {
      if (points >= 202.5) {
         System.out.println("Rank:A1");
      }else if (points >= 122.4) {
         System.out.println("Rank:A2");
      }else {
         System.out.println("Rank:A3");
      }
   }
}


Passing Parameters by Value :

While working under calling process, contentions is to be passed. These ought to be in similar request as their separate boundaries in the strategy determination. Boundaries can be passed by esteem or by reference.

Passing Boundaries by Worth means calling a strategy with a boundary. Through this, the contention esteem is passed to the boundary.

The accompanying project shows an instance of passing boundary by esteem. The upsides of the contentions continues as before even after the technique conjuring.



public class swappingExample {

   public static void main(String[] args) {
      int a = 30;
      int b = 45;
      System.out.println("Before swapping, a = " + a + " and b = " + b);

      // Invoke the swap method
      swapFunction(a, b);
      System.out.println("\n**Now, Before and After swapping values will be same here**:");
      System.out.println("After swapping, a = " + a + " and b is " + b);
   }

   public static void swapFunction(int a, int b) {
      System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
      
      // Swap n1 with n2
      int c = a;
      a = b;
      b = c;
      System.out.println("After swapping(Inside), a = " + a + " b = " + b);
   }
}





Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30

**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45



Method Overloading: 

At the point when a class has at least two techniques by a similar name however various boundaries, it is known as strategy over-burdening.

If, suppose we need to track down the base number of twofold sort. Then, at that point, the idea of over-burdening will be acquainted with make at least two strategies with a similar name however various boundaries.

Over-burdening strategies makes program lucid. Here, two strategies are given by a similar name however with various boundaries. The base number from number and twofold sorts is the outcome





public class ExampleOverloading {

   public static void main(String[] args) {
      int a = 11;
      int b = 6;
      double c = 7.3;
      double d = 9.4;
      int result1 = minFunction(a, b);
      
      // same function name with different parameters
      double result2 = minFunction(c, d);
      System.out.println("Minimum Value = " + result1);
      System.out.println("Minimum Value = " + result2);
   }

   // for integer
   public static int minFunction(int n1, int n2) {
      int min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
   
   // for double
   public static double minFunction(double n1, double n2) {
     double min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
}








Methods - Using Command-Line Arguments :

In some cases you will need to pass some data into a program when you run it. By supplying main with arguments from the command line, this can be accomplished

An order line contention is the data that straightforwardly follows the program's name on the order line when it is executed. To get to the order line contentions inside a Java program is very simple. In the String array given to main(), they are stored as strings.



public class CommandLine {

   public static void main(String args[]) { 
      for(int i = 0; i<args.length; i++) {
         System.out.println("args[" + i + "]: " +  args[i]);
      }
   }
}



$java CommandLine this is a command line 200 -100


args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100




Tuesday 2 January 2024

Understanding Java Data Types: A Comprehensive Guide

 


Java, a flexible and generally utilized programming language, depends on a powerful arrangement of information types to work with the control of information inside programs. These information types assume a critical part in characterizing the qualities of factors, determining the sort of information they can hold, and impacting the tasks that can be performed on them. In this article, we will dive into the rudiments of Java information types, investigating crude and reference types, their attributes, and their applications.




1. Primitive Data Types:

 Java has eight crude information types, which are the most essential structure blocks for addressing information. There are four groups of these types of data

    a. Integral Data Types:

            i. byte
                    The byte data type is an 8-bit signed two's complement integer. It can represent values from                     -128 to 127.
            ii. short
                    The short data type is a 16-bit signed two's complement integer, covering a range from                             -32,768 to 32,767.

           iii. int
                    The int data type is a 32-bit signed two's complement integer,    suitable for most integer-                        related computations.

           iv. long
                    The long data type is a 64-bit signed two's complement integer, capable of handling larger                     integer values.

    b. Floating-Point Data Types
            i. float
                    The float data type is a 32-bit single-precision floating-point, suitable for representing                             decimal values with moderate precision.

            ii. double
                    The double data type is a 64-bit double-precision floating-point, offering higher precision                         for decimal values.
    c. Character Data Type
               1.char
                        The char data type represents a 16-bit Unicode character. It allows the storage and                                     manipulation of individual characters and symbols.

    d. Boolean Data Type
                1.boolean
                        The boolean data type has only two possible values: true and false. It is primarily used                             for logical comparisons and branching.

2. Declaring and Initializing Variables:

In Java, variables must be declared with a specific data type before they can be used. 

For example:



int age; // Declaration
age = 25; // Initialization
Variables can also be declared and initialized in a single line:


double pi = 3.14; // Declaration and Initialization

3. Reference Data Types:

While crude information types handle straightforward qualities straightforwardly, reference information types manage more intricate items and give a reference to the article's memory area. Normal instances of reference types include:

a. Objects
In Java, everything is an item, and articles are cases of classes. For instance:

String greeting = "Hello, World!";
Here, String is a class, and greeting is an instance of that class.




4. Type Conversion:

Java upholds both understood and express sort change.

a. Verifiable Sort Transformation (Augmenting)

In specific circumstances, Java consequently changes over more modest information types to bigger ones without unequivocal projecting. For instance:


int smallNumber = 42;
double largerNumber = smallNumber; // Implicit conversion


b. Express Sort Change (Restricting)
While changing over bigger information types to more modest ones, express projecting is required. For instance:

double bigNumber = 123.456;
int smallNumber = (int) bigNumber; // Explicit conversion


5. Type Promotion:


In articulations including various information types, Java performs type advancement to guarantee similarity. The accompanying guidelines are applied:

On the off chance that two qualities have various information types, Java advances the more modest information type to the bigger one preceding playing out the activity.
Assuming that one of the qualities is twofold, the other is changed over completely to twofold.
Assuming one of the qualities is float, the other is changed over completely to drift.
On the off chance that one of the qualities is long, the other is switched over completely to long.
Assuming that one of the qualities is a fundamental sort (byte, short, int), the other is changed over completely to int.



6. End

Understanding Java information types is central to composing viable and solid projects. Whether managing crude or reference types, appropriate usage of information types guarantees exact portrayal and control of information inside your Java applications. As you leave on your programming process, dominating these essential ideas will engage you to make powerful and effective programming arrangements.

This article has given a far reaching outline of Java's essential information types, their qualities, and how they can be utilized in different situations. Outfitted with this information, you are exceptional to explore the complexities of information control in Java and construct hearty applications that satisfy the needs of current programming improvement.

Keep in mind, practice is critical to dominating these ideas. Try different things with various information types, investigate their ways of behaving, and steadily integrate them into your coding collection. As you proceed with your Java process, you'll find that a strong comprehension of information types lays the foundation for further developed programming ideas and methods. Have fun coding!

Unveiling the Power of Java: Understanding Objects and Classes

 

 Introduction:


Ava, one of the top broadly utilized programming languages, has gained enormous popularity for its portability, suppleness, and object-oriented advance . At the heart of Java's object-oriented paradigm lies the idea of objects and classes, that makeup the foundation of its strong and modular architecture . In this article, we'll dig into the globe of Java's object-oriented programming and investigate the importance of objects and classes in constructing scalable and maintainable program .










Objects and Classes in Java:


At its basic, Java is an object-oriented programming (OOP) verbal communication, that is to say it revolves around the idea of objects . An thing is a basic unit in Java, serving a real-world entity or conception . Objects encapsulate information and conduct, offering a modular and systematic way to form programming language . The blueprint for building objects is defined by classes . A course, in Java, represents as a template or blueprint for objects . It encapsulates information subscribers (fields) and methods that clarify the conduct of the objects instantiated from it . Classes act as a blueprint for building many instances of objects, letting for programming language reuse and the implementation of a modular construct .

Encapsulation and Abstraction:


Java's OOP paradigm emphasizes encapsulation, a conception that entails bundling information and methods within a course, restricting entry to the inner details of the course . This encapsulation ensures that the inner assert of an thing is not directly available from exterior the lesson, encouraging information integrity and security . Abstraction is key principle in Java's OOP algorithm . It entails simplifying complicated systems by modeling classes as said by the crucial attributes and behaviors pertinent to the application . Abstraction lets developers to concentrate on the crucial facets of an thing whereas disguising the unnecessary details, making the programming language more controllable and scalable .

Inheritance and Polymorphism:

Java's OOP paradigm emphasizes encapsulation, a conception that entails bundling information and methods within a course, restricting entry to the inner details of the course . This encapsulatioJava supports inheritn ensures that the inner assert of an thing is not directly available from exterior the lesson, encouraging information integrity and security . Abstraction is key principle in Java's OOP system . It entails simplifying complicated systems by modeling classes as said by the crucial attributes and behaviors pertinent to the application . Abstraction lets developers to concentrate on the crucial facets of an thing whereas disguising the unnecessary details, making the programming language more controllable and scalable .

Example:

Let's contemplate a basic instance to exemplify the concepts of objects and classes in Java . imagine we have a lesson named "Car" with traits as an example make, machine, and year, besides methods like start Engine and stop Engine . we may build several instances of the Car course, each serving a particular car with original qualities .


public class Car {
    // Data members
    String make;
    String model;
    int year;

    // Methods
    public void startEngine() {
        System.out.println("Engine started");
    }

    public void stopEngine() {
        System.out.println("Engine stopped");
    }

    // Constructor
    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    // Main method for illustration
    public static void main(String[] args) {
        // Creating instances of the Car class
        Car car1 = new Car("Toyota", "Camry", 2022);
        Car car2 = new Car("Ford", "Mustang", 2021);

        // Accessing methods
        car1.startEngine();
        car2.stopEngine();
    }
}


Conclusion:

Java's object-oriented advance, with its emphasis on objects and classes, facilitates the growth of modular, reusable, and maintainable application . knowledge the principles of encapsulation, abstraction, inheritance, and polymorphism empowers developers to generate strong and scalable applications . By leveraging the potency of objects and classes, Java continues to be a cornerstone in contemporary program advancement, offering a opaque foundation for constructing complicated and effective systems .


Monday 1 January 2024

JAVA

 Mastering the Basics: A Comprehensive Guide to Java Syntax


Introduction: 

Java, a versatile and object-oriented programming verbal communication, has become a cornerstone in application advancement . To board on your Java roam, it's essential to grip the basics of Java syntax . In such documentation, we'll investigate the basic components, conventions, and form that makeup the spine of Java programming .


01. Java Program Structure: 


A Java program is structured as a collection of classes . Each program need to have without a doubt one course with an essential procedure . the essential procedure is the entry point for the program, where execution kicks off 
.
👆←→→→→→→→→→→→→→→→→→→→→→→→→→→
public class MyProgram {
    public static void main(String[] args) {
        // Your code here
    }
}
→→→→→→→→→→→→→→→→→→→→→→→→→→→→

02.Variables and Data Types: 

Java is a statically-typed verbal communication, meaning factor types need to be announced explicitly . familiar information types include int, double, char, and boolean . factor names have to hold to camelCase conference .

↑→→→→→→→→→→→→→→→→→→→→→→→→→→→→→

int age = 25;
double price = 19.99;
char grade = 'A';
boolean isJavaFun = true;

→→→→→→→→→→→→→→→→→→→→→→→→→→→→→

03.Control Flow Statements: 

Java supports crucial comparison movement statements, containing if, else, alternate, for, whereas, and do-while . These structures dictate the movement of program execution as said by ailments or loops .


→→→→→→→→→→→→→→→→→→→→→→→→→→→→→


if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}

for (int i = 0; i < 5; i++) {
    // Code to repeat five times
}

while (condition) {
    // Code to execute as long as the condition is true
}

→→→→→→→→→→→→→→→→→→→→→→→→→→→→→

04.Methods: 

Methods in Java encapsulate reusable blocks of programming language . they're announced with a revert write, a designation, and limits (if any) . The invalid revert write signifies a way that doesn't revert a worth .

→→→→→→→→→→→→→→→→→→→→→→→→→→→→→

public int add(int a, int b) {
    return a + b;
}

public void printMessage() {
    System.out.println("Hello, Java!");
}

→→→→→→→→→→→→→→→→→→→→→→→→→→→→→

05.Object-Oriented Concepts:

Java is celebrated for its object-oriented paradigm . Classes and objects makeup the basis of Java programs . Classes encapsulate information and conduct, whereas objects are instances of classes .

→→→→→→→→→→→→→→→→→→→→→→→→→→→→→

class Dog {
    String breed;
    int age;

    void bark() {
        System.out.println("Woof!");
    }
}

// Creating an object
Dog myDog = new Dog();
myDog.breed = "Labrador";
myDog.age = 2;
myDog.bark();


→→→→→→→→→→→→→→→→→→→→→→→→→→→→→

06.Arrays:

Arrays in Java are collections of elements of the same data type. They offer a way to store and manipulate data efficiently.

→→→→→→→→→→→→→→→→→→→→→→→→→→→→→


int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[3]; // Creating an array with a specified size
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";

→→→→→→→→→→→→→→→→→→→→→→→→→→→→→

07.Exception Handling:

Java employs exception handling to manage errors during runtime. The try, catch, finally blocks handle exceptions gracefully.


→→→→→→→→→→→→→→→→→→→→→→→→→→→→→

try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
} finally {
    // Code that executes regardless of whether an exception occurred
}

→→→→→→→→→→→→→→→→→→→→→→→→→→→→→


Conclusion


Mastering Java syntax lays the foundation for adept programming . common exercise, exploration of sophisticated concepts, and involvement with the Java community will in addition to polish your abilities . As you dig deeper into Java advancement, remember that a healthy win of syntax is the key to unlocking the language's complete capability . such documentation offers a exhaustive summary of Java syntax, covering crucial concepts that lay the groundwork for cogent Java programming . regardless of whether you're a learner or seeking a refresher, knowledge these basics is essential for navigating the globe of Java growth .





Powered by Blogger.

Assignment 2 PHP Answer | source code |UOM

 admin.php <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "WaterBills&...

Sponsor

Ahamed Hather

Popular Posts