Tuesday, December 29, 2015

Static: what are the static variable and the static method?

We have a question here: what are the static variable and the static method? We will see what the static variable is and what the static method is in this post.

Definition


static variables: variables allocated for a class. Data stored in static variables is common for all the instances of that class.
static methods: methods allocated for a class. Static methods are common for all the instances of that class, so you don't need to make an instance to use that static method.

non-static variables:  variables allocated for an instance. Data stored in non-static variables is NOT common for all the instances of that class. The data stored changes its value depending instances even if they are made from a same class.

Static variables


At first, we will see an ordinal code without using static:

public class Test { public static void main(String args[]) { SubTest subtestone = new SubTest(); subtestone.a = 1; subtestone.b = 2; SubTest subtesttwo = new SubTest(); subtesttwo.a = 3; subtesttwo.b = 4; System.out.println(subtestone.a); System.out.println(subtestone.b); System.out.println(subtesttwo.a); System.out.println(subtesttwo.b); } } class SubTest{ int a; // these variables are not static int b; }
the result

The integer-variables "a" and "b" change its values by being assigned values. This is because the variables are allocated for the object, not for the class, thus, the each variable can have a different value every time we make a new object.

Now we will see how static variables work:

public class Test { public static void main(String args[]) { SubTest subtestone = new SubTest(); subtestone.a = 1; subtestone.b = 2; SubTest subtesttwo = new SubTest(); subtesttwo.a = 3; subtesttwo.b = 4; System.out.println(subtestone.a); System.out.println(subtestone.b); System.out.println(subtesttwo.a); System.out.println(subtesttwo.b); } } class SubTest{ static int a; //These variables are static static int b; }

the result

This time, all of the integer-variables "a" and "b" are treated as "3" and "4". This is because the variables are allocated for the class, not for the object, thus, the each variable can NOT have a different value every time we make a new object. Data stored in static variables is common for all the objects( or instances ) of that class. See the result above.

But, needless to say, if these static variables are allocated for the class which has the main method, the variables "a" and "b" change its values as follows:
public class Test { static int a; //These variables are static. static int b; public static void main(String args[]) { a = 1; b = 2; System.out.println(a); System.out.println(b); a = 3; b = 4; System.out.println(a); System.out.println(b); } }

the result


Static variables are allocated for the class, not for the object (or the instance), so even though they are static variables, they change its values depending on what value we assign to the variables.

Static methods

Static methods have same concept as static variables. Static methods are common for all the objects( or instances ) of that class.
At first, we will see an ordinal code without using static:

public class Test { public static void main(String args[]) { SubTest subtestone = new SubTest(); subtestone.showValue("My name is John."); SubTest subtesttwo = new SubTest(); subtesttwo.showValue("My name is Alice."); } } class SubTest{ void showValue(String word){ // This method is not static. System.out.println(word); } }

the result

The method is not static one, so the method is allocated for the object which we've created.

Now we will see how static methods work:
public class Test { public static void main(String args[]) { SubTest.showValue("My name is John."); SubTest.showValue("My name is Alice."); } } class SubTest{ static void showValue(String word){ // This method is static. System.out.println(word); } }

the result is same as the previous one.

The method is static one, so the method is allocated for the SubTest. Therefore, to use the static method, we don't need to make a new object. We can directly access to the static method of SubTest class.


Sunday, December 20, 2015

Constructor

How the constructor works? In C#, all steps inside a constructor are executed at first as you make an object of class.

We will see an example:
using System;

namespace Tester {
    public class Program {
        public static void Main(string[] args) {
            Console.WriteLine("Hello, world!");
            Calc calc = new Calc();
        }
    }

    public class Calc {
        int x;
        int y;
        int z;

        public Calc() {
           x = 5;
           y = 7;
           z = x * y;
           Console.WriteLine(z);
        }
    }
}

the result

We didn't use any method of Calc class in the main method to show the result of the calculation, but the result of this program shows "35" after Hello World.

This is because the Calc class has a constructor which calculates and show the result.

This constructor showed the result, so we didn't need to write any method for the calculation and showing the result. Everytime we make an object of the class, the constructor of the class is executed.

Without the constructor, this program would be as follows:
using System;

namespace Tester {
    public class Program {
        public static void Main(string[] args) {
            Console.WriteLine("Hello, world!");
            Calc calc = new Calc();
            calc.CalcA();
        }
    }

    public class Calc {
        int x;
        int y;
        int z;

        public void CalcA() {
           x = 5;
           y = 7;
           z = x * y;
           Console.WriteLine(z);
        }
    }
}

We can see, in the main method, calc.CalcA (CalcA method of Calc class) is being used.

We can compare how the constructor simplifies the program.

By the way, the constructor always have a same name as the class which contains the constructor. Plus, constructor is used as "void" (returns no value). On the other hand, the method doesn't have a same name as the class which contains the method. The method usually has a different name from the class.

Wednesday, December 16, 2015

break and continue

When you press "q", you can exit the infinite loop in this code:

using System;

class test
{
        static void Main(string[] args)
        {
                char myKey;
                for ( ; ; )
                {
                    // Read one character
                    myKey = (char) Console.Read();
                    if (myKey == 'q') break;
                }
        }
}


"continue" is used inside a loop to skip certain steps as follows:
using System;

class test
    {
        static void Main(string[] args)
        {
            int i = 1, n, sum;

            sum = 0;

            while (i <= 2) {
                n = int.Parse(Console.ReadLine());
                if (n < 0)
                continue;  //If n is less than 0, exit from loop
          
                sum = sum + n;
                i++;
            }
      
            Console.WriteLine("sum = " + sum);
            Console.ReadKey();
        }
    }

Saturday, December 12, 2015

The Product Over All Primes

The Product Over All Primes is  4π2 according to this paper.
http://link.springer.com/article/10.1007%2Fs00220-007-0350-z 
Abstract
We generalize the classical definition of zeta-regularization of an infinite product. The extension enjoys the same properties as the classical definition, and yields new infinite products. With this generalization we compute the product over all prime numbers answering a question of Ch. Soulé. The result is 4π2. This gives a new analytic proof, companion to Euler’s classical proof, that the set of prime numbers is infinite.

If you are interested in this kind of math, 1+2+3+4+.... Wikipedia.en is fun to read.

Multi-threaded programming

We will see how to use the multi-threaded programming in C#. See here to see what the multi-threading is.

the code:
using System;
using System.Threading;

namespace ThreadTest
{
    class Program
    {
        public static void Main() {
                Thread thrd1 = new Thread(new ThreadStart(MyThread.Thread1 ) );
                Thread thrd2 = new Thread(new ThreadStart(MyThread.Thread2 ) );

                thrd1.Start();
                thrd2.Start();
              
                Console.ReadKey(true);
        }
    }
  
    public class MyThread {

        public static void Thread1() {
                for (int i = 0; i < 10; i++) {
                        Console.WriteLine("Thread1 {0}", i);
                }
        }

        public static void Thread2() {
                for (int i = 0; i < 10; i++) {
                        Console.WriteLine("Thread2 {0}", i);
                }
        }
    }
}

To use the multi-threading, you have to make an object of class Thread. In this program, "thrd1" and "thrd2" are the objects that we have made. After making such thread's object, ".Start()" is used to start the thread. In this program, "thrd1.Start();" and "thrd2.Start()" are written to start the threads that we have made.

the result

The each thread works independently, so the result above shows the two threads that we have made are working simultaneously.

In the first program, the thread function (of MyThread class) was static function. But the thread function doesn't need to be static. If we will NOT use the thread function as static, we must make an object of Thread class and use it as follows:

using System;
using System.Threading;

namespace ThreadTest
{
    class Program
    {
        public static void Main() {
                MyThread thrdobj = new MyThread();
          
                Thread thrd1 = new Thread(new ThreadStart(thrdobj.Thread1 ) );
                Thread thrd2 = new Thread(new ThreadStart(thrdobj.Thread2 ) );

                thrd1.Start();
                thrd2.Start();
              
                Console.ReadKey(true);
        }
    }
  
    public class MyThread {

        public void Thread1() {
                for (int i = 0; i < 10; i++) {
                        Console.WriteLine("Thread1 {0}", i);
                }
        }

        public void Thread2() {
                for (int i = 0; i < 10; i++) {
                        Console.WriteLine("Thread2 {0}", i);
                }
        }
    }
}

References

"Multithreaded Programming Using C#", Code project, seen on 12th December 2015

Wednesday, December 2, 2015

Let's make life game 2

We already downloaded Swing designer in the last post. So now we can make an actual GUI application with SwingDesigner.

We will start making life game in this post. 

At first, we will make a display for the game. Start your Eclipse. 
Then make a Java project. Whatever is good for the name. I chose "LifeGame" for the project name.



Then click "Finish". We will see new project "LifeGame" was added to your project explorer.

We will make a new class for the main window. Click "File" from the menu bar and select "New", then "Others".



You will see the following display. Select "WindowBuilder".

Select the "Swing Designer", then"Application Window":

Whatever name is good for this. I wrote "MainWindow" for the name. Then click "OK".


You will see the following class was added to the project. Click "Design" now.

You will see an empty window. We will customize this empty window and make it LifeGame from now on.

Click the play button.


You can see the empty window which you've created is actually working.


Saturday, November 28, 2015

the datagrid and the database

This is a GUI program which I made. By downloading it, you can see how the datagrid and the connection to a database work.

download: https://www.dropbox.com/s/xc1cut65xuzir2l/DatagridTest.zip?dl=0

code: download the file above and see inside the project.
This is a WPF program.



Wednesday, November 25, 2015

DB searcher

You can search a database file (accdb) in this Excel file. But maybe when you use this excel, you will see some warnings (because this file uses ADO to connect to the database). Please read carefully the warnings and enable the connection to the database to use this Excel.

Photo:


Download:
https://www.dropbox.com/s/mskm2h5gvv54bqb/DBsearch.zip?dl=0

Code:
See inside the Excel.

Monday, November 23, 2015

Open and delete a file (incomplete version) (server)

This program is a server program which receives commands from the client. See here for the client.

code:

import java.awt.Desktop;
import java.io.File;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class FileSearchServer{
public static void main (String args[]){
 try {
        // Create a new server socket that listens at port 8080
        ServerSocket ServerSocket1 = new ServerSocket(8080);
        System.out.println("Server is lisenting ... ");
        Socket socket1 = ServerSocket1.accept(); //accept a connection from client on port 8080

        OutputStream outputStream1 = socket1.getOutputStream();
        ObjectOutputStream objectOutputStream1 = new ObjectOutputStream(outputStream1);
        InputStream inputStream1 = socket1.getInputStream();
        ObjectInputStream objectInputStream1 = new ObjectInputStream(inputStream1);

        String rcv_path, send_msg, storewords2;
        String storewords1 = "";

        while(true) {
           // Recieve a message from client
           System.out.println("Waiting for client to respond ... ");
           rcv_path = (String)objectInputStream1.readObject();
           if(rcv_path != null &&  !(rcv_path.startsWith("del ")) && !(rcv_path.startsWith("open "))) {
          System.out.println("From Client : " + rcv_path);
            File file1 = new File(rcv_path);
       File[] files = file1.listFiles();
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US);

        for (int i = 0; i < files.length; i++){
         String mime = "";
        File file = files[i];
        System.out.println((i + 1) + ":    " + file + " *information is sent*");

        Path source = Paths.get(file.getPath());
           mime = Files.probeContentType(source);

        storewords2 = ((i + 1) + ":  " + file + "\nName:  "+ file.getName() + "\nLast modified time:  " + sdf.format(file.lastModified()) + "\nFile size:  " + getKB(file.length()) + " KB" + "\nMime type: " + mime);
        storewords1 = storewords1 + "\n" + storewords2 + "\n";
       }
            }else if( rcv_path != null && rcv_path.startsWith("del ")){
             System.out.println("From Client : " + rcv_path);
             String d_path = "";
             d_path = rcv_path.substring(4, (rcv_path.length()));
             File file1 = new File(d_path);
              if(file1.delete()){
               storewords1 = "Successfully deleted";
              } else{
               storewords1 = d_path + "\nThis file could not be deleted";
              }
            }else if( rcv_path != null && rcv_path.startsWith("open ")){
             System.out.println("From Client : " + rcv_path);
             String o_path = "";
             o_path = rcv_path.substring(5, (rcv_path.length()));
             File file1 = new File(o_path);
             Desktop desktop = Desktop.getDesktop();
             desktop.open(file1);
            }

           // Send a message to client
           System.out.print("\nTo Client : ");
           send_msg = storewords1;
           objectOutputStream1.writeObject(send_msg);
       }
     } catch(Exception e) {
        System.out.println(e);
     }
  }

 private static BigDecimal getKB(long byte1){
  double kbyte1;
  double byte2;

  byte2 = byte1;
  kbyte1 = byte2/1024;

  BigDecimal value = new BigDecimal(kbyte1);
  BigDecimal roundHalfUp1 = value.setScale(2, BigDecimal.ROUND_HALF_UP);

  return roundHalfUp1;
 }
}

Open and delete a file (incomplete version) (client)

This program is a client program which sends commands to the server. See here for the server.

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

public class FileSearchClient {

 public static void main(String args[]) {
       try {
          Socket theSocket = new Socket("write local IP address here", 8080);
          System.out.println("Connected to server");

          InputStream inputStream = theSocket.getInputStream();
          ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
          OutputStream OutputStream = theSocket.getOutputStream();
          ObjectOutputStream objectOutputStream = new ObjectOutputStream(OutputStream);

          BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

          String rcv_msg, send_msg;

          while(true) {
             // Send a message to Server
             System.out.print("To Server : ");
             send_msg = br.readLine();
             objectOutputStream.writeObject(send_msg);

             // Recieve a message from Server
             System.out.println("Waiting for server to respond ... ");
             if((rcv_msg = (String)objectInputStream.readObject()) != null) {
                System.out.println("\nFrom Server : " + rcv_msg);
             }
          }
       } catch(Exception e) {
          System.out.println(e);
       }
    }
 }

Responding program (client)

See here for the server program.

Code:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class MyClient {
   public static void main(String args[]) {
      try {
         Socket theSocket = new Socket("write local IP address here", 8080);
         System.out.println("Connected to server");

         InputStream is = theSocket.getInputStream();
         ObjectInputStream ois = new ObjectInputStream(is);
         OutputStream os = theSocket.getOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(os);

         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

         String rcv_msg, send_msg;
         while(true) {
            // Send a message to Server
            System.out.print("To Server : ");
            send_msg = br.readLine();
            oos.writeObject(send_msg);

            // Recieve a message from Server */
            System.out.println("Waiting for server to respond ... ");
            if((rcv_msg = (String)ois.readObject()) != null) {
               System.out.println("\nFrom Server : " + rcv_msg);
            }
         }
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}

Responding program (server)

This program receives commands from a client and responds certain messages, See here for the client.

Code:

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {
   public static void main(String args[]) {
      try {
         // Create a new server socket that listens at port 8080
         ServerSocket ServerSocket = new ServerSocket(8080);
         System.out.println("Server is lisenting ... ");
         Socket socket1 = ServerSocket.accept();//accept a connection from client on port 8080

         OutputStream outputStream1 = socket1.getOutputStream();
         ObjectOutputStream objectOutputStream1 = new ObjectOutputStream(outputStream1);
         InputStream inPutStream1 = socket1.getInputStream();
         ObjectInputStream objectInputStream1 = new ObjectInputStream(inPutStream1);

         String rcv_msg;
         while(true) {
            /* Recieve a message from client */
            System.out.println("Waiting for client to respond ... ");
            if((rcv_msg = (String)objectInputStream1.readObject()) != null) {
             if(rcv_msg.equals("What is your name?")){
              System.out.println("From Client : " + rcv_msg);
              System.out.print("\nTo Client : ");
                    objectOutputStream1.writeObject("My name is A.\n");
              continue;
             }else if(rcv_msg.equals("Song2")){
              System.out.println("From Client : " + rcv_msg);
              System.out.print("\nTo Client : ");
                    objectOutputStream1.writeObject("Woo-hooWoo-hoo\nWoo-hoo\nWoo-hoo");
              continue;
             }else if(rcv_msg.equals("What food do you like?")){
              System.out.println("From Client : " + rcv_msg);
              System.out.print("\nTo Client : ");
                    objectOutputStream1.writeObject("I like apples.\nWhat do you like to eat?\n");
              continue;
             }else{
              System.out.println("From Client : " + rcv_msg);
              System.out.print("\nTo Client : ");
                    objectOutputStream1.writeObject("Error.\n");
                    System.out.println("From Client : " + rcv_msg);
              continue;
             }
            }
         }
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}

open & delete file (client)

This is a client file. See the server here.

code:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

public class FileSearchClient {

 public static void main(String args[]) {
       try {
          Socket theSocket = new Socket("Write Local IP address here", 8080);
          System.out.println("Connected to server");

          InputStream inputStream = theSocket.getInputStream();
          ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
          OutputStream OutputStream = theSocket.getOutputStream();
          ObjectOutputStream objectOutputStream = new ObjectOutputStream(OutputStream);

          BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

          String rcv_msg, send_msg;

          while(true) {
             /* Send a message to Server */
             System.out.print("To Server : ");
             send_msg = br.readLine();
             objectOutputStream.writeObject(send_msg);

             /* Recieve a message from Server */
             System.out.println("Waiting for server to respond ... ");
             if((rcv_msg = (String)objectInputStream.readObject()) != null) {
                System.out.println("\nFrom Server : " + rcv_msg);
             }
          }
       } catch(Exception e) {
          System.out.println(e);
       }
    }
 }

open & delete file (server)

This server receives commands from a client and deal with files.

code:

import java.awt.Desktop;
import java.io.File;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class FileSearchServer{
public static void main (String args[]){
 try {
        // Create a new server socket that listens at port 8080
        ServerSocket ServerSocket1 = new ServerSocket(8080);
        System.out.println("Server is lisenting ... ");
        Socket socket1 = ServerSocket1.accept(); //accept a connection from client on port 8080

        OutputStream outputStream1 = socket1.getOutputStream();
        ObjectOutputStream objectOutputStream1 = new ObjectOutputStream(outputStream1);
        InputStream inputStream1 = socket1.getInputStream();
        ObjectInputStream objectInputStream1 = new ObjectInputStream(inputStream1);

        String rcv_path, send_msg, storewords2;
        String storewords1 = "";

        while(true) {
           // Recieve a message from client
           System.out.println("Waiting for client to respond ... ");
           rcv_path = (String)objectInputStream1.readObject();
           if(rcv_path != null &&  !(rcv_path.startsWith("del ")) && !(rcv_path.startsWith("open "))) {
          System.out.println("From Client : " + rcv_path);
            File file1 = new File(rcv_path);
       File[] files = file1.listFiles();
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US);

        for (int i = 0; i < files.length; i++){
         String mime = "";
        File file = files[i];
        System.out.println((i + 1) + ":    " + file + " *information is sent*");

        Path source = Paths.get(file.getPath());
           mime = Files.probeContentType(source);

        storewords2 = ((i + 1) + ":  " + file + "\nName:  "+ file.getName() + "\nLast modified time:  " + sdf.format(file.lastModified()) + "\nFile size:  " + getKB(file.length()) + " KB" + "\nMime type: " + mime);
        storewords1 = storewords1 + "\n" + storewords2 + "\n";
       }
            }else if( rcv_path != null && rcv_path.startsWith("del ")){
             System.out.println("From Client : " + rcv_path);
             String d_path = "";
             d_path = rcv_path.substring(4, (rcv_path.length()));
             File file1 = new File(d_path);
              if(file1.delete()){
               storewords1 = "Successfully deleted";
              } else{
               storewords1 = d_path + "\nThis file could not be deleted";
              }
            }else if( rcv_path != null && rcv_path.startsWith("open ")){
             System.out.println("From Client : " + rcv_path);
             String o_path = "";
             o_path = rcv_path.substring(5, (rcv_path.length()));
             File file1 = new File(o_path);
             Desktop desktop = Desktop.getDesktop();
             desktop.open(file1);
            }

           // Send a message to client
           System.out.print("\nTo Client : ");
           send_msg = storewords1;
           objectOutputStream1.writeObject(send_msg);
       }
     } catch(Exception e) {
        System.out.println(e);
     }
  }

 private static BigDecimal getKB(long byte1){
  double kbyte1;
  double byte2;

  byte2 = byte1;
  kbyte1 = byte2/1024;

  BigDecimal value = new BigDecimal(kbyte1);
  BigDecimal roundHalfUp1 = value.setScale(2, BigDecimal.ROUND_HALF_UP);

  return roundHalfUp1;
 }
}

Data input & save & output (using a .txt file)


using System;
using System.Text;
using System.IO;
using System.ComponentModel;
using System.Windows.Forms;

public class Sample2 {
  public static void Main(string[] args) {
        bool isSecond = false;
        bool shouldStop = false;
        string path = "";
        string text = "";

        while(!shouldStop){

        try{
             if(!isSecond){
              Console.WriteLine("Prepare a .txt file to write on.");
              Console.WriteLine("Give me a directory for the .txt file.");
              Console.WriteLine("(Example: C:\\Users\\Documents\\aaa.txt)");
              Console.WriteLine("To stop this program, write [/stop] and hit the enter key.");
              path = Console.ReadLine();
             }
           
             if(path.Equals("/stop", StringComparison.CurrentCultureIgnoreCase)){
               break;
             }

           Encoding enc = Encoding.GetEncoding("Shift_JIS");
           //Shift JIS is for Japanese. Please change here depending on your language.
           StreamReader sr = new StreamReader(path, enc);
           text = sr.ReadToEnd();            

           sr.Close();
         
           Console.WriteLine("\nTo stop this program, write [/stop] and hit the enter key.");
           Console.WriteLine("If you want to open the .txt file, write [/open] and hit the enter key.");
           Console.WriteLine("If you want to check the inside of the ,txt file, write [/view] and hit the enter key.");
           Console.WriteLine("If you want to search for a certain word, write [/search] and hit the enter key");
           Console.WriteLine("Write some words to save in the .txt file:\n");

           StreamWriter writer = new StreamWriter(@path, true, enc);
           string word = Console.ReadLine();

             if(word.Equals("/stop", StringComparison.CurrentCultureIgnoreCase)){
               writer.Close();
               break;
             }else if(word.Equals("/open", StringComparison.CurrentCultureIgnoreCase)){
               writer.Close();
               System.Diagnostics.Process.Start(@path);
             
               isSecond = true;
               Console.WriteLine("Excuted.");
               continue;
             }else if(word.Equals("/search", StringComparison.CurrentCultureIgnoreCase)){
               writer.Close();
               Console.WriteLine("What word do you want to search for?");
               string searchWord = Console.ReadLine();
               Console.WriteLine(searchWord + " is being searched for..");
             
               System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(
               @searchWord,
               System.Text.RegularExpressions.RegexOptions.IgnoreCase);
             
               System.Text.RegularExpressions.Match m = r.Match(text);
             
               int count = 0;
               while (m.Success){
                   count++;
                   m = m.NextMatch();
               }
             
               Console.WriteLine("The word " + searchWord + "appreas " + count + " times in the .txt file.");
               isSecond = true;
               continue;
             }else if(word.Equals("/view", StringComparison.CurrentCultureIgnoreCase)){
                 writer.Close();
                 Console.WriteLine("Saved data: \n" + text + "\n");
                 isSecond = true;
                 continue;
             }    
   
           writer.WriteLine(word);
           Console.WriteLine("Saved");

           writer.Close();
           isSecond = true;
         
           }catch(FileNotFoundException){
             Console.WriteLine("File not found");
            return;
           }catch(Win32Exception){
             Console.WriteLine("File not found");
             return;
           }catch(IOException){
             Console.WriteLine("IOException");
             return;
           }catch(NotSupportedException){
             Console.WriteLine("NotSupportedException");
             return;
           }catch(ArgumentException){
             Console.WriteLine("ArgumentException");
             return;
           }
         }

        Console.WriteLine("Program terminated");
          if(isSecond){  
            Console.WriteLine(".txt file will be opened.");
            System.Diagnostics.Process.Start(@path);
          }
        return;
  }
}

Sun rise


two angels



The original concept is William Adolphe Bouguereau's L'Amour et Psyché, enfants.

a woman who is thinking


a dog


Sunday, November 22, 2015

How to change the format of currency-typed data

With the VBA editor, you can change the format of currency-typed data.

Open up the VBA editor and write as follows:

Sub Test()
Worksheets("Sheet1").Columns("A").NumberFormatLocal = "#,##0 ""RS"""
End Sub

RS is a currency of India. If you execute this macro, all of the data of A-column of Sheet1 will be displayed as follows:
All data of A-column is displayed in this format

If you want to designate a format for the data which are less than 0, write as follows:

Sub Test()
Worksheets("Sheet1").Columns("A").NumberFormatLocal = "#,##0 ""euro"";[Red]#,##0 ""euro"""
End Sub


The two formats are divided by ";". If you excute this macro, all data which are less than 0 is displayed in red:


How to make a GUI program with C#

Today, I will explain how to make a Graphical User Interface (GUI) program with C#. We will make a simple program with a button.

Go to microsoft's website to download for Integrated Development Environment called Visual Studio:
https://www.visualstudio.com/vs/

Visual Studio community version is a free & useful IDE for C#. Please note, Enterprise version and Professional version are not free but only community version is free.
(Actually not only for C#. Visual Studio can be used to develop other language's programs like C, C++, Visual Basic and so on).


After downloading the Visual Studio, start it. You will be asked to log into your Microsoft account. Log in with your information.

After logging in, Start page like below will show up. Choose "File" --> "New" --> "Project".


A window like below will show up now. Choose "Visual C#" --> "WPF application". You can name it as you like, so you can use the default name "WpfApplication1" as it is. I named it as "WpfApplication2" because WpfApplication1 is already existing. By the way, this style of capitalization is called "PascalCasing". See here for the design detail.

Then this window like below will show up. This is the place where you fix and edit your program design.You will define how the program will look like here. We will add a button to our program.


Choose "button" from the toolbox and drag & drop it in the window as follows:


After adding the button, double-click the button on the window.

You will be brought to a window where you write codes for the program. You will define what your program will do. (not for design now!) There are two sections; one is named MainWindow(), and the other is button_click(). "MainWindow()" is a constructor, which is called everytime the program starts, so usually codes for initialization are written here.

Second one "button_click()" is a method. Method is used to define a certain routine that produces a certain return. This is called "Function" in C or C++. This "button_click" method defines what will happen when the button is clicked.

Write "MessageBox.Show("Hello World!!");" inside button_click() method as follows:

MassageBox.Show("Anything to show inside the message box") is also a method, but this method is called from other place of the program and is prepared from the beginning automatically by the visual studio. What you need to do to use this MessageBox.show is just call it like above.

After writing the code, click "Start" from the menu bar.

Then your program will appear....


Click the button at the center. You will see the Message box you defined.




Sunday, November 15, 2015

How to start C# programming

C# is a programming language which is very similar to Java and is useful to make an application which is relating to .NET Framework.
.NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs primarily on Microsoft Windows.-Wikipedia .Net framework
Here we will learn how to prepare for programming with C#.

We suppose that you are using windows 7 OS. At first, we must set the environment variable for C#. Open your explorer then move as follows:
Start --> Computer -->  Windows --> Microsoft.NET --> Framework (if you are using OS 64bit version, choose Framework64) --> (choose the latest version like "v4.0")

Then copy the path as follows:


When you've done copying it, we will move to "Environment Variables" as follows:
Start --> Right-Click on Computer --> Properties --> Advanced system settings --> Environment Variables



Then look for Environment variables and click it.

You will see the following window. If there is an item called "PATH", edit it. If you don't find "PATH", click "new" button and make a item named "PATH" in the user variable pane.
If you've clicked "Edit", add the path of Microsoft.NET's framework which you have copied. Please add ";" in the end of the path unless ";" is already there:
example: ;C:\Windows\Microsoft.NET\Framework64\v4.0.30319
or
C:\Windows\Microsoft.NET\Framework64\v4.0.30319


like this

Then click "OK".

If you've clicked "New", name it as "PATH" then add the path without adding anything. If you've clicked "New", you don't need to put anything in front of the path.
example: C:\Windows\Microsoft.NET\Framework64\v4.0.30319

add this path to Environment Variables.

When you've done this, click "OK".

Now you can use C#'s command on CMD.

We will check if the new environment variable is working. Open your CMD. Then write as follows:
csc
Then push the enter on your physical keyboard.

If you see this Microsoft's message and "warning CS2008"(plus some message) and "error CS1562"(plus some message), that means you've succeeded the environment variable setting.

When you create a C# program, use this "csc" command after moving to the folder which has the .cs file:
csc Sample.cs
Then you can create a .exe file if there aren't any errors in the source file.

To move to the targeted folder, use cd command:
cd C:\Users\Documents\C#

like this

You must be at the folder which contains the targeted C#'s source file to use the csc command, which create the .exe file from the C#'s source file.