学习Scanner
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
//创建扫描对象接受数据
System.out.println("使用next方式接收");
Scanner scanner = new Scanner(System.in);
//判断用户有没有输入字符串
if (scanner.hasNext()){ //可以没这个if
String str = scanner.nextLine();
System.out.println("输入内容为"+str);
}
//凡是IO流要习惯关闭,不然会一直占用资源
scanner.close();
}
}
使用next和nextline方法获取输入字符串。
使用hasnextLine和hasnext判断是否还有输入数据。
next();和nextLine();的区别:
next();
1.一定要读到有效字符才可以结束输入
2.对有效字符之前的空白next方法会自动去掉
3.只有输入有效字符后的空白或者其他是结束符
4.next不能得到带有空白的字符串
nextLine();
1.以enter为结束符nextLine返回回车前的所有数据。
2.可以获得空白
has是布尔类型
equals 判断字符串是否相等
public class Demo04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
//equals 判断字符串是否相等
if( s.equals("Hello")){
System.out.println("end");
}
scanner.close();
}
}
JDk7里switch多选择结构支持String字符串。