`
Mr_Chunlei
  • 浏览: 28728 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

Java实现乘法表,switch注意事项,if判断,判断字符串中文个数

 
阅读更多

一、Java乘法表考察的是循环,我们只要使用简单的循环嵌套即可完成,实现代码一如下:

package com.hello;
public class TreeParser {

	public static void main(String[] args){
		for(int i = 1; i <= 9;i++){
			for(int j = 1;j <= i;j++){
				System.out.print(j+"*"+i+"="+i*j+"\t");
			}
			System.out.println();
		}
	}
	
}
运行结果如下:

1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81

二、使用switch中default是当寻找不到匹配的时候执行,而当default提前时,也是需要break 来使其终止,否则会出现:

package com.hello;
public class TreeParser {

	public static void main(String[] args){
		char a = 'b';
		switch(a){
		default: 
			a = 'c';
			System.out.println(a);
		case 'c': System.out.println(a);
		}
	}
	
}

执行结果:

c
c
三、使用if条件

package com.hello;
public class TreeParser {

	public static void main(String[] args){
		boolean flag = false;
		if(flag = true){
			System.out.println(flag);
		}else{
			System.out.println(flag);
		}
	}
	
}

运行结果:

true

四、判断字符串中中文字符的个数

package com.hello;

public class TreeParser {
	
	/**
	 * 利用了转化为Byte后每个汉字可以转化为两个负数
	 * @param args
	 */
	public static void main(String[] args){
		String s = "you are so beautiful that 我非常喜欢你";
		byte[] b = s.getBytes();
		int k = 0;
		for(int i = 0;i < b.length;i++){
			//System.out.print(b[i]+" ");用于显示转化后的数组
			if(b[i] < 0){
				k++;
			}
		}
		//System.out.println();
		System.out.print("\""+s+"\"含有"+k/2+"个中文");
	}
	
}

运行结果如下:

//121 111 117 32 97 114 101 32 115 111 32 98 101 97 117 116 105 102 117 108 32 116 104 97 116 32 -50 -46 -73 -57 -77 -93 -49 -78 -69 -74 -60 -29 
"you are so beautiful that 我非常喜欢你"含有6个中文




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics