Posts

Showing posts from March, 2021

In Java Swing, Change Side Colors Of Frame On Button Click

Image
import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.JButton; import java.awt.BorderLayout; import java.awt.Color; import java.util.Random; public class JColorFrame extends JFrame{ private JPanel[]sides; private JButton btn; private Color[]colors; private Random random; public JColorFrame(){ super("Colors"); sides = new JPanel[]{ new JPanel(), new JPanel(), new JPanel(), new JPanel() }; btn = new JButton("Change"); colors = new Color[]{ Color.RED, Color.BLUE, Color.CYAN, Color.PINK }; random = new Random(); } private void createGUI(){ String[]dirs={ BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.EAST, BorderLayout.WEST }; getContentPane().add(btn); for(int i = dirs.length-1; 0<= i; i --) getContentPane().add(sides[i], dirs[i]); } private void bindEvents(){ btn.addActionListener((e)->{ SwingUtilities.invokeLater(()->

In Java, Multiple String Operations With Single Scanner Object

Image
 Problem Statement: Write a method named site. This method accepts the Scanner object as its parameter. This method reads a commercial website URL that starts with www and ends with .edu or .com. This method retrieves the name of the site and outputs the site without the www prefix and the domain suffix. If the user enters www.yahoo.com then this method outputs yahoo. Write a method called decrypt that accepts a Scanner object as its parameter. this method reads an encrypted word and then decrypts the word. Here is the decryption algorithm: only the even numbered characters should be counted as the part of the word. Other characters should be discarded. For example if the user enters: hwealxlaod then the decrypted word is HELLO. Pay attention that the decrypted word is all in capital letters. Write a method called reverse that accepts the Scanner object as its parameter. This method asks the user for the entire name and prints the name in the reverse order. You must only use nextLine(

In Cpp/C++, Demonstrate Telegram Bill And Morse Code Translation

Image
#include<iostream> #include<string> using namespace std; void telegramBill(); void morseCode(); int main(){ int choice; cout << "Welcome to Western Union Telegram Company" << endl << endl; cout << "1 - Process Telegram Bill" << endl; cout << "2 - Translate to Morse Code" << endl << endl; cout << "Enter your choice: "; cin >> choice; cin.ignore(); switch(choice){ case 1: telegramBill(); break; case 2: morseCode(); break; default: cout << endl << choice << " is not a valid choice." << endl; } return 0; } void telegramBill(){ const double RATE_PER_FIVE = 1.50; const double RATE_PER_SINGLE = 0.50; string custName, street, city, state, zip; int words, blockFiveWords, remSingleWords, payment, change, dollars, quarters, dimes, nickels, pennies; double amountDue; cout << "Enter the name of the customer: ";

In Java, Ship Implementing With Cargo And Cruise Ship

Image
import java.util.List; import java.util.ArrayList; public class TestShip{ public static void main(String[]args){ List<Ship> ships = new ArrayList<>(); ships.add(new Ship("NSU Vic", 1884)); ships.add(new Ship("NSU Column", 1902)); ships.add(new CruiseShip("Java Queen 1", 2003, 450)); ships.add(new CruiseShip("CIS Minnow", 2010, 250)); ships.add(new CargoShip("Demon 1", 1999, 7000)); ships.add(new CargoShip("Demon 2", 1993, 10000)); for(Ship s: ships){ System.out.println(s.toString()); } } } Download

In C, Merge Sorted Data Files Into Single Output Data File

Image
/** * your name, * the course number, * the date the program was completed, * a brief description of theprogram. */ #include<stdio.h> int merge(const char*, const char*, const char*); int main(){ int error = merge("Data1.txt","Data2.txt","Merged.txt"); if(error){ printf("Error: File merging failed\n"); } else { printf("Success: File merged\n"); } return error; } int merge(const char* n1, const char* n2, const char* n3){ FILE *in1 = fopen(n1, "r"); if(!in1){ printf("Error: Could not read file: %s\n", n1); return 1; } FILE *in2 = fopen(n2, "r"); if(!in2){ fclose(in1); printf("Error: Could not read file: %s\n", n2); return 2; } FILE *out = fopen(n3, "w"); if(!out){ fclose(in1); fclose(in2); printf("Error: Could not write file: %s\n", n3); return 3; } int num1, num2; //until end of file whi

In Python, Test If Given List Is Sorted Or Not

Image
def isSorted(stack): value = True prv = None if 0 < len(stack): prv = stack[0] for cur in stack: if prv < cur: value = False break return value if '__main__' == __name__: stack = [20, 20, 17, 11, 8, 8, 3, 2] print(isSorted(stack), stack) stack = [22] print(isSorted(stack), stack) stack = [] print(isSorted(stack), stack) stack = [21, 22, 20] print(isSorted(stack), stack) Download

In Python, Implementing Own Range() To Return List

Image
def myRange(start, stop = None, step = None): nums = None if None == step: step = 1 if None == stop: stop = start start = 0 if None != start and None != step: nums = [] while start < stop: nums.append(start) start += step return nums if '__main__' == __name__: print(myRange(3)) print(myRange(1, 7)) print(myRange(1, 7, 2)) print(myRange(-5, 1)) print(myRange(-5, 1, 2)) Download

In Python, Compute Average Of All Numbers In File

Image
def read_all(path): nums = None try: with open(path, 'r') as file: for line in file: if not nums: nums = [] try: nums.append(int(line.strip())) except ValueError: pass except IOError as e: print(e) return nums def average(nums): if not nums: return None total = 0 count = 0 for num in nums: total += num count += 1 return total/count if '__main__' == __name__: nums = read_all('number.dat') print(nums) print('average', average(nums)) Download

In Python, How To Fix Broken Wi-Fi Using Loop And If-Else? I Wish I Could 😄

Image
solutions = [ 'Reboot the computer and try to connect', 'Reboot the router and try to connect', 'Make sure the cables between the router & modem are plugged in firmly', 'Move the router to a new location and try to connect', 'Get a new router' ] print('### Troubleshooting Wifi issue ###') while True: step = solutions.pop(0) print('Step:',step) if 0 == len(solutions): break print('Did that fix the problem?') ans = input().lower().strip() if ans and 'y' == ans[0]: break

In Java, Finding Combinations From User Given Numbers

Image
import java.util.Scanner; public class Combo10{ public static void main(String[]args){ int[]nums = new int[10]; Scanner user = new Scanner(System.in); int i = nums.length - 1; while(0 <= i){ System.out.print("Enter number: "); nums[i --] = user.nextInt(); } int j = nums.length - 1; int n1, n2; System.out.println("Trying combinations ..."); while(0 <= j){ n1 = nums[j --]; i = nums.length - 1; while(0 <= i){ n2 = nums[i --]; if(n1 != n2){ System.out.printf("%d & %d%n", n1, n2); } } } } } Download

In Java, Compute Total Of ArrayList

Image
import java.util.Scanner; import java.util.ArrayList; public class Main{ public static double sum(ArrayList<Double> list){ double total = 0; for(double value: list) total += value; return total; } private static ArrayList<Double> readNumbers(final Scanner in, final int count){ ArrayList<Double> list = new ArrayList<>(); double real; while(count > list.size()){ System.out.print("Enter a number: "); try{ real = new Double(in.nextLine()); list.add(real); }catch(NumberFormatException e){ System.out.println("Error: Not a number!"); }catch(Exception e){ System.out.println("Error: Something went wrong!"); break; } } return list; } public static void main(String[]args){ ArrayList<Double> list = readNumbers(new Scanner(System.in), 5); double total = sum(list); System.out.printf("Sum of %s is: %.2f%n", list, total); } } Download

In Java, Implement List Of Inventory

Image
import java.util.List; import java.util.LinkedList; public class InventoryListImpl implements InventoryList{ private List<Inventory> list; public InventoryListImpl(){ list = new LinkedList<Inventory>(); } public int getSize(){ return list.size(); } public boolean add(Inventory item){ int size = getSize(), cmp; if(MAX_SIZE == size) return false; for(int i = 0; size > i; i ++){ cmp = list.get(i).getName().compareTo(item.getName()); if(0 == cmp){ return false; } else if(0 < cmp){ list.add(i, item); i = size; return true; } } list.add(item); return true; } public Inventory remove(Inventory item){ int size = getSize(); if(0 == size) return null; for(int i = 0; size > i; i ++){ if(0 == list.get(i).getName().compareTo(item.getName())){ return list.remove(i); } } return null; } public boolean contains(Inventory item){ int size = getSize(); if(0 == size) return false; for(int i = 0;

In Java, Compute Billing For Home And Corporate Users

Image
public class Bills{ private static void printBill(final String client, final int connections, final int channels){ System.out.printf("Client: %s%n", client); System.out.printf("No# of connections: %d%n", connections); System.out.printf("No# of channels: %d%n", channels); float regChg = 5.5f; float srvChg = 21.5f; float chnChg = 8.5f; if(10 < channels){ chnChg += 0.5f * (channels - 10); } if("Corporate".equalsIgnoreCase(client)){ regChg = 15.0f; srvChg = 75.0f; chnChg = 50.0f; if(20 < channels){ chnChg += 2.0f * (channels - 20); } } if(10 < connections){ srvChg += 5.0 * (connections-10); } System.out.printf("Registration charges: $%.2f%n", regChg); System.out.printf("Initial service charges: $%.2f%n", srvChg); System.out.printf("Premium channels: $%.2f%n", chnChg); double total = regChg + srvChg + chnChg; System.out.printf("Total charges: $%.

In Java, Sorted ArrayList Of Names In Title Case

Image
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main{ static List<String> personNames = new ArrayList<String>(); public static void main(String args[]){ Scanner scanner = new Scanner(System.in); String inputName; while (true){ System.out.println("Enter the next name:"); inputName = scanner.nextLine().trim(); if (inputName.toLowerCase().equals("end")){ break; } else { insertionSort(titleCase(inputName)); } } System.out.println(personNames.toString()); } /** * * It converts the given sting in titleCase. * * @param name * * @return * */ public static String titleCase(String name){ final char[]all = name.toCharArray(); StringBuilder s1 = new StringBuilder(all.length); boolean caps = true; for(char c : all){ if(Character.isSpaceChar(c)){ caps = true; } else if(caps){ c = Character.toUpperCase(c); caps = false;

In PHP, Simple Session Example Of Login And Logout

Image
<?php session_start(); if(isset($_SESSION['username']) && isset($_POST['action']) && 'logout' === $_POST['action']){ unset($_SESSION['username']); } if(isset($_POST['username']) && isset($_POST['action']) && 'login' === $_POST['action']){ $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING); $usernmae = trim($username); if($username){ $_SESSION['username'] = $username; } else { echo '<p>Error: Invalid login attempt</p>'; } } if(isset($_SESSION['username'])){ echo '<p>Hello <b>', ($_SESSION['username']), '</b> you are logged in</p>', '<form method="post">', '<input type="submit" value="Logout"/>', '<input type="hidden" value="logout" name="

In Java, Password Pattern Validation

Image
import java.util.Scanner; public class ValidatePassword{ public static void main(String[]args){ String pswd; int digi, uper, lowr; char[]chars = null; final int MIN = 2; final String ERROR = "%nError: At least %d %s is mandate!"; Scanner user = new Scanner(System.in); do{ digi = uper = lowr = 0; chars = null; System.out.print("\nEnter password: "); if(!user.hasNextLine()) break; pswd = user.nextLine(); if(null == pswd) break; chars = pswd.toCharArray(); for(char c: chars){ if(Character.isUpperCase(c)){ uper ++; } else if(Character.isLowerCase(c)){ lowr ++; } else if(Character.isDigit(c)){ digi ++; } } if(MIN > digi){ System.out.printf(ERROR, MIN, "digits"); } else if(MIN > uper){ System.out.printf(ERROR, MIN, "upper case"); } else if(MIN > lowr){ System.out.printf(ERROR, MIN, "lower case"); } else { break; } }while(true)