定义一个StringBuffer类对象, 然后向对象中添加26个小写的英文字母, 要求逆序的方式输出, 并且删除前5个字符.
public static void main(String[] args) {
StringBuffer buf = new StringBuffer();
for (int i = 'a'; i <= 'z'; i++) {
buf.append((char)i);
}
buf.reverse();
buf.delete(0, 5);
System.out.println(buf);
}
利用Random类产生5个1~30之间(包含1和30)的随机数
class randomNumber {
private static Random random = new Random();
public static int [] create(int len) {
int data [] = new int [len];
int foot = 0;
while(foot < data.length) {
int num = random.nextInt(30);
if (num != 0) {
data[foot++] = num;
}
}
return data;
}
}
public class JavaAPIDemo {
public static void main(String[] args) {
int result [] = randomNumber.create(5);
System.out.println(Arrays.toString(result));
}
}
输入一个email地址, 使用正则表达式验证该Email地址是否正确
class Validator {
public static boolean isEmail(String email) {
if (email == null || email.equals("")) {
return false;
}
String regex = "\\w+@\\w+\\.\\w+";
return email.matches(regex);
}
}
public class JavaAPIDemo {
public static void main(String[] args) {
String email = "w_ww@yund.com";
System.out.println(Validator.isEmail(email));
}
}
编写程序, 用0~1之间的随机数来模拟扔硬币实验, 统计扔1000次后出现的正面反面的次数并输出
class Coin {
private int front; // 正面出现的次数
private int back; // 反面出现的次护士
private Random random = new Random();
public void throwCoin(int num) {
for (int i = 0; i < num; i++) {
int temp = random.nextInt(2);
if (temp == 0) {
this.front++;
} else {
this.back++;
}
}
}
public int getFront() {
return this.front;
}
public int getBack() {
return this.back;
}
}
public class JavaAPIDemo {
public static void main(String[] args) {
Coin coin = new Coin();
coin.throwCoin(1000);
System.out.println(coin.getBack());
System.out.println(coin.getFront());
}
}
编写正则表达式, 判断给定的是否是一个合法的ip ip第一位可能是1-2,可能没有, 且每一段不高于255
class Validator {
public static boolean isIP(String ip) {
if (ip == null || "".equals(ip)) {
return false;
}
String regex = "([1-2]?[0-9]?[0-9]\\.){3}([1-2]?[0-9]?[0-9])";
if (ip.matches(regex)) {
String result[] = ip.split("\\.");
for (int i = 0; i < result.length; i++) {
int temp = Integer.parseInt(result[i]);
if (temp > 255) {
return false;
}
}
} else {
return false;
}
return true;
}
}
public class JavaAPIDemo {
public static void main(String[] args) {
String ip = "192.168.2.2";
System.out.println(Validator.isIP(ip));
}
}