数字与字符串
装箱与拆箱
数字与字符串互相转换方法
public class TestNumber {
public static void main(String[] args){
int i = 5;
Integer it = new Integer(i); //基本类转封装类 装箱
int i2 = it.intValue(); //封装类型转换成基本类型 拆箱
System.out.println(Integer.MAX_VALUE); //整形最大值
System.out.println(Integer.MIN_VALUE); //整形最小值
float number1 = 3.14F;
Float a =new Float(number1);
float number2 = a.floatValue();
String str3 = a.toString();
System.out.println(str3);
float a1 = Float.parseFloat(str3);
System.out.println(a1);
//数字转字符串
String str = String.valueOf(i); //用String静态方法valueof
Integer b = i;
String str2 = b.toString(); //先装箱为b,再直接调用对象toString
System.out.println(str2);
String str1 = "9527";
int i1 = Integer.parseInt(str1); //字符串转数字,使用Integer.paresInt方法调用
System.out.println(i1);
String str4 = "3.1a4"; //字符串3.1a4转换float失败
float a2 =Float.parseFloat(str4);
System.out.println(a2);
}
}
数方法认识
常见数方法以及练习计算e值
public class MathMethod {
public static void main(String args[]){
float number1 = 3.14f;
System.out.println(Math.round(number1)); //四舍五入,为什么只有int
System.out.println(Math.random()); //为什么取不到>=1的数
System.out.println((int) (Math.random()*10)); //int 1-10以此类推
System.out.println(Math.sqrt(4)); //开方
System.out.println(Math.pow(2,3)); //次方
System.out.println(Math.PI); //pai
System.out.println(Math.E); //e
//计算lim n->无穷 (1+1/n)^n = e
int n = Integer.MAX_VALUE;
double e = Math.pow(1+1d/n,n);
System.out.println(e);
System.out.println(Integer.MAX_VALUE); //计算结果不一样应该系统n精度不够
}
}
计算一千万以内有多少个素数
两个方法组成:素数的判断与个数计数器
public class PrimeNumber {
public static void main(String args[]){
primeCalculate();
}
//素数判断方法
public static boolean isPrime(int i){
for(int j = 2;j<=Math.sqrt(i);j++){
if(i%j==0)
return false;
}
return true;
}
//素数计数器
public static void primeCalculate(){
int max = 1000 * 1000; //一千万以内素数
int count = 0;
for (int i = 2; i<=max;i++){
if(isPrime(i)){
count++;
}
}
System.out.println("一千万以内的素数有"+count+"个");
}
}