Debugging and Optimizing Essential Java Code Examples

Classified in Computers

Written on in English with a size of 10.4 KB

This document presents seven fundamental Java programming examples (pg1 through pg7) that demonstrate basic input/output, conditional logic, array handling, and algorithmic concepts. The original code contained numerous syntax errors, capitalization issues, and logical flaws. Below, we provide the corrected and optimized versions, ensuring proper Java conventions and functionality.

1. pg1: Conditional Arithmetic Checks

Purpose: Evaluating multiple arithmetic relationships between three input integers (a, b, c).

The original code had incorrect capitalization (Int, If, Else) and a logical flaw where the combined condition check was unreachable due to sequential else if statements. The corrected version addresses these issues.

import java.util.Scanner;

public class pg1 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter values for a, b, c:");
        int a = in.nextInt();
        int b = in.nextInt();
        int c = in.nextInt();

        boolean condition1 = (a + b == c);
        boolean condition2 = (b - c == a);
        boolean condition3 = (a * b == c);

        if (condition1 && condition2 && condition3) {
            System.out.println("All conditions are correct.");
        } else if (condition1 || condition2 || condition3) {
            System.out.println("At least one condition is correct.");
        } else {
            System.out.println("Nothing is correct.");
        }
    }
}

2. pg2: Counting Divisions by Two

Purpose: Determining how many times an integer can be divided by 2 until it is less than 2.

This snippet was corrected for variable mismatch (using n instead of input a) and ensuring the counter (q) increments correctly inside the while loop.

import java.util.Scanner;

class pg2 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter an integer (n):");
        int n = in.nextInt();
        int q = 0;

        if (n >= 2) {
            while (n >= 2) {
                n = n / 2;
                q++; // Increment counter
            }
        }
        System.out.println("Number of divisions by 2: " + q);
    }
}

3. pg3: Generating Permutations of "carbon"

Purpose: Generating all unique 6-letter permutations of the characters in the word "carbon".

Fixes included declaring all loop variables (i, j, k, l, m, n) and the count variable, correcting the array name from str to alpha, and ensuring proper syntax for the nested loops and conditional checks for unique indices.

class pg3 {
    public static void main(String[] args) {
        char alpha[] = {'c', 'a', 'r', 'b', 'o', 'n'};
        int i, j, k, l, m, n;
        int count = 0;

        // 6 nested loops to check all combinations
        for (i = 0; i < alpha.length; i++) {
            for (j = 0; j < alpha.length; j++) {
                for (k = 0; k < alpha.length; k++) {
                    for (l = 0; l < alpha.length; l++) {
                        for (m = 0; m < alpha.length; m++) {
                            for (n = 0; n < alpha.length; n++) {
                                // Check if all indices are unique (i.e., a permutation)
                                if (i != j && i != k && i != l && i != m && i != n &&
                                    j != k && j != l && j != m && j != n &&
                                    k != l && k != m && k != n &&
                                    l != m && l != n &&
                                    m != n) {

                                    String permutation = "" + alpha[i] + alpha[j] + alpha[k] + alpha[l] + alpha[m] + alpha[n];
                                    System.out.println(permutation);
                                    count += 1;
                                    System.out.println("Count: " + count);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

4. pg4: Reading and Printing String Arrays

Purpose: Reading N lines of input from the user and storing them in a String array, then printing the contents.

The original loop structure was fundamentally broken. This version correctly handles Scanner input after nextInt() and uses standard for loops for reading and printing the array elements.

import java.util.Scanner;

class pg4 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter value of n (number of lines):");
        int n = in.nextInt();
        in.nextLine(); // Consume newline left by nextInt()

        String str[] = new String[n];
        System.out.println("Enter the lines:");

        int i;
        // Loop to read input
        for (i = 0; i < n; i++) {
            System.out.print("Line " + (i + 1) + ": ");
            str[i] = in.nextLine();
        }

        System.out.println("\n--- Entered Lines ---");

        // Loop to print input
        for (i = 0; i < n; i++) {
            System.out.println(str[i]);
        }
    }
}

5. pg5: Odd Number Check via Subtraction

Purpose: Implementing a custom isOdd method that determines parity by repeatedly subtracting 2.

Syntax corrections were applied (public, static, proper capitalization). This method demonstrates an alternative, albeit inefficient, way to check for odd numbers compared to the modulo operator (%).

import java.util.Scanner;

class pg5 {
    /**
     * Checks if a number is odd by repeatedly subtracting 2.
     * @param n The integer to check.
     * @return true if n is odd, false otherwise.
     */
    public static boolean isOdd(int n) {
        while (n > 1) {
            n = n - 2;
        }
        if (n == 1) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter value of n:");
        int n = in.nextInt();

        if (isOdd(n)) {
            System.out.println(n + " is odd.");
        } else {
            System.out.println(n + " is even (or zero/negative).");
        }
    }
}

6. pg6: Finding Minimum and Maximum in an Array

Purpose: Implementing separate methods to find the minimum and maximum values within a user-defined array.

Crucial logical errors were fixed in the min and max methods, where the original code returned immediately after the first comparison, preventing the full array scan. Syntax and variable declarations were also corrected.

import java.util.Scanner;

class pg6 {
    // Finds the minimum value in the first 'num' elements of array 'a'
    public static int min(int a[], int num) {
        int minValue = a[0];
        for (int i = 1; i < num; i++) {
            if (a[i] < minValue) {
                minValue = a[i];
            }
        }
        return minValue;
    }

    // Finds the maximum value in the first 'num' elements of array 'b'
    public static int max(int b[], int num) {
        int maxValue = b[0];
        for (int i = 1; i < num; i++) {
            if (b[i] > maxValue) {
                maxValue = b[i];
            }
        }
        return maxValue;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int arr[] = new int[20];
        System.out.println("How many numbers do you want to enter (max 20)?");
        int arrcount = in.nextInt();

        if (arrcount > 20 || arrcount <= 0) {
            System.out.println("Invalid count.");
            return;
        }

        System.out.println("Enter elements:");
        int i;
        for (i = 0; i < arrcount; i++) {
            System.out.print("Enter " + (i + 1) + " number: ");
            arr[i] = in.nextInt();
        }

        int minimum = min(arr, arrcount);
        int maximum = max(arr, arrcount);

        System.out.println("\nMinimum value entered: " + minimum);
        System.out.println("Maximum value entered: " + maximum);
    }
}

7. pg7: Identifying Pairs with Odd Products

Purpose: Iterating through an array to find pairs of distinct elements whose product is odd.

Fixes included correcting the method signature, ensuring the product method was closed properly, fixing the spelling of continue, correcting array access in main, and adjusting the nested loop structure (j = i + 1) to efficiently check distinct pairs only once. We used long for the product calculation to prevent potential integer overflow.

import java.util.Scanner;

class pg7 {
    // Finds pairs of distinct elements whose product is odd
    public static void product(int a[], int c) {
        System.out.println("\nChecking products for odd results:");
        for (int i = 0; i < c; i++) {
            // Start j from i + 1 to ensure distinct pairs (i != j) and avoid redundant checks
            for (int j = i + 1; j < c; j++) {
                // Product of two integers is odd ONLY if both integers are odd.
                long pro = (long) a[i] * a[j];

                if (pro % 2 != 0) {
                    System.out.println("The product of " + a[i] + " and " + a[j] + " is Odd (" + pro + ").");
                }
            }
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int arr[] = new int[20];
        System.out.println("How many numbers do you want to enter (max 20)?");
        int c = in.nextInt();

        if (c > 20 || c <= 0) {
            System.out.println("Invalid count.");
            return;
        }

        int i;
        for (i = 0; i < c; i++) {
            System.out.print("Enter " + (i + 1) + " number: ");
            arr[i] = in.nextInt();
        }

        // Call product method
        product(arr, c);
    }
}

Related entries: