Pages

Saturday, June 18, 2016

Java: Calculate if a number is divisible by another number

A number x is divisible by y if the remainder after the division is zero. Write
a program that tests whether one number is divisible by another number. Reads both numbers from the keyboard.

public static void divisible() {

            Scanner kb = new Scanner(System.in);
            System.out.println("Enter the value of x...");
            int x = kb.nextInt();
            System.out.println("Enter the value of y...");
            int y = kb.nextInt();

            if (x % y == 0) {

                  System.out.println(x + " is divisible by " + y);

            } else {

                  System.out.println(x + " is not divisible by " + y);
            }


      }


Code explanation:

public static void divisible(): Here the void we use void method because it won't return, but print a result. 
Scanner kb = new Scanner(System.in): In this program we're going to read two integers from the keyboard. Scanner is used with this objetive. Note: In order to utilize Scanner we need to import the Scanner library. We must include the following line of code:  import java.util.Scanner.

System.out.println("Entrar un numero x..."): System.out.println prints a message though the console. In this case to give instructions to the user. 

int x = kb.nextInt(): Here we declare the variable x as an int, which is equals to the variable kb that we declared in Scanner.  nextInt() means it is going to take the next Integer value the user enter through the keyboard and is going to be stored at the variable x.

Then we repeat the code for variable y.

if (x % y == 0): In order to get the remainder from the division between two numbers we use the Mod method. In Java it is represented by the percentage sign (%).

The rest of the code prints if either x is divisible by y or no.


Monday, June 1, 2015

Visual Basic 6.0 Traffic lights

This program is going to simulate a  real traffic light at an interval of three seconds. 




In order to do this program we will need to insert 4 Shapes, 3 circles and 1 rectangle. 


To change the Shape's form we'll go to Properties > Shape 



Now to change the color of the Shapes you just need to go to Shape > Properties > Fill Style and change it to Solid.   



Then go to Properties > FillColor and choose the desire color. 



You will need to insert a Timer and assign it a value of 3000 in the Interval attribute which means 3 seconds. In order to do that you go to Properties > Interval and type 3000. 



The following is the whole program code: 



Private Sub Form_Load()
Shape2.Visible = True
Shape1.Visible = False
Shape3.Visible = False
End Sub

Private Sub Timer1_Timer()
If Shape1.Visible Then

Shape2.Visible = True
Shape1.Visible = False
Shape3.Visible = False

ElseIf Shape2.Visible Then

Shape3.Visible = True
Shape2.Visible = False
Shape1.Visible = False

Else

Shape1.Visible = True
Shape2.Visible = False
Shape3.Visible = False

End If

End Sub

Note: It is necessary that the names of my Objects such as the Shapes and Timer be the same as yours in order to the program to work.


Monday, July 21, 2014

Prime numbers in Visual Basic 6.0

Prime numbers as other classifications of natural numbers were classified by Pythagoras and his sect, whose members were called Pythagoreans-.

This program will result in the prime numbers from a value to another that we specify.

For the form we'll need 2 textbox (txtFrom and txtTo). Two labels, one listbox (lstResult) and 1 commandbutton (cmdCalculate). As shown in the right image.

In the calculate button insert the following code:





Option Explicit

Dim d, h, v, a, b, c As Integer


Private Sub cmdCalculate_Click()

If Val(txtFrom.Text) < Val(txtTo.Text) Then
lstResult.Clear

d = Val(txtFrom.Text)
h = Val(txtTo.Text)
v = d - 1

Do While v < h
v = v + 1

'Identificar si el numero es primo
a = 0
b = 1


Do While b <= v
c = v Mod b

If c = 0 Then
a = a + 1
b = b + 1

Else
b = b + 1
End If

Loop

If a = 2 Or v = 1 Then

lstResult.AddItem (v)
End If
Loop

Else
MsgBox ("The value of From must be greater tha the value of To")
End If

txtFrom.Text = ""
txtTo.Text = ""
txtFrom.SetFocus

End Sub



Image: Rest up, little Pikachu! by xThunderbolt








Saturday, May 25, 2013

C#: Convert from decimal to binary



The following program will convert a decimal number (base 10) into it's binary representation (base 2).
To achieve it we need to create:
2 textboxes called txt_dec and txt_bin
1 button called btn_calculate  



En el botón btn_calcular digitar el siguiente codigo:


           
                int dec, bin;
                string out = "";
                dec = Convert.ToInt16(txt_dec.Text);
 

                while (dec > 0)
                {

                    bin = dec % 2;
                    dec = dec / 2;
                    Convert.ToString(bin);
                    out = bin + out;
                    txt_dec.Text = Convert.ToString(out);

                }

                txt_dec.Focus();



Code explanation:

int dec, bin: We declate the variable dec and bin Integer type.

string out = "": We declare the variable out type string which we'll assign the value 'nothing'.

dec = Convert.ToInt16(txt_dec.Text): Here we assign to the dec variable the textbox txt_dec value, at the same time we convert the textbx to Integer type.

while (dec > 0): While the variable dec be greater than 0 then ...

bin = dec % 2: The variable bin will get the value of the operation: the variable dec value % 2. (% means Mod in C#). The Mod is used to obtain a division residue. The division will be between the number we indicate next to the symbol %, this case the number 2, because 2 is the binary numbers base.

dec = dec / 2: After to obtain the first residue the variable dec will get it's own value between 2.

Convert.ToString(bin): We convert the variable bin into String type to achieve the concatenation.

out = bin + out: The variable "out" is going to get the bin's value  (which contain the division residue) concatenated with the same variable "out" to keep accumulating the values of the others residues that generates while the "WHILE" runs.

txt_bin.Text = Convert.ToString(out):Finally we assign to the textbox txt_bin, the value of the variable "out".


Monday, May 20, 2013

JavaScript form validation

This is an example of a form validation using JavaScript. First we create a form in HTML, with the fields Name, Last name and Telephone y two buttons Validate and Clear. We'll assign to each of these HTML elements an id to identify them in the JavaScript code with their respective names.


Ex:
<form>
<label>Name:</label>
<input type="text" id="name" name="name" size="20" autofocus="autofocus" /><br/>
<label>LastName:</label>
<input type="text" id="lastname" name="lastname" /><br/>
<label>Telephone:</label>
<input type="text" id="telephone" name="telephono" /><br/>
<input type="button" value="Validate" id="boton_validate" />
<input type="reset" value="Clear" />
</form>


Then bellow the form we write the JS code:


<script type="text/javascript">

function validate() {
    var name= document.getElementById("name");
    var lastname= document.getElementById("lastname");
    var telephone= document.getElementById("telephone");

    if (name.value.trim() == "") {
        name.focus();
        return alert("There is an empty element");
    } else {
        if (lastname.value.trim() == "") {
            lastname.focus();
            return alert("There is an empty element");
        } else {
            if (telephone.value.trim() == "") {
                telephone.focus();
                return alert("There is an empty element");
            }
        }
    }

}

document.getElementById("validate_button").onclick = validate;

</script>

Code explanation: 

First we create the "validate" function, on it the code that this will return.
We assign to JS variables the HTML inputs. Ex: var name = document.document.getElementById("name");

We ask if the JS variables values are empty then we send the focus to the corresponding input (name.focus();) and we send to screen the message (return alert("There is an empty element");)

Finally we decide that the validate button's name (this case "validate_button", identified by its id in HTML ), the event "onclick" returns "validate" that is the function's name.

Note: The function trim() is used to eliminate white spaces in the begging and ending of a string.

Definitely the full code will look like this:



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>
<head>
<title>JavaScript Form Validation</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>


<body bgcolor="#FFFFFF">

<hr />
<h2> JavaScript form validation </h2>
<hr />
&nbsp;

<form>
<label>Name:</label>
<input type="text" id="name" name="name" size="20" autofocus="autofocus" /><br/>
<label>LastName:</label>
<input type="text" id="lastname" name="lastname" /><br/>
<label>Telephone:</label>
<input type="text" id="telephone" name="telephone" /><br/>
<input type="button" value="Validate" id="validate_button" />
<input type="reset" value="Clear" />
</form>

<script type="text/javascript">

function validate() {
    var name= document.getElementById("name");
    var lastname= document.getElementById("lastname");
    var telephone= document.getElementById("telephone");

    if (name.value.trim() == "") {
        name.focus();
        return alert("There is an empty element");
    } else {
        if (lastname.value.trim() == "") {
            lastname.focus();
            return alert("There is an empty element");
        } else {
            if (telephone.value.trim() == "") {
                telephone.focus();
                return alert("There is an empty element");
            }
        }
    }

}

document.getElementById("validate_button").onclick = validate;


</script>


</body>
</html>



Sunday, May 19, 2013

Calculate the Area of a Rectangle in DFD


DFD is a simple flowchart editor and simulator program.

To calculate the area of a rectangle is implement the formula a = b * h. Where a is the area, b is the base and h, the height. To run this program we'll use the program DFD. You can download it from hereNote: The software language is Spanish.

First the variables "b" and "h" will be read, as shown in the right image, in a Read object.

Then we'll assign to the "a" constant the resulting value of the operation "b * h". In an Assign object.

Finally in an Output object the value of "a" will be printed.


Multiplication table in Visual Basic 6.0


This program works by inserting a number to a TextBox and when press the "Multiply" button the table multiplication of that number from 1 to 12 is going to appear in the ListBox. In order to do that we're going to user 1 TextBox, 1 Listbox and 1 CommandButton, as shown bellow.



















To make this program works we have to tape the following code in your CommandButton, this case called Command1:


Private Sub Command1_Click()

List1.Clear
Dim n As Integer
n = 0
Do While n < 12
n = n + 1
r = Val(Text1.Text) * n
List1.AddItem (Text1.Text & " x " & n & " = " & r)
Loop
Text1.Text = ""
Text1.SetFocus

End Sub


Now explain the code above:

List1.Clear: This is going to, each time the code runs, clean the Listbox.

Dim  n as Integer: Here we declare the variable "n" which stores Integer values.

n= 0: Here we give to the variable "n" the value 0. This way we initialize this variable which must have a value to use the Do While.

Do While n < 12: Here we say while the variable "n" be less than 12 run the code between the Do While and the Loop.

n= n+1: This code will make you add 1 to the variable "n". This way the variable "n" that had a value of 0 is going to plus 1 while the value of "n" be less than 12.

r = Val(Text.Text) * n: "r" es the constant where the value of the multiplication will be stored, the order represents the operation. 

List1.AddItem (Text1.Text & " x " & n & " = " & r): This part is where literally we say to the program to add to the Listbox the value of the TextBox, the letter "x", the value of the variable "n", the = sign and the value of the variable "r". What we are doing here is concatenating the variables and the multiplication signs. The & sign is used in VB 6.0 to concatenate.

Loop: In case of failure to comply the condition settled in the Do While it retuns back, when the condition is met then the Do While ends. 

Text1.Text = "": This will, each time we press the Multiply button, the TextBox value gets clean. 

Text1.SetFocus: Return the cursor to the Text1. 

If we insert the number 2 to the Textbox then this will be the result.