Friday, June 28, 2013

Jave 24: h7-h10 (Java)

1) ternary operator

int x = ( y > 5 ) ? 1 : 2 ;

2) Class Calendar in java.util : class Clock

import java.util.*;

class Clock {

public static void main(String[] arg) {
// get current time and date
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int month = now.get(Calendar.MONTH) + 1;
int day = now.get(Calendar.DAY_OF_MONTH);
int year = now.get(Calendar.YEAR);

// display greeting
if (hour < 12) {
System.out.println("Good morning.\n");
}
else if (hour < 17) {
System.out.println("Good afternoon.\n");
}
else {
System.out.println("Good evening.\n");
}

// begin time message by showing the minutes
System.out.print("It’s");
if (minute != 0) {
System.out.print(" " + minute + " ");
System.out.print( (minute != 1) ? "minutes" : "minute");
System.out.print(" past");
}

// display the hour
System.out.print(" ");
System.out.print( (hour > 12) ? (hour - 12) : hour );
System.out.print(" o’clock on ");

// display the name of the month
switch (month) {
case 1:
System.out.print("January");
break;
case 2:
System.out.print("February");
break;
case 3:
System.out.print("March");
break;
case 4:
System.out.print("April");
break;
case 5:
System.out.print("May");
break;
case 6:
System.out.print("June");
break;
case 7:
System.out.print("July");
break;
case 8:
System.out.print("August");
break;
case 9:
System.out.print("September");
break;
case 10:
System.out.print("October");
break;
case 11:
System.out.print("November");
break;
case 12:
System.out.print("December");
}

// display the date and year
System.out.println(" " + day + ", " + year + ".");
}
}

3) break: class TargetLoop


public class TargetLoop {

public static void main(String[] args) {
int points = 0;
int target = 100;
//target loop
targetLoop:
while (target <= 100) {
for (int i = 0; i < target; i++) {
if (points > 50){
break targetLoop;
}
points = points + i;
System.out.print(points + " ");
}
}
// System.out.println(i); //i doesn't exist now.
System.out.println("\n"); //comment this line to see difference
// Complex for Loop
for (int i = 0, j = 0; i * j < 50; i++, j += 2) {
System.out.println(i + " * " + j + " = " + (i * j));
}
//empty section
int i=6; 
for ( ; i < 8; i++) {
System.out.println(i);
}
}
}

4) System.curentTimeMillis() & .substring(begin, end): class Benchmark (test how fast is your computer)

public class Benchmark {

public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long endTime = startTime + 60000;
long index = 0;
while (true) {
@SuppressWarnings("unused")
double x = Math.sqrt(index);
long now = System.currentTimeMillis();
if (now > endTime) {
break;
}
index++;
}
String strIndex = String.valueOf(index);
// output the index in more readable style
int len = strIndex.length();
int t = (int) Math.floor(len/3);
int m = (int) (len % 3);
if (t == 0){
System.out.print(index);
}
else{
for (int i = 1; i < t+2; i++){
if (i == 1){
if (m!=0){
System.out.print(strIndex.substring(0,m)+"_");
}
}
else if (i == t+1) {
System.out.print(strIndex.substring(m+(i-2)*3,m+(i-1)*3));
}
else{
System.out.print(strIndex.substring(m+(i-2)*3,m+(i-1)*3)+"_");
}
}
}
System.out.println(" loops in one minute.");
}

}

 5) Arrays

default value of variable:
numeric = 0;
char = '\0';
boolean = false;

.toCharArray(): change a string to a char array (class SpaceRemover)
.sort(): sort a array (class Name)

public class SpaceRemover {

public static void main(String[] args) {
String mostFamous = "Rudolph the Red-Nosed Reindeer";
char[] mfl = mostFamous.toCharArray();
for (int dex = 0; dex < mfl.length; dex++) {
char current = mfl[dex];
if (current != ' ') {
System.out.print(current);
else {
System.out.print('.');
}
}
System.out.println();
}
}
import java.util.*;

public class Name {

public static void main(String[] args) {
String names[] = { "Lauren", "Audrina", "Heidi", "Whitney",
"Stephanie", "Spencer", "Lisa", "Brody", "Frankie",
"Holly", "Jordan", "Brian", "Jason" };
System.out.println("The original order:");
for (int i = 0; i < names.length; i++) {
System.out.print(i + ": " + names[i] + " ");
}
Arrays.sort(names);
System.out.println("\nThe new order:");
for (int i = 0; i < names.length; i++) {
System.out.print(i + ": " + names[i] + " ");
}
System.out.println();
}

}

 6) Casting

One type of variable that cannot be used in any casting is Boolean values.
.intValue() and .parseInt(String)

class Wheel and class NewRoot
Integer suffix = new Integer(5309);
int newSuffix = suffix.intValue();
public class Wheel {

public static void main(String[] args) {
String phrase[] = {
"A STITCH IN TIME SAVES NINE",
"DON'T EAT YELLOW SNOW",
"JUST DO IT",
"EVERY GOOD BOY DOES FINE",
"I WANT MY MTV",
"I LIKE IKE",
"PLAY IT AGAIN, SAM",
"FROSTY THE SNOWMAN",
"ONE MORE FOR THE ROAD",
"HOME FIELD ADVANTAGE",
"VALENTINE'S DAY MASSACRE",
"GROVER CLEVELAND OHIO",
"SPAGHETTI WESTERN",
"AQUA TEEN HUNGER FORCE",
"IT'S A WONDERFUL LIFE"
};
int[] letterCount = new int[26];
for (int count = 0; count < phrase.length; count++) {
String current = phrase[count];
char[] letters = current.toCharArray();
for (int count2 = 0; count2 < letters.length; count2++) {
char lett = letters[count2];
if ( (lett >= 'A') & (lett <= 'Z') ) {
letterCount[lett - 'A']++;
}
}
}
for (char count = 'A'; count <= 'Z'; count++) {
System.out.print(count + ": " +
letterCount[count - 'A'] +
" ");
}
System.out.println();
}
 public class NewRoot {

public static void main(String[] args) {
int number = 100;
if (args.length > 0) {
number = Integer.parseInt(args[0]);
}
System.out.println("The square root of "
+ number
+ " is "
+ Math.sqrt(number) );
}

}

Wednesday, June 26, 2013

Java 24: h1-h6 (Java)

1)Java Programs including: 

1.1) application: main()
1.2) applets: init() and paint()
import java.awt.*;

public class RootApplet extends javax.swing.JApplet{

int number;

public void init(){
number = 225;
}

public void paint(Graphics screen){
Graphics2D screen2D = (Graphics2D) screen;
screen2D.drawString("The square root of " + number +                " is " + Math.sqrt(number), 10, 50);
}

}

2) int

final int TOUCH = 6; //TOUCH is a constant

int x = 3;
int y = x++ *10; // y = 30, x =4

int x = 3;
int y = ++x *10;// y =40, x=4

int z = 0b0000_1101; // z =13 

3) String

You can insert several special characters into a string in this manner. The
following list shows these special characters; note that each is preceded by
a backslash (\).
\’ Single quotation mark
\” Double quotation mark
\\ Backslash
\t Tab
\b Backspace
\r Carriage return
\f Formfeed
\n Newline


public class Test{
public static void main(String[] args) {
String i = "'c'";
i += 1;
i = i.toUpperCase();
i = i.toLowerCase();
System.out.println(i);
System.out.println(i.length());
System.out.println(i.equals("'c'1"));
System.out.println(i.indexOf("c"));
}
}
'c'1
4
true
1

Saturday, June 22, 2013

Eclipse 中EGit的一些问题 (GitHub)

1) 比较好的中文Git 教程,为Git Tutorial翻译版本

2) 使用eclipse的Egit连接github的问题。

$ sudo apt-get install git-core git-gui git-doc

How to Setup and Use Github in Ubuntu

If you ran into a message "Could not open a connection to your authentication agent." when type ssh-add, it must be that you don't have settings for ssh-agent.
$ ssh-agent
SSH_AUTH_SOCK=/var/folders/sx/5z2568ss68997plzhw6qympw0000gn/T//ssh-9ikR207fRO4n/agent.64887; export SSH_AUTH_SOCK;
SSH_AGENT_PID=64888; export SSH_AGENT_PID;
echo Agent pid 64888;
Then you have to set it up. If you type ssh-agent, it prints like the above.
$ eval `ssh-agent`
$ ssh-add
Identity added: /your/home/.ssh/id_rsa (/your/home/.ssh/id_rsa)

SSH原理与运用(一):远程登录

五、公钥登录
使用密码登录,每次都必须输入密码,非常麻烦。好在SSH还提供了公钥登录,可以省去输入密码的步骤。
所谓"公钥登录",原理很简单,就是用户将自己的公钥储存在远程主机上。登录的时候,远程主机会向用户发送一段随机字符串,用户用自己的私钥加密后,再发回来。远程主机用事先储存的公钥进行解密,如果成功,就证明用户是可信的,直接允许登录shell,不再要求密码。
这种方法要求用户必须提供自己的公钥。如果没有现成的,可以直接用ssh-keygen生成一个:
  $ ssh-keygen
运行上面的命令以后,系统会出现一系列提示,可以一路回车。其中有一个问题是,要不要对私钥设置口令(passphrase),如果担心私钥的安全,这里可以设置一个。
运行结束以后,在$HOME/.ssh/目录下,会新生成两个文件:id_rsa.pub和id_rsa。前者是你的公钥,后者是你的私钥。
这时再输入下面的命令,将公钥传送到远程主机host上面:
  $ ssh-copy-id user@host
好了,从此你再登录,就不需要输入密码了。
如果还是不行,就打开远程主机的/etc/ssh/sshd_config这个文件,检查下面几行前面"#"注释是否取掉。
  RSAAuthentication yes
  PubkeyAuthentication yes
  AuthorizedKeysFile .ssh/authorized_keys
然后,重启远程主机的ssh服务。
  // ubuntu系统
  service ssh restart
  // debian系统
  /etc/init.d/ssh restart

Some tips of Eclipse (Eclipse)

1) avoiding “resource is out of sync with the filesystem”

Enable this in Preferences - General - Workspace - Refresh Automatically (called Refresh using native hooks or polling in newer builds)

2) 更改eclipse(myeclipse) author的默认名字 --- 修改MyEclipse eclipse 注释的作者
在eclipse/myeclipse中,当我们去添加注释的作者选项时,@author 后边一般都会默认填充的你登录计算机的用户名。如何去修改呢:
方法一:修改计算机登录的用户名(99.9999%的人应该都不愿意去这样做,特别是一些公司的域帐户登录的电脑根本就改不了)。
方法二:将 @author 属性写死 。
通过菜单 Window->Preference 打开参数设置面板,然后选择:
1.Java -> Code Style -> Code Templates
2.在右侧选择Comments,将其中的Types项,然后选右边的"Edit",进入编辑模式,将 @author ${user} 中的${user}改成你自己的名字即可。
----我也曾经这改过,咸麻烦。
方法三:修改ini配置文件。
在eclipse/myeclipse的目录下找到eclipse.ini/myeclipse.ini文件,在-vmargs后边添加上启动参数:-Duser.name=你想要显示的名字。
重启eclipse/myeclipse搞定。

Friday, June 21, 2013

Most useful plugins for Eclipse (Eclipse)

1) JUnit
http://www.vogella.com/articles/JUnit/article.html

1.1. Project preparation
Create a new source folder test. For this right-click on your project, select Properties and choose the Java Build Path . Select the Source tab.
Press the Add Folder button, afterwards press the Create New Folder button. Create the test folder.
The result is depicted in the following sceenshot.
(Alternatively you can add a new source folder by right-clicking on a project and selecting New → Source Folder.)
1.2. Creating JUnit tests
You can write the JUnit tests manually but Eclipse supports the creation of JUnit tests via wizards.
For example to create a JUnit test or a test class for an existing class, right-click on your new class, select this class in the Package Explorer view, right-click on it and select New → JUnit Test Case.
Alternatively you can also use the JUnit wizards available under File → New → Other... → Java → JUnit.
(Wizard for creating test suites
To create a test suite in Eclipse you select the test classes which should be included into this in the Package Explorerview, right-click on them and select New → Other... → JUnit → JUnit Test Suite.)
1.3. Running JUnit tests
To run a test, select the class which contains the tests, right-click on it and select Run-as → JUnit Test. This starts JUnit and executes all test methods in this class.
Eclipse provides the Alt+Shift+X, ,T shortcut to run the test in the selected class. If you position the cursor on one method name, this shortcut runs only the selected test method.
To see the result of an JUnit test, Eclipse uses the JUnit view which shows the results of the tests. You can also select individual unit test in this view, right-click them and select Run to execute them again.
1.4. JUnit Content Assists
(JUnit uses static methods and Eclipse cannot always create the corresponding static import statements automatically.)
You can make the JUnit test methods available via the Content AssistsContent Assists is a functionality in Eclipse which allows the developer to get context sensitive code completion in an editor upon user request.
Open the Preferences via Window → Preferences and select Java → Editor → Content Assist → Favorites.
Use the new New Type button to add the org.junit.Assert type. This makes for example the assertTrue,assertFalse and assertEquals methods directly available in the Content Assists.

2) EGit
在Eclipse里使用github的插件

3) Checkstyle 4) Window Builder5) VisualVM

6)Umbrello
For UML diagrams

7)Ant