C30N9's Doomworld Forums Blog

C30N9's Doomworld Forums Blog

Java Memory Game July 6, 2015, 11:11 pm
In an assignment, I created a simple memory game.

Memory Game.

Also, I have a question. Which is better to use to close the program? System.exit(0)? Or dispose() to destroy the window, which already terminates the program on close?

Java GUI Calculator July 2, 2015, 11:36 pm
Here is a code for a calculator using GUI and event driven programming. One annoying problem is that the numbered buttons call the action method twice. Suggestions to improve the program is much appreciated.

EDIT: An error found. Putting 0s in front of numbers might manipulate the calculation a bit.

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

// these are for evaluating equations stored in a string. searched on net
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class Calculator extends JFrame {

// components are declared here for reference in the inner class (ButtonListener)

JButton jbtCalculate = new JButton("Calculate");
JButton jbtClear = new JButton("Clear");
JButton[] jbtNumbers = new JButton[10];
JButton[] jbtOperators = {new JButton ("+"), new JButton ("-"), new JButton ("/"), new JButton ("*")};

JTextField equationText = new JTextField(15);

ButtonListener listener = new ButtonListener();

public Calculator() {

JPanel mainPanel = new JPanel(new BorderLayout(5, 5));

JPanel panelText = new JPanel();
JPanel panelNumberButtons = new JPanel(new GridLayout(4, 3, 5, 5));
JPanel panelOperatorButtons = new JPanel(new GridLayout(4, 1, 5, 5));
JPanel panelBottomButtons = new JPanel(new FlowLayout(FlowLayout.CENTER)); // "Calculate" and "Clear" buttons

for (int i = 0; i < jbtNumbers.length; i++) {

jbtNumbers = new JButton("" + i);


panelText.setBorder(new TitledBorder("Equation"));

panelNumberButtons.setBorder(new TitledBorder("Numbers"));
for (int i = jbtNumbers.length - 1; i > 0; i -= 3) {

panelNumberButtons.add(jbtNumbers[i - 2]);
panelNumberButtons.add(jbtNumbers[i - 1]);

jbtNumbers[i - 2].addActionListener(listener);
jbtNumbers[i - 1].addActionListener(listener);


panelOperatorButtons.setBorder(new TitledBorder("Ops"));
for (int i = 0; i < jbtOperators.length; i++) {




mainPanel.add(panelText, BorderLayout.NORTH);
mainPanel.add(panelNumberButtons, BorderLayout.CENTER);
mainPanel.add(panelOperatorButtons, BorderLayout.EAST);
mainPanel.add(panelBottomButtons, BorderLayout.SOUTH);



class ButtonListener implements ActionListener {

// these are for evaluating equations stored in a string. searched on net
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");

public void actionPerformed(ActionEvent e) {

if (e.getSource() != jbtCalculate && e.getSource() != jbtClear)
equationText.setText(equationText.getText() + ((JButton)e.getSource()).getText());

else if (e.getSource() == jbtClear)


try {



catch (Exception ex) {





public static void main(String[] args) {

Calculator calculator = new Calculator();

calculator.setSize(225, 300);



Finding the biggest object June 27, 2015, 11:45 am
I've been asked to write a method which is public static Object max(Object[] a). It should return the highest Object in an Object array using compareTo method. However, with this method's parameter, since Object doesn't have compareTo method, I'm supposed to put several if statements to determine if the object is an instanceof Account, or Employee, or other classes that use compareTo:

public static Object max(Object[] a) {

if (a instanceof Account[]) {

// for loops and casting from Object to Account

return max;


if (a instanceof Employee[]) {

// for loops and casting from Object to Employee

return max;

// yadda yadda...

So I changed the function to this:

public static Object max(Comparable[] a) {

Comparable max = a[0];

for (int j = 0; j < a.length; j++)
if (max.compareTo(a[j]) < 0)
max = a[j];

return max;


Which works fine, and I think it's similar to java.util.Arrays.max(anArray). But I heard that it's not a very good idea to do that. Is it healthy to do this?

Dealing with regex in Java June 21, 2015, 4:41 pm
I'm supposed to write a method that acts like java.lang.String.split, except that this new method returns a String array including the delimeters. For example:

split("Java#HTML#Cpp", "#") would return "Java", "#", "HTML", "#" and "Cpp" in an array. I already done the hard part, which returns the array correctly. However, I don't how to make it work with regular expressions, such as:

split("Java#HTML$Cpp%Python", "[#$%]"). It should return:

"Java", "#", "HTML", "$", "Cpp", "%", "Python".

Any ideas?

Here is my code BTW:

public class Task1 {

public static void main(String[] args) {

String[] s = split("Java#$oooHTML#$oooCpp", "#$ooo");

for (int i = 0; i < s.length; i++)


public static String[] split(String s, String regex) {

// example: s = "Java#HTML#Cpp", regex = "#"

int counter = 0;
StringBuilder subString = new StringBuilder(s); // "Java#HTML#Cpp"
String[] result;

// get number of sub strings and store in counter
while (subString.indexOf(regex) != -1) {

counter += 2;
subString = subString.delete(0, subString.indexOf(regex) + 1);
// to "HTML#Cpp" to "Cpp"


result = new String[counter];
subString = new StringBuilder(s); // new "Java#HTML#Cpp"

if (regex.indexOf("[") != -1 && regex.indexOf("]", regex.indexOf("[")) != -1)
isRegex = true;

// fill result[]
for (int i = 0; i < result.length; i++) {

// if the current subString does not start with regex
if (!subString.toString().startsWith(regex)) {

if (subString.indexOf(regex) != -1) {

result = subString.substring(0, subString.indexOf(regex));
subString = subString.delete(0, subString.indexOf(regex));

} else
result = subString.substring(0);

} else {

result = new String(regex);// String.valueOf(subString.charAt(0)); // store the regex "#"
subString = subString.delete(0, regex.length());



return result;



An algorithm for this June 8, 2015, 9:44 am
So I want the output to be this:

____5 (four spaces)
___45 (three spaces)
__345 (and so on...)

Using without more than 2 loops. Doesn't matter any language, but C or Java works.

Variables in recursive functions May 1, 2015, 8:09 am
Yesterday, in my C programming lab, I was solving problems with recursions, the hardest part was that some of them required using variables inside recursive functions for better solutions. I tried to avoid declaring variables inside them as that would harm the memory, so I ended up declaring global variables, which ended in a mess. Here is an example of my functions:

void arrayRecursion (int x[], int length) {

if (length != 0) {

//int lengthTop = length;
printf ("%d\t%d\n", x[10 - length], x[length - 1]);
arrayRecursion (x, length - 1);



The number "10" in the above code is the size of the array I declared later in the main function. I could use a constant value of 10 in SIZE, but a better way is to put another integer variable in the function to store length value like the comment I wrote, but this will make it change its value to the new length, and it will keep declaring integer type variable.

int length = 6;
int z, currentElement = 0;
int foundError = 0;

void pali (char x[]) {

if (foundError)
printf ("\nNo, it is not.");

else if (currentElement != length) {

//if (length % 2 == 0)
// z = length/ 2;

// z = (length / 2) + 1;

//if (currentElement <= z)

if (x[currentElement] != x[length - currentElement - 1]) {
foundError = 1;


pali (x);



This messy function is supposed to check if a string is a palindrom string. length's value is the length of the character array "LeooeL", same issue as the first code (putting the length as a variable). z (didn't bother to pick a name for it) should be used to indicate whenever it should stop checking, but I didn't finish the function, so I put a comment for each statement concerning it, as it's the not the issue here. Notice where I declared the variables, not favorable.

Can anyone explain this to me? April 13, 2015, 12:25 pm
EDIT: Nevermind, I misunderstood it at first. I thought that when I add "6", it would add to array[5] (or the sixth element of the array). Problem solved.

This is for an assignment. I'm not asking for the solution, but I'm a bit confused:

Write a C program to create and manipulate a one dimensional array (list) of up to a hundred sorted (ascending order) numbers by using functions to insert, remove, or print elements as follows:
- Function insert: will search for the appropriate position of a given element and if the element is already in the list will display an error message. If not, the function will shift all the elements starting from the position of the element to the right of the array and then insert the element into that position.
- Function remove: will search for the element to be removed and if not found will display an error message. If the element exists, the function will remove it and shift all the elements that follow it to the left of the array.
- Function print: will print the elements that exist in the array at that point.
Your program should display a menu to the user that allows him/her to insert, remove, or print as many elements as they want until they want to stop. If an element is inserted into an already full list, an error message should be displayed. The array (list) at the beginning should be empty.

Example of a sample run:
Enter your choice: 1) insert 2) remove 3) print 4) exit
List is empty, No change
Enter your choice: 1) insert 2) remove 3) print 4) exit
Enter element to insert
Element 6 is inserted
Enter your choice: 1) insert 2) remove 3) print 4) exit
Enter element to insert
Element 9 is inserted
Enter your choice: 1) insert 2) remove 3) print 4) exit
Enter element to insert
Element 7 is inserted
Enter your choice: 1) insert 2) remove 3) print 4) exit
Enter element to remove
Element 112 does not exist, No change
Enter your choice: 1) insert 2) remove 3) print 4) exit
Enter element to remove
Element 6 is removed
Enter your choice: 1) insert 2) remove 3) print 4) exit
Elements in list are:
Enter your choice: 1) insert 2) remove 3) print 4) exit
Enter element to insert
Element 7 already exists, No change
Enter your choice: 1) insert 2) remove 3) print 4) exit

It seems to me that the example is wrong, shouldn't element 7 become 6? And what if the 100th element (99) is shifted to the right? They didn't say anything about the limits.

Solving equations with e ^ x and x April 1, 2015, 7:10 am
Today, in my Calc II exam, I've came across the question of finding the derivative of an inverse function when x = 2. The function was as I remember:

f(x) = e ^ 2x + 4x + 1

I didn't know how to solve for x algebraically after I substituted f(x) with 2 (or using ln or exp functions). So I put automatically x = 0 as it will satisfy the equation and then I proceeded. Luckily, it was a multiple choice question, so the method of solving isn't important.

How do I solve this?

[SOLVED] Why is the output negative? March 10, 2015, 9:59 am
This code is supposed to calculate e to the power x. It works fine at lower numbers, but then at x = 3.6, the output starts to decrease as x goes up. What's wrong?

C language.

EDIT: The problem was that "factorial" function was an int, so at high values, it won't work.

#include <stdio.h>

double factorial (int n) {

double f_result = 1; //factorial result
int i;

for (i = 1; i <= n; i++)
f_result *= i;

return f_result;


double power (double base, int exponent) {

double p_result = 1; //power result
int i;

for (i = 1; i <= exponent; i++)
p_result *= base;

return p_result;

double compute_ex (double x) {

double division = 1;
double div_sum = 0;
int counter = 0;

while (division >= 0.0001) {

division = power (x, counter) / factorial (counter);
div_sum += division;



return div_sum; //div_sum is the sum of the infinite series, which is e to the power x


int main()

double x;

printf ("Enter the value of x:\n");
scanf ("%lf", &x);

printf ("e to the power %.1lf = %.2lf", x, compute_ex (x));

return 0;


Minor in mathematics February 25, 2015, 1:27 pm
I'm majoring in computer science (first year), and I'm thinking of taking minor in math. The reason is because of its connection to computer science (since it's a sub-field of math), and I like it a lot. The question is, are these a good pair?

For CS degrees, math courses include Calculus I and II, Discrete Mathematics, Statistics, Linear Algebra and Numerical Methods. As for the mathematics minor, it includes Calculus III, Foundations of Mathematics, Normal Differential Equations, Mathematical Analysis I, Abstract Algebra I and other math courses in the choice of the student.

I feel getting a minor in math is a waste of time. It's because where I live, computer scientists and engineers usually end up in programming jobs, or maintaining computers. So it's very likely that I won't work in the "theoretical" part of computer science, and I "assume" that math is applied more on the theoretical part than programming (or software engineering).

Shall I forget it and pursue other minors, or am I being ignorant about how good it is to study such pair?