Scanner类
简介
public final class Scanner
extends Object
implements Interator
作用
JDK5以后用于接受键盘录入。
使用
- 导包: import java.util.Scanner;
- 创建对象: Scanner sc = new Scanner(System.in);
- System.in是什么?
- System是一个类
- System类下有一个静态字段
- public static final InputStream in;
- System.in相当于一个InputStream对象,InputStream is = System.in
- InputStream //标准的输入流,对应键盘录入
- 构造方法:
- public Scanner(InputStream source)
- System.in是什么?
- 调用方法: 例: int x = sc.nextInt();
方法
public boolean hasNextInt();
//判断输入是否是int类型数据
public int nextInt();
//接收输入的int类型数据
//结合使用
if(sc.hasNextInt()) {
int x = sc.nextInt();
System.out.println("x:"+x);
}else {
System.out.println("您输入的数据有误");
}
public String nextLine();
//接收字符串
String类
构造方法
public String()
//空构造
public String(byte[] byte)
//把字节数组转换成字符串
public String(byte[] bytes,int index,int length)
//把字节数组的一部分转成字符串
public String(char[] value)
//把字符数组转成字符串
public String(char[] value,int index,int count)
//把字符数组的一部分转成字符串
public String(String original)
//把字符串常量值转成字符串
String s = "abc";
//不用构造方法的赋值方法
//字符串字面值"abc"也可以看成一个对象
方法
- 判断功能
public boolean equals(Object obj)
//比较字符串的内容是否相同
public boolean equalsIgnoreCase(String str)
//比较是否相同,不区分大小写
public boolean contatins(String str)
//判断大串中是否包含小串
public boolean startsWith(String str)
//判断字符串是否以某个指定的字符串开头
public boolean endsWith(String str)
//判断字符串是否以某个指定字符串结尾
public boolean isEmpty()
//判断字符串是否为空
- 获取功能
public int length();
//获取字符串长度
public char charAt(int index);
//返回索引处的字符
public int indexOf(int ch)
//返回指定字符在此字符串中第一次出现处的索引
//为什么是int ch,'a'和97都可以代表'a'
public int indexOf(String str)
//返回指定字符串再此字符串中第一次出现的索引
public int indexOf(int ch,int fromIndex)
//返回指定字符在此字符串中从指定位置后第一次出现的索引
public int indexOf(String Str,int fromIndex)
//返回指定字符串在此字符串中从指定位置后第一次出现的索引
public String substring(int start)
//从指定位置开始截取字符串,默认到末尾
public String substring(int start,int end)
//从指定位置开始到指定位置结束截取字符串,包左不包右
- 转换功能
public byte[] getBytes()
//把字符串转换为字节数组
public char[] toCharArray()
//把字符串转换为字符数组
public static String valueOf(char[] chs)
//把字符数组转成字符串
public static String valueOf(int i)
//把int类型的数据转成字符串
//注意:String类的valueof方法可以把任意类型的数据转成字符串
public String toLowerCase()
//把字符串转成小写
public String toUpperCase()
//把字符串转成大写
public String concat(String str)
//把字符串拼接
- 替换功能
public String replace(char old,char new)
public String replace(String old,String new)
- 去除字符串两端空格
public String trim()
- 按字典顺序比较两个字符串
public int compareTo(String str)
public int compareToIgnoreCase(String str)
写在最后
因为自己java基础薄弱,所以最近在看传智播客2015刘意老师的java视频,已经看到了day12,发现看过的都忘得差不多了,所以想对每天的学习进行总结,并且在这里记录一下,方便自己以后查看,也希望对大家有所帮助,并不很全,只是简单的概括,具体例子什么的都没有写。有错误的地方希望大家指正,谢谢!