Wednesday, September 30, 2015

Right triangle and Circle calculator

This macro calculates "Area of a circle" and "Diameter" if you put a value in "Radius" box and choose "circle" in the combo-box. If you choose "Right triangle" in the combo-box and put a value of Base and Height, this calculates the Area and the length of the third-leg.



Interface is like this. The code is below.
------------------------
Private Sub UserForm_Initialize()

TextBox1.Value = 0
TextBox2.Value = 0
TextBox3.Value = 0
TextBox4.Value = 0

Label1.Font.Size = 8
Label2.Font.Size = 8
Label3.Font.Size = 8
Label4.Font.Size = 8

Label1.Caption = ""
Label2.Caption = ""
Label3.Caption = ""
Label4.Caption = ""

With ComboBox1
        .AddItem ("Circle")
        .AddItem ("Right Triangle")
End With


End Sub

Private Sub CommandButton1_Click()
Dim NumPi As Double
NumPi = Application.WorksheetFunction.Pi()

If ComboBox1.Value = "Right Triangle" Then
Label1.Caption = "Base"
Label2.Caption = "Height"
Label3.Caption = "Area"
Label4.Caption = "Third leg"

    If Not IsNumeric(TextBox1.Value) Or Not IsNumeric(TextBox2.Value) Or Not IsNumeric(TextBox3.Value) Or Not IsNumeric(TextBox4.Value) Then
        MsgBox "Enter only numbers in the boxes. Spaces make an error also."
        TextBox1.Value = 0
        TextBox2.Value = 0
        TextBox3.Value = 0
        TextBox4.Value = 0
    End If
 
    If TextBox1.Value = 0 Or TextBox2.Value = 0 Then
        MsgBox "Base and height are both essential to calculate the area and the third leg."
        TextBox1.Value = 0
        TextBox2.Value = 0
        TextBox3.Value = 0
        TextBox4.Value = 0
    End If

    If Not TextBox1.Value = 0 Or Not TextBox2.Value = 0 Then
        TextBox3.Value = CDbl(TextBox1.Value * TextBox2.Value * 0.5)
        TextBox4.Value = CDbl(Sqr(TextBox1.Value * TextBox1.Value + TextBox2.Value * TextBox2.Value))
    End If
End If

If ComboBox1.Value = "Circle" Then
    TextBox4.Value = 0
        Label1.Caption = "Radius"
        Label2.Caption = "Diameter"
        Label3.Caption = "Area"
        Label4.Caption = ""

    If Not IsNumeric(TextBox1.Value) Or Not IsNumeric(TextBox2.Value) Or Not IsNumeric(TextBox3.Value) Then
        MsgBox "Enter only numbers in the boxes. Spaces make an error also."
        TextBox1.Value = 0
        TextBox2.Value = 0
        TextBox3.Value = 0
    End If

    If Not TextBox1.Value = 0 Then
        TextBox2.Value = CDbl(TextBox1.Value * 2)
        TextBox3.Value = CDbl(TextBox1.Value * TextBox1.Value * NumPi)
    ElseIf Not TextBox2.Value = 0 Then
        TextBox1.Value = CDbl(TextBox2.Value / 2)
        TextBox3.Value = CDbl((TextBox2.Value / 2) * (TextBox2.Value / 2) * NumPi)
    ElseIf Not TextBox3.Value = 0 Then
        TextBox1.Value = CDbl(Math.Sqr(TextBox3.Value / NumPi))
        TextBox2.Value = CDbl(Math.Sqr(TextBox3.Value / NumPi) * 2)
    End If
End If


End Sub

Private Sub CommandButton2_Click()

TextBox1.Value = 0
TextBox2.Value = 0
TextBox3.Value = 0
TextBox4.Value = 0

End Sub

FTP program in Java

This program receives a local file path and upload it. I used Jsch library to make this program, so if you want to use this program, you must download Jsch.jar file, then save the Jsch somewhere and set a classpath for the Jsch.jar file. This is difficult...But if you are using Eclipse, it is easy to set a classpath for an external library. Check here.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Locale;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SFTPinJava {
public SFTPinJava() {

}

public static void main(String[] args) {
 String SFTPHOST = "your host";
 int SFTPPORT = portnumber;
 String SFTPUSER = "user_name";
 String SFTPPASS = "password";
 String SFTPWORKINGDIR = "location";

 Session session = null;
 Channel channel = null;
 ChannelSftp channelSftp = null;

 try{
   System.out.println("Enter the local path of the file which you want to upload:");

    BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
    String str = input.readLine( );

         System.out.println("Your file's local path is: " + str);

   JSch jsch = new JSch();
   session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
   session.setPassword(SFTPPASS);
   java.util.Properties config = new java.util.Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);
   session.connect();
   channel = session.openChannel("sftp");
   channel.connect();
   channelSftp = (ChannelSftp)channel;
   channelSftp.cd(SFTPWORKINGDIR);
   File f = new File((str));
   channelSftp.put(new FileInputStream(f), f.getName());

   SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.JAPAN);

   System.out.println("File transfered successfully to host.");
   System.out.println("Name: " + f.getName());
   System.out.println("Path: " + f.getPath());
   System.out.println("File size: " + (getKB(f.length())) + "KB");
   System.out.println("Extension: " + getSuffix(f.getName()));
   System.out.println("File last Modified time: " + sdf.format(f.lastModified()));
  }catch(Exception ex){
  ex.printStackTrace();
  }
 }

  private static String getSuffix(String fileName) {
   if (fileName == null)
         return null;
      int point = fileName.lastIndexOf(".");
      if (point != -1) {
          return fileName.substring(point + 1);
      }
      return fileName;
  }

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

   kbyte1 = byte2/1024;
   return kbyte1;
  }
}

Receive a word and read a text file and count how many times the word appears in the text file

This is a sample code which receives a word and read a text file and count how many times the word appears in the text file. If you are using Mac, this program might make an error because it uses .useDelimiter("\\r\\n").

import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; class ScanTwo{ public static void main(String args[]){ try{ System.out.println("Input a path of the file:"); BufferedReader input = new BufferedReader (new InputStreamReader (System.in)); String str1 = input.readLine( ); System.out.println("Your file's local path is: " + str1); File file = new File(str1); Scanner scan = new Scanner(file); scan.useDelimiter("¥¥r¥¥n"); System.out.println("Input a word:"); BufferedReader input2 = new BufferedReader (new InputStreamReader (System.in)); String str3 = input2.readLine( ); System.out.println("Your word is: " + str3); int count = 0; while(scan.hasNext()) { String str2 = scan.next(); Pattern pattern1 = Pattern.compile(str3); Matcher m = pattern1.matcher(str2); while (m.find()) { count++; } } scan.close(); System.out.println(count); }catch(FileNotFoundException e){ System.out.println(e); }catch(Exception ex){ ex.printStackTrace(); } } }

Let me explain the detail. This program scans from the command line by this code:

BufferedReader input =  new BufferedReader (new InputStreamReader (System.in));
String str1 = input.readLine( );

This makes "input" object and the content of the input is substituted to the variable str1. That's why

  System.out.println("Your file's local path is: " + str1);

this shows what the content of str1...which means this shows the input.
  File file = new File(str1);
  Scanner scan = new Scanner(file);
  scan.useDelimiter("¥¥r¥¥n");
The "File" is a file class. I made an object "file" from the File class. This File class and the object are used to deal with files in Java. "scan" is an object of Scanner class. This "scan.useDelimiter("¥¥r¥¥n");" is written to designate a delimiter and separate the data.
  BufferedReader input2  = new BufferedReader (new InputStreamReader (System.in));
  String str3 = input2.readLine( );
This is written to scan again from the command line.. to designate a word to search.




and...
  while(scan.hasNext()) {
    String str2 = scan.next();
    Pattern pattern1 = Pattern.compile(str3);
        Matcher m = pattern1.matcher(str2);
         while (m.find()) {
             count++;
         }
      }
This is the most difficult part. This repeat a same action as long as there is something to scan in the file (see the condition of while statement). str3 is a word which was input from the command line.

In this program, str2 stores "scan.next". scan is an object of Scanner class. This scan data between one delimiter and the other delimiter.  If there is a word which matches the word str3 inside the words str2, m.find becomes "true". When m.find is true, count adds 1 to itself.

That's why when the variable "count" is displayed, we can see how many times the words appeared in the text file.


Monday, September 28, 2015

Simple calculator

This is a simple calculator. You enter numbers to calculate, then you can choose a operator for the calculation as follows:

To make the UserFom with Excel VBA, you must make a interface as follows:
The box at the top is TextBox1. The box at the second top is TextBox2. The box at the bottom is TextBox3. Others are a combo-box and a button.

The code is below:
------------------------------------------------------------------------------
Dim NumResult As Double

Private Sub TextBox1_Change()

If IsNumeric(TextBox1.Value) = False Then
TextBox1.Value = ""
End If

End Sub

Private Sub TextBox2_Change()

If IsNumeric(TextBox2.Value) = False Then
TextBox1.Value = ""
End If

End Sub

Private Sub UserForm_Initialize()
TextBox1.SetFocus
TextBox2.SetFocus


ComboBox1.AddItem "+"
ComboBox1.AddItem "-"
ComboBox1.AddItem "/"
ComboBox1.AddItem "multiply"
 
TextBox3.Value = NumResult

End Sub
Private Sub CommandButton1_Click()
Dim Num1 As Double
Dim Num2 As Double

Num1 = TextBox1.Value
Num2 = TextBox2.Value

If ComboBox1.Value = "+" Then
        NumResult = Num1 + Num2
        TextBox3.Value = NumResult
ElseIf ComboBox1.Value = "-" Then
    NumResult = Num1 - Num2
    TextBox3.Value = NumResult
ElseIf ComboBox1.Value = "/" Then
    TextBox3.Value = (Num1 / Num2)
ElseIf ComboBox1.Value = "multiply" Then
    NumResult = Num1 * Num2
    TextBox3.Value = NumResult
End If


End Sub


VBA sample code Prime number checker

This is a sample code to make a user form which checks if the number is prime or not. If you enter a number in the above box, it checks if it is a prime number. Open the Excel and make a UserFom as follows:

Note that you don't need to write "TextBox1" and "TextBox2" inside the boxes. I wrote them inside to make it easy to understand. Then write a code as follows:
-------------------------------------------------------------------------------
Private Sub UserForm_Initialize()

TextBox1.SetFocus
TextBox2.Value = "Enter a number above"

End Sub

Private Sub CommandButton1_Click()
If Not IsNumeric(TextBox1.Value) Then
    TextBox2.Value = "Enter only numbers."
    Exit Sub
End If

If IsPrime(CLng(TextBox1.Value)) Then
    TextBox2.Value = "This is a prime number."
ElseIf Not IsPrime(CLng(TextBox1.Value)) Then
    TextBox2.Value = "This is not a prime number."
End If

End Sub

Function IsPrime(ByVal number As Long) As Boolean

    If number > 3 Then
        If number Mod 2 = 0 Then Exit Function
        If number Mod 3 = 0 Then Exit Function
    End If
 
    Dim divisor As Long
    Dim increment As Long
    Dim maxDivisor As Long
 
    divisor = 5
    increment = 2

    maxDivisor = Sqr(number) + 1
 
    Do Until divisor > maxDivisor
        If number Mod divisor = 0 Then Exit Function
        divisor = divisor + increment

        increment = 6 - increment
    Loop
 
    IsPrime = True
 
End Function

Thursday, September 24, 2015

String

String is a date type. Words are stored in String type data, like "Hello" "John Micheal Cane" "I like the pizza". We will see how to use this String data type.
We have some String datas in the range A1 to A7,

Sub TestForEach()
Dim HumanName As String

HumanName = Range("A1").Value
Range("A1").Offset(, 1).Value = LCase(HumanName)
Range("A1").Offset(, 2).Value = UCase(HumanName)

End Sub

This makes the name John Dow Upper case and Lower case.



For Each

For Each variable In collection

Next variable

As the code for the For Each loop, For Each is used when you do something with Each item stored in that variable.


If you want to replace the space with hyphen and write the names in this way "John-Dow", For Each statement comes in handy.

Sub TestForEach()
Dim MyCell As Variant

For Each MyCell In Range("A1:A7")

    MyCell.Value = Replace(MyCell.Value, " ", "-")

Next MyCell

End Sub

The variable for For Each statement must be declared as variant. This For each statement replaces all spaces " " in the name with a hyphen "-". Names will be written with hyphens like John-Dow.


For loop

In this section, we will learn For loop. For loop is an operation which repeats a same operation, so you don't need to write a long code if you can the loop. Here is the example of loop.

Sub LoopExample()

    Dim StartNumber As Integer
    Dim EndNumber As Integer

    EndNumber = 5

    For StartNumber = 1 To EndNumber

        MsgBox StartNumber

    Next StartNumber

End Sub

If you run this code, you will see "MsgBox StartNumber" is executed 5 times. This is the loop. Note that every time it is looped, the variable StartNumber is added 1. This is looped as long as the condition is satisfied. The condition is "To EndNumber" now and EndNumber is 5 here, so this is executed until the StartNumber becomes 5.

If you want to don't want to add any number to StartNumber every time it is looped, write "Step 0" as follows:

   For StartNumber = 1 To EndNumber Step 0

        MsgBox StartNumber

    Next StartNumber

It executes the loop without adding any number. The problem is the condition  for stopping the loop is never satisfied because StartNumber never become 5 if you don't add any number to StartNumber. If you want to stop this infinite loop after mistakenly executing it, press "control" and "pause break" on your keyboard.

If you want to add 2 to StartNumber every time it is looped, write "Step 2" in the same way.
Negative number is possible, too. If you write "Step -1", it decreases the StartNumber ever time it is looped.

Note that you must initialize the StartNumber in the for loop statement.

   For StartNumber = 1 To EndNumber Step 0

        MsgBox StartNumber

    Next StartNumber

Even if you initialize the variable outside of the for loop statement, it makes an error when you compile the code. You must initialize the variable inside the for loop statement.

With for loop statement, we can add every number between 1 and 100. This operation would be very hard without using for loop statement.

Sub LoopExample()

    Dim StartNumber As Integer
    Dim EndNumber As Integer
    Dim Result As Integer

    EndNumber = 100

    For StartNumber = 1 To EndNumber

        Result = Result + StartNumber

    Next StartNumber

MsgBox Result

End Sub

This add all numbers between 1 and 100.

If you want to see what is happening during the addition, we can change the code a little.

Sub LoopExample()

    Dim StartNumber As Integer
    Dim EndNumber As Integer
    Dim Result As Integer
    Dim counter As Integer

    EndNumber = 100

    For StartNumber = 1 To EndNumber

        Result = Result + StartNumber
        counter = counter + 1
        Cells(counter, 1).Value = Result

    Next StartNumber

End Sub

This writes the value of "Result" variable in the A column (ie, A1, A2, A3...) every time the loop is executed.


Tuesday, September 22, 2015

Range and Resize

We have learned how to use Offset method in the previous section. In this section, we learn how to use Resize method. Resize method enables us to resize the range of selected cells. For example, if we write the code as follows:

Sub TestSub

Range("A1").Resize(2,2).Select

End Sub

This macro selects the cells A1 to B2. Note that (2,2) cell is B2, which is equal to the parameter of Resize method.

Sub TestSub()

Range("A1").Resize(3, 2).Select

End Sub

This selects the cells A1 to B3. As we see above, when the property of the Range object is A1, Resize method with the parameter (3,2) (which is equal to B3) makes a selecting range A1 to B3.

Note that, if we write similar thing with the Offset method,

Sub TestSub

Range("A1").Offset(3,2).Select

End Sub

This would selects the cell C3. Offset method just moves a selecting cell or range to a new location, while Resize method makes a new range.


Range and Offset

We have learned how Range object works. Offset method can be used for the object to move the range to somewhere else.

For example, we consider of selecting a range A1 at first.

Sub TestSub()

Range("A1").Select

End Sub

This Sub selects the A1 cell. Then we move this cell to E5 using Offset method.

Sub TestSub()

Range("A1").Offset(4,4).Select

End Sub

We run the macro and see what happens. Running this code, can you see that the selecting on the A1 cell moved to E5 cell? (Maybe it would be easier to do this by making a button for this macro)

This is the offset. You can move the location of the cell which you are selecting. Not only a single cell, you can designate multiple cells to move with the Offset method.

Sub TestSub()

Range("A1:D5").Offset(4,1).Select

End Sub

This macro moves the location of the range from (A1:D5) to (B5:E9) because it moves like (A+1 1+4:D+1:5+4).

You can use also negative numbers like this.

Sub TestSub()

Range("E7").Offset(-4,-3).Select

End Sub

This would move to B3 cell.


Button

In the previous section, we learned how to write codes with VBA Editor. But to active the macro on the spread sheet, we must click Macro on the developer tool bar, which is un-useful. Now we learn how to run a macro using a button on a spread sheet.

At first, we register a macro with the VBA editor. Open up the VBA editor from the developer tool bar by clicking Visual Basic on the developer tool bar.

the images cited from home and learn.

On the coding window, we write as follows:

Sub TestSub

Range(ActiveCell, "D6").Select

End Sub

We save this macro. Then we will try to use this macro from a button which we will create now. Note that ActiveCell represents the cell on which your cursor currently is. Needless to say, Range represents a range. Range(ActiveCell, "D6") represents a range "Active cell" to D6. If you write as Range("A1:D6") or Range("A1","D6"), it represents a range A1 to D6.

After the dot, a verb Select is written. This is a method which enables us to select certain cells. Thus, if we run this code, this macro selects the range of cells Active cell to D6.

Now we have written codes and made a macro. Now we will make a button on the spread sheet. Click the Excel icon to go back to the spread sheet.
the image cited from home and learn.

 Go see the developer bar of the spread sheet. On the Control panel of the bar, you try to find Insert item. Click Insert, then click the rectangular thing on the list.
the image cited from home and learn.

Then move your mouse to the spread sheet. Pressing the left mouse button, you can draw a rectangular which will be a button which we will use for the macro.

As you let your go of the left mouse button, a dialogue box appears. This dialogue box is used to assign a macro to a button. Assign the macro TestSub which we've created just now to the button.
Now you have a button which says "Button 1"on the spread sheet.

Then right-click on the button and we will see a list of some items. Click Edit Text from the list.
the image cited from home and learn.

You can change the name now. Change the name "Button 1" to "TestSub" to make it easier to see what the button is.
the image made by myself

Now we have the button which runs the macro we've created. Clicking the button, you will see the range Active cell to D6 gets selected.

References

Home and Learn, accessed 22nd September 2015.







Write codes

If you want to write codes for Excel with VBA, enable the developer tool bar, then see the developer tool bar on the Ribbon.
the image: cited from HomeLearn. Though "stop recording" is being selected on the photo, click the Visual Basic to open the Visual Basic Editor. 

By clicking the Visual Basic on left of the bar, you can open the Visual Basic Editor on which you can write codes for Excel. 
the image: cited from HomeLearn.

If you want to save the macro for only Sheet1, open the folders of VBAProject (Book1) and click sheet1 as being shown on the photo. In case you want to use this macro every time you open the Excel, you click VBA project (Personal.exlb) and save there, but we will save the macro only for sheet1 this time, so we will save it here.

Now we will writes codes here. On the coding window on right, write "Sub Range_A1_D6()". This is the name of the Sub. Then we press Enter on keyboard. Then "End Sub" will automatically appears at the last line.
the image: cited from HomeLearn.
Now we will write how the program actually works in between Sub and End Sub. Write there as follows:
the image: cited from HomeLearn.

Range is the object with properties A1 and D6. Select is a method. This codes means "select the cells of a range A1 to D6." From the menu bar at the top, click File then Save Book 1.

When we do this, we might get a message saying this file can not be saved. Excel can't save Macros in a file that end in xlxs. In that case, click the "Save As Type" dropdown list and, from the list, select Excel Macro-Enabled Workbook(*.xlsm). After changing the file to xlsm, we can save the file without error message now. 





References

Home Learn "Excel VBA programming" accessed on 22nd September 2015.

Methods

For example, there is Quit method.

Application.Quit

Sometimes it's difficult to see if it's a method or a parameter because they are written at same place. One way to see if it's a method or not is to see whether the word is a verb or not. If the word is just a noun, it would be a parameter. While if the word is a verb, it would be a method.

Another example is Add method. Here is an example.

Worksheets.Add After:=Worksheets(1)

This is an object "Worksheets". The method is Add. We will see the detail of method later, but this is how method is used.




Dot notation

I don't know how to explain the Dot notation completely. So I will explain it with examples. For example, we consider of a cellphone. We can notate it like this.

phone

This is the object. From the cellphone, you can gain a lot of information. Now we try to gain the information of some phone number.

phone.phonenumber

We've added the property of phone number to the phone object.

Now we suppose that we want to use the property "phone number" as "2120000000" because this is your girlfriend's number which we want to manipulate here.

phone.phonenumber = "2120000000"

Now we have an object "phone" and the property "phonenumber", and the value "2120000000" for the property.

If we wanted to call someone with the cellphone, now we must use the phone. It is called doing a method.

phone.call

Method can come with parameters. With parameters, we can set the detail of the method. Maybe a parameter of the call method would be WhoToCall.

phone.call WhoToCall:=MOM

Note that there is a space between the method (call) and the parameter (WhoToCall), while there is no space between the equal sign and the value (MOM).

We might need more parameters for the call method. For example, we might have a VideoCall parameter and a IsSkypeCall parameter.

phone.call WhoToCall:=MOM VideoCall:=No IsSkypeCall:=No

To separate these parameters, we put a space between the 3 parameters.

Back to the Excel VBA. In the VBA programming we mainly use these "object," "method" and "parameter." For example, there is an object called ActiveCell which is cell where your cursor is currently is. We can use the ActiveCell object in the same way.

ActiveCell.Font

This shows the property "Font" of ActiveCell. Fonts have a name property all of their own. To reach to the information of the name property, place a dot after Font property, then type the Name property.

ActiveCell.Font.Name

A property needs a value, so now we set "Times New Roman" for the value of the property.

ActiveCell.Font.Name = "Times New Roman"

Now the font of the cell where your cursor is currently is is set to "Times New Roman." That is to say, this sets "Times New Roman" to be the font of the ActiveCell.

We can also set a bold value for the Font:

ActiveCell.Font.Bold = True


REFERENCES

HomeLearn "Dot notation" accessed on 22nd September 2015.

Monday, September 21, 2015

Primarity test for long integer

Result

class Test{
    public static void main(String args[]){
    display(44);
    display(5);
    display(46487);
    display(99557865459558797l);
    }

   private static void display(long Num){
         if( isPrimeNum( Num ) ) {
            System.out.println( Num + " is a prime number." );
         } else{
            System.out.println( Num +" isn't a prime number.");
         }
      }

   private static boolean isPrimeNum( long x ) {
         if( x == 2 )
         return true;

         if( x < 2 || x % 2 == 0 )
         return false;

         for( long a = 3; a <= Math.sqrt((double)x); a += 2 )
             if( x % a == 0 )
             return false;
    
   return true;
   }
 }

Primality test

In this class, I am using "display()" method which displays whether the number is a prime number. Note that method is different from object though it seems similar a little.

----------------------------------------------------------------------------
class Test{
    public static void main(String args[]){
    display(44);
    display(5);
    display(46487);
    display(97247);
    }

   private static void display(int Num){
         if( isPrimeNum( Num ) ) {
            System.out.println( Num + " is a prime number." );
         } else{
            System.out.println( Num +" isn't a prime number.");
         }
      }

   private static boolean isPrimeNum( int x ) {
         if( x == 2 )
         return true;

         if( x < 2 || x % 2 == 0 )
         return false;

         for( int a = 3; a <= Math.sqrt((double)x); a += 2 )
             if( x % a == 0 )
             return false;
 
   return true;
   }
 }
----------------------------------------------------------------------------

Primality test and make a list of the prime numbers

public class PrimeNum {
    final static int MIN = 100, MAX = 500; /*Enter the max integer and the minimum integer here*/

    //Primarity test on x
    static boolean isPrimeNum( int x ) {
        if( x == 2 ) return true;
        if( x < 2 || x % 2 == 0 ) return false;
        for( int n = 3; n <= Math.sqrt((double)x); n += 2 )
            if( x % n == 0 ) return false;
        return true;
    }
    public static void main( String[] args ) {
        int cnt = 0;

        System.out.println( Prime numbers between "MIN+" and "+MAX );
        for( int n = MIN; n <= MAX; n++  ) {
            if( isPrimeNum( n ) ) {
                System.out.print( n + " " );
                if( ++cnt%5==0 ) System.out.println();
            }
        }
    }
}

Primality test for long integer

class Primaritytest{
    final static long n = 99557865459558797l;

    static boolean isPrimeNum( long x ){
        if( x == 2 )
        return true;

        if( x < 2 || x % 2 == 0 )
        return false;

        for( int n = 3; n <= Math.sqrt((double)x); n += 2 )
        if( x % n == 0 )
        return false;

        return true;
    }

    public static void main( String[] args ) {
       if( isPrimeNum( n ) ) {
           System.out.println( n + " is a prime number." );
           } else{
           System.out.println( n +" is not a prime number.");
           }
    }
}

BMI calculator

import java.util.Scanner;

public class BMI {
    public static void main(String[] args){

        Scanner input = new Scanner(System.in);

        double weight = 0.0;
        double height = 0.0;
        double bmi = 0.0;

        System.out.print("Enter your weight in pounds: ");
        weight = input.nextInt();

        System.out.print("Enter your height: ");
        height = input.nextInt();

        bmi = ((weight * 703)/(height * height));

        System.out.printf("Your BMI is %f\n", bmi);

        System.out.println("BMI VALUES");
        System.out.println("Underweight: Under 18.5");
        System.out.println("Normal: 18.5-24.9 ");
        System.out.println("Overweight: 25-29.9");
        System.out.println("Obese: 30 or over");
     }
    }

Return characters in uppercase

---------------------------------------------
class Returnuppercase {
   public static void main(String[] args) {
       String hi = "hello world!";
       System.out.println(hi);
       String upper = hi.toUpperCase();
       System.out.println(upper);
   }
}
---------------------------------------------


Question from Codingbat:
Given a string, return a new string where the last 3 chars are now in upper case. If the string has less than 3 chars, uppercase whatever is there. Note that str.toUpperCase() returns the uppercase version of a string. answer:


---------------------------------------------
public String endUp(String str) {
    int cut = str.length() - 3;

    if(str.length() > 2) {
        String front = str.substring(0, cut);
        String back  = str.substring(cut, str.length());
        return front + back.toUpperCase();
    }

    return str.toUpperCase();
}
---------------------------------------------

Use two layouts for one flame

Result: BorderLayout at the center and Flowlayout at the south.


import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.FlowLayout;

public class BorderLayoutTest2 extends JFrame{

  public static void main(String[] args){
    BorderLayoutTest2 frame = new BorderLayoutTest2();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(10, 10, 300, 200);
    frame.setTitle("Practice");
    frame.setVisible(true);
  }

  BorderLayoutTest2(){
    JButton button1 = new JButton("NORTH");
    JButton button2 = new JButton("CENTER");
    JButton button3 = new JButton("SOUTH");
    JButton button4 = new JButton("WEST");
    JButton button5 = new JButton("EAST");
    JButton button6 = new JButton("NEW");
    JButton button7 = new JButton("NEW");

     JPanel p1 = new JPanel();
     p1.setLayout(new BorderLayout());

      p1.add(button1, BorderLayout.NORTH);
      p1.add(button2, BorderLayout.CENTER);
      p1.add(button3, BorderLayout.SOUTH);
      p1.add(button4, BorderLayout.WEST);
      p1.add(button5, BorderLayout.EAST);

    JPanel p2 = new JPanel();
    FlowLayout flayout = new FlowLayout();
    flayout.setAlignment(FlowLayout.LEFT);
     p2.setLayout(flayout);
     p2.add(button6);
     p2.add(button7);

    getContentPane().add(p1, BorderLayout.CENTER);
    getContentPane().add(p2, BorderLayout.SOUTH);
  }
}

Caluculater

You need "Swing" to run this program.

import javax.swing.*;
import java.awt.event.*;
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;

class CalcSample extends JFrame{
private static final long serialVersionUID = 1L;
BorderLayout borderLayout1 = new BorderLayout();
JPanel contentPane = new JPanel();
JTextField result = new JTextField("");
double stackedValue = 0.0;
boolean isStacked = false;
boolean afterCalc = false;
String currentOp = "";

  public static void main(String args[]){
 CalcSample frame = new CalcSample("Calculator");
 frame.setVisible(true);
 }

  CalcSample(String title){
 contentPane.setLayout(borderLayout1);
 setTitle(title);
 setSize(250, 350);
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 setContentPane(contentPane);

 contentPane.add(result, BorderLayout.NORTH);

 JPanel keyPanel = new JPanel();
 keyPanel.setLayout(new GridLayout(4, 4));
 contentPane.add(keyPanel, BorderLayout.CENTER);

 keyPanel.add(new NumberButton("7"), 0);
 keyPanel.add(new NumberButton("8"), 1);
 keyPanel.add(new NumberButton("9"), 2);
 keyPanel.add(new CalcButton("÷"), 3);
 keyPanel.add(new NumberButton("4"), 4);
 keyPanel.add(new NumberButton("5"), 5);
 keyPanel.add(new NumberButton("6"), 6);
 keyPanel.add(new CalcButton("×"), 7);
 keyPanel.add(new NumberButton("1"), 8);
 keyPanel.add(new NumberButton("2"), 9);
 keyPanel.add(new NumberButton("3"), 10);
 keyPanel.add(new CalcButton("-"), 11);
 keyPanel.add(new NumberButton("0"), 12);
 keyPanel.add(new CalcButton("."), 13);
 keyPanel.add(new CalcButton("+"), 14);
 keyPanel.add(new CalcButton("="), 15);

 contentPane.add(new ClearButton(), BorderLayout.SOUTH);
   }


 public void appendResult(String c) {
  if (!afterCalc)
   result.setText(result.getText() + c);
  else {
   result.setText(c);
   afterCalc = false;
  }
 }


 public class NumberButton extends JButton implements ActionListener {
  private static final long serialVersionUID = 1L;

  public NumberButton(String keyTop) {
   super(keyTop);
   this.addActionListener(this);
  }

  public void actionPerformed(ActionEvent evt) {
   String keyNumber = this.getText();
   appendResult(keyNumber);
  }
 }


 public class CalcButton extends JButton implements ActionListener {
  private static final long serialVersionUID = 1L;

  public CalcButton(String op) {
   super(op);
   this.addActionListener(this);
  }

  public void actionPerformed(ActionEvent e) {
   if (isStacked) {
    double resultValue = (Double.valueOf(result.getText()))
      .doubleValue();
    if (currentOp.equals("+"))
     stackedValue += resultValue;
    else if (currentOp.equals("-"))
     stackedValue -= resultValue;
    else if (currentOp.equals("×"))
     stackedValue *= resultValue;
    else if (currentOp.equals("÷"))
     stackedValue /= resultValue;
    result.setText(String.valueOf(stackedValue));
   }
   currentOp = this.getText();
   stackedValue = (Double.valueOf(result.getText())).doubleValue();
   afterCalc = true;
   if (currentOp.equals("="))
    isStacked = false;
   else
    isStacked = true;
  }
 }


 public class ClearButton extends JButton implements ActionListener {

  private static final long serialVersionUID = 1L;

  public ClearButton() {
   super("C");
   this.addActionListener(this);
  }

  public void actionPerformed(ActionEvent evt) {
   stackedValue = 0.0;
   afterCalc = false;
   isStacked = false;
   result.setText("");
  }
 }
}

Calculater-like number inputer (can not calculate)

This calculater-like number inputer can not calculate but can display numbers which you enter. Maybe you can customize it to a better application. You need "Swing" to run this program.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Sample1 extends JFrame{
private static final long serialVersionUID = 1L;

JPanel contentPane = new JPanel();
BorderLayout borderLayout1 = new BorderLayout();
JTextField result = new JTextField("");


 public static void main(String args[]){
 Sample1 frame = new Sample1("Practice window.");
 frame.setVisible(true);
 }

 Sample1(String title){
        contentPane.setLayout(borderLayout1);
 setContentPane(contentPane);
 setTitle(title);
 setSize(new Dimension(250, 300));
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 contentPane.add(result, BorderLayout.NORTH);

 JPanel keyPanel = new JPanel();
 keyPanel.setLayout(new GridLayout(4, 3));
 contentPane.add(keyPanel, BorderLayout.CENTER);

 keyPanel.add(new NumberButton("7"), 0);
 keyPanel.add(new NumberButton("8"), 1);
 keyPanel.add(new NumberButton("9"), 2);
 keyPanel.add(new NumberButton("4"), 3);
 keyPanel.add(new NumberButton("5"), 4);
 keyPanel.add(new NumberButton("6"), 5);
 keyPanel.add(new NumberButton("1"), 6);
 keyPanel.add(new NumberButton("2"), 7);
 keyPanel.add(new NumberButton("3"), 8);
 keyPanel.add(new NumberButton("0"), 9);
 keyPanel.add(new JButton("Calc"), 10);

 contentPane.add(new JButton("C"), BorderLayout.SOUTH);
 setVisible(true);
   }

    public void appendResult(String c) {
  result.setText(result.getText() + c);
   }

public class NumberButton extends JButton implements ActionListener {
  private static final long serialVersionUID = 1L;

  public NumberButton(String keyTop) {
   super(keyTop);
   this.addActionListener(this);
  }

  public void actionPerformed(ActionEvent evt) {
   String keyNumber = this.getText();
   appendResult(keyNumber);
  }
 }
}

Java's sample code: Prime number test

This code examines if the number which you entered is a prime number.

Recoding a macro

In this section, we will learn how to record a macro and see what codes the macro has. At first, we will record a simple macro that right aligns text in a cell. Enter the letters A to F in the A column of Excel:
the image: cited from HomeLearn

On the developer tab, see the Code panel click Record Macro.
the image: cited from HomeLearn

Then the Record Macro dialogue box will appear as following:
the image: cited from HomeLearn

We will name it TestMacro. Choose and click the Personal Macro Workbook then OK. Now the recording begins.
the image: cited from HomeLearn

Select the cells A1 to A6. Click on the Home tab on the Excel ribbon. See the Alignment panel and click the right-align option:

these images: cited from HomeLearn

Now see the coding wondow. You will find a new object (the recorded macro) on the white area on left. The new object is called Personal.XLSB. Click the plus symbol to expand the entry and you'll see some folders. Expand these as well:
the image: cited from HomeLearn

Double click Module1 and you will find the code of the macro which you have just recorded,
the image: cited from HomeLearn

To use this recorded macro, see the developer tab and find Macros. Click Macros and choose the macro you have added and click it.
the image: cited from HomeLearn. Though "stop recording" is being selected on the photo, choose Macros to use the macro that you've added.


Note that such a sub of macro which is created by recording tend to have uselessly long code. Uselessly long code takes uselessly long time to run. To make a short and efficient code for a Sub of  macro, we must write the code by ourselves.

References

Home Learn "Excel VBA programming" accessed on 21st September 2015.

Development Environment

See the developer tab which we added, then click the Visual Basic button. It enables us to open up the VBA Editor in Excel. Note that there are a few other ways to open it up. We use this way anyway for a while.
the image: cited from HomeLearn

Seeing the display, we notice that there is an area on the left named as Project - VBA Project. The white area show all the object that your project currently has (you don't need to what the object is).  By default, there are three Sheet objects: Sheet1, Sheet2, and Sheet3 which correspond with the Excel worksheets.

The fourth thing called ThisWorkBook refers to the workbook where all your current macros are.
Note that, if we record a macro, Personal Macro Workbook appears (which is not visible above yet). We can use Personal Macro Workbook to store macros that you use quite frequently.

There is nothing on the grey area because we don't have any any coding window yet. Double click the sheet1 on left, then we will see that a window appears, which is the coding window. We will writes all codes on this coding window,

the image: cited from HomeLearn

Because we double-clicked the sheet1 and opened the coding window, the codes written on this coding window affect only "sheet1" worksheet. likewise, if we want to add codes which affect sheet2, we must double-click the sheet2 and open the coding window.

As a practice, we will write a program. We don't need to what the code means now. Add the following in the white area for Sheet1:
Sub HelloWorld() 
MsgBox "Hello VBA World!" 
End Sub
This simple program displays "Hello World".
the image: cited from HomeLearn

There is a blue word "Sub" at first line of the program, which corresponds with "End Sub". Sub is short for Subroutine, which is just a chunk of code that does a particular job. End Sub represents an end of the code chunk. The code chunk, Sub, needs a name followed by a pair of round brackets. Note that we can have anything you like as a name for your Sub. Though other coders wouldn't like it, you can even name it "donuts" or "banana."

In between "Sub" and "End Sub", we write actual codes for the Sub.

Once we write a code, we can run the code. Have a look at the tool bar above, then we will find a run button which seems like a play button of a video player.
Click it and we can run the code. Another way to run your code is to click the Run menu. From the Run menu, select Run Sub/User Form.

The MsgBox "" on the code stands for Message Box. We can display things which is in between double quotes.

The code we have added is supposed to display this message,


References

Home Learn "Excel VBA programming" accessed on 21st September 2015.

Preparation: How to Add the Developer Toolbar to Excel

To get prepared make Macro with Excel, you must change the setting of Excel. If you are using Excel 2007, click the round Office button, then click Excel Options at the bottom. On the "Popular" pane, you will find the check box "Show developer tab in the Ribbon." Please check the box.

the image:cited from Home learn
If you check the box, now you can use the developer tab in the Ribbon. Now see the developer tab in the Ribbon, then you will see Macro Security on the Code panel. Click it and Select the option for Enable all macros. Then make sure that "Trust access to the VBA object model" is checked.

References

Home Learn "Excel VBA programming" accessed on 21st September 2015.