11 JavaAPI之lang的几个小程序
/*写一个方法统计出一个字符串中,数字的个数、空格的个数、 小写英文字母的个数、大写英文字母的个数等。*/ class Census { String str; int num ; int chs ; int upcase ; int lowcase ; public Census() {} public Census(String str) { this(); this.str = str; } public int GetChar(){ char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { if (Character.isLetter(ch[i])) { chs++; }; } return chs; } public int GetNum(){ char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { char c = ch[i]; if (Character.isDigit(ch[i])) { num++; }; } return num; } public int GetUpCase(){ char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { char c = ch[i]; if (Character.isUpperCase(ch[i])) { upcase++; }; } return upcase; } public int GetLowCase(){ char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { char c = ch[i]; if (Character.isLowerCase(ch[i])) { lowcase++; }; } return lowcase; } @Override public String toString() { return "str=" + str + ", 数字的个数=" + this.GetNum() + ", 字符的个数=" + this.GetChar() + ", 大写字母的个数=" + this.GetUpCase() + ", 小写字母的个数=" + this.GetLowCase() ; } } public class CensusTest{ public static void main(String[] args) { Census a = new Census("78uijkIIOreY228"); System.out.println(a.toString()); } }
计算一个圆面积和周长还有圆心到原点的距离。
class Point { //定义Point类 double x; double y; double z; public Point(){} public Point(double x, double y, double z) { this(); this.x = x; this.y = y; this.z = z; } @Override public String toString() { return "Point [x=" + x + ", y=" + y + ", z=" + z + "]"; } public double distanceOfo(){ return Math.sqrt(x*x+y*y+z*z); } } public class PointTest{ public static void main(String[] args) { Point a = new Point(15,19,23); System.out.println(a.distanceOfo()); //输出double 类型点到原点距离 System.out.println(String.format("%.2f",(a.distanceOfo()))); //输出小数位后两位 } }
class Circle extends Point{ //定义一个子类Circle 父类是Point double radius; public Circle(){} public Circle(double x, double y, double z,double radius) { super(x,y,z); this.radius = radius; } public double getPerimeter(){ //计算周长 return (Math.PI*radius*2); } public double getArea(){ return (Math.PI*radius*radius); //计算面积 } } public class CircleTest { public static void main(String[] args) { Circle a = new Circle(10,20,32,25); System.out.println(a.toString()+"坐标点的圆面积==>"+a.getArea()); System.out.println(a.toString()+"坐标点的圆周长==>"+a.getPerimeter()); } }
使用一行代码计算大数阶乘
import java.math.BigInteger; import java.util.Scanner; public class Factorial { public static BigInteger fac(int n){ return (n == 1 ? new BigInteger(""+1):new BigInteger(""+n).multiply(fac(n-1))); } public static void main(String[] args) { Scanner a = new Scanner(System.in); System.out.println("请输入一个数"); int scr = a.nextInt(); System.out.println(scr+"的阶乘=="+fac(scr)); } }