Java 基础类库

Scanner类

  • Scanner可以从文件、输入流、字符串作为数据源,用于从文件、输入流、字符串中解析数据。
  • 默认情况下,使用空白(包括空格、Tab、回车)作为多个输入项之间的分隔符。
  • 类方法:
    方法名 说明
    hasNextXxx() 是否有下一个Xxx类型的输入项,其中Xxx可以是Int、Long等基本类型
    hasNextLine( ) 是否有下一行(即只有回车算分隔符)
    hasNext( ) 判断是否包含下一个字符串
    nextXxx( ) 获取下一个Xxx类型的输入项
    nextLine( ) 获取下一行输入项
    next( ) 获取下一个数据
    close( ) 关闭输入流
  • 读取文件输入
import java.util.Scanner;
public class ScannerFileTest
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(new File("ScannerFileTest.java"));
        System.out.println("ScannerFileTest.java文件内容如下:");
        while(sc.hasNextLine())
        {
            System.out.println(sc.nextLine());
        }
    }
}
  • 读取键盘输入
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int sum = 0;
		while(sc.hasNextLine()) {
			System.out.println(sc.nextLine());
			sum += 1;
			if (sum == 3) {
				sc.close();
				break;
			}
		}
	}
}

在这里插入图片描述

  • 关于阻塞:由上面例子可以看到,在每输入一句以后,程序停在了when处等待输入,只有在执行了break以后才跳出循环。

Object类

  • Object是所有类的父类,当定义的类没有extends指定父类时,默认其父类为Object类,即所有类均可以使用Object类的方法。
  • 类方法:
    方法名 说明
    equals(Object obj) 判断两个对象是否为同一对象(地址是否相同)
    getClass( ) 返回该对象运行时的类
    toString( ) 返回该对象的字符串表示,在输出或“+”链接字符串时自动调用
    clone( ) 克隆
  • getClass( )用法
    判断a是否就是类A的对象时:a.getClass( ) == A.class;
  • 重写clone( )
class Address {
   String detail;
   public Address(String d) { detail = d; }
}
class User implements Cloneable {
   int age;
   Address add;
   public User(int age) { this.age = age; add = new Address("湖北武汉"); }
   public User clone() throws CloneNotSupportedException { return (User)super.clone(); }
}

public class Main {
   public static void main(String[] args) throws CloneNotSupportedException {
   	User u1 = new User(29);
   	User u2 = u1.clone();
   	System.out.println(u1 == u2);
   }
}

输出为false,说明clone( )会重新分配地址。

String、StringBuffer类

详见Java字符串处理

Math类

  • Math类两个变量:PI和E
  • Math类方法:
    方法名 说明
    toDegrees、toRadians 转换为角度、转换为弧度
    sin、cos、tan 正弦、余弦、正切
    asin、acos、atan 反正弦、反余弦、反正切
    sinh、cosh、tanh 双曲正弦、双曲余弦、双曲正切
    floor、ceil、round 向下取整、向上取整、四舍五入取整
    sqrt、cbrt 平方根、立方根
    exp、pow e的幂、乘方
    log、log10 自然对数ln、底数为10的对数
    abs 绝对值
    max、min 最大值、最小值

Random和ThreadLocalRandom类

  • Random和ThreadLocalRandom用法基本相似,ThreadLocalRandom在并发访问环境下可以减少多线程资源竞争,保证系统具有更好的线程安全性。
  • 创建方法:Random rand = new Random();
    ThreadLocalRandom rand = ThreadLocalRandom.current();
    其中,()内填写的是随机数的种子,默认为当前时间。例如:
    Random rand = new Random(50)表示种子是50
  • Random类方法:
    方法名 说明
    nextBoolean( ) 获取下一个Boolean类型随机数
    nextDouble( ) 获取下一个0.0~1.0之间随机数
    nextInt( ) 获取下一个整数取整范围内的随机数
    nextInt(int a) 取得下一个0~a之间的整数随机数

猜你喜欢

转载自blog.csdn.net/qq_43575267/article/details/87741171
今日推荐