第四/五章
1.编写Java程序,判断x是奇数还是偶数
代码如下:
// An highlighted block
package exercise;
public class decide1 {
static int x=5;
public static void main(String[] args) {
// TODO Auto-generated method stub
if(x%2==1) {
System.out.println("x为奇数");
}else {
System.out.println("x为偶数");
}
}
}
2.编写Java程序,用for循环打印棱形
代码如下:
// An highlighted block
public class exercise {
public static void main(String[] args) {
//System.out.println("\n"+"//");
//int l=4;//定义斜边长度
for(int i=1;i<=4;i++) {
for(int j=4;j>i-1;j--) {
System.out.print(" ");
}
//System.out.println("/");
for(int k=1;k<=i;k++) {
System.out.print("* ");
}
System.out.println();
}//上半部分
for(int i=1;i<=3;i++) {
for(int j=3;j>=3-i;j--) {
System.out.print(" ");
}
for(int k=1;k<=4-i;k++) {
System.out.print("* ");
}
System.out.println();
}//下半部分
}
3.编写java程序,使用while循环计算1+1/2!+…+1/20!
// An highlighted block
public class exercise {
public static void main(String[] args) {
int N=20;
int i=1;
double sum=0;
while(i<=N) {
int temp=1;
int j=1;
while(j<=i) {
temp=temp*j;
j++;
}
sum=sum+(double)1/temp;
i++;
}
System.out.println(sum);
}
}
4.使用String类的toUpperCase()方法和toLowerCase()方法来实现大小写的转换
String str=new String("Yao Li you dian lan");
String str1=str.toLowerCase();
String str2=str.toUpperCase();
System.out.println(str1);
System.out.println(str2);
5.分别截取字符串str1和字符串str2中的部分内容。如果截取后的两个子串相同(不区分大小写)输出相同,否则输出不同
public static void main(String[] args) {
String str1=new String("Yao Li ke ai you shan liang");
String str2=new String("Yao Li piao liang you cong ming");
int size1=str1.length();
int size2=str2.length();
String str3=str1.substring(7, size1);
String str4=str2.substring(7, size2);
String str5=str3.toLowerCase();
String str6=str4.toLowerCase();
boolean tp=(str5==str6);
if (tp==false) {
System.out.println("不同");
}else {
System.out.println("相同");
}
//System.out.println(tp);
// System.out.println(str2);
}
6.使用正则表达式来判断字符串text是否为合法的手机号
public static void main(String[] args) {
String str1=new String("text");
String tel="\\d{11,}";
if (str1.matches(tel)) {
System.out.println(str1+"是电话号码");
}else {
System.out.println(str1+"不是电话号码");
}
}
7.使用字符串生成器,将字符串str追加1~10这10个数字
public static void main(String[] args) {
//String str1=new String("yao li zhen piao liang");
StringBuilder builder=new StringBuilder("yao li you dian xiao dai meng");
for(int i=1;i<=10;i++) {
builder.append(i);
}
System.out.println(builder);
}