Scanner对象
java.util.Scanner是Java5的新特征,可通过Scanner类来获取用户的输入
- next()
public class Demo01 {
public static void main(String[] args) {
//创建一个扫描器对象,用于接收键盘数据
Scanner scanner = new Scanner(System.in); //输入hello world
System.out.println("使用next方式接收: ");
//判断用户有没有字符串
if (scanner.hasNext()) {
//使用next()方法接收
String str = scanner.next();
System.out.println("输出的内容为:" + str); //输出hello 对输入有效字符之前的空白,next()会自动去掉,而在有效字符之后遇到空白会作为结束符,所以next()不能得到带有空格的字符串
}
//凡是属于IO流的类如果不关闭会一直占用资源
scanner.close();
}
}
- nextLine()
public class Demo02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); //输入hello world
System.out.println("使用nextLine()方法接收:");
if (scanner.hasNext()){
String str = scanner.nextLine();
System.out.println("输出的内容为:" + str); //输出hello world 以Enter为结束符,可以获得空白
}
scanner.close();
}
}
- hasNextInt()
public class Demo03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i = 0;
float j = 0.0f;
System.out.println("请输如整数:");
if (scanner.hasNextInt()){
i = scanner.nextInt();
System.out.println("输入的整数是:" + i);
}else{
System.out.println("输入的不是整数");
}
System.out.println("请输入小数:");
if (scanner.hasNextFloat()){
j = scanner.nextFloat();
System.out.println("输入的小数为:" + j);
}else{
System.out.println("输入的不是小数");
}
scanner.close();
}
}
判断字符串是否相等:别用 == 用s.equals()
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
if(s.equals("Hello")){
System.out.println("s");
}
Swtitch
JDK7以后支持字符串作为Switch变量
字符的本质还是数字
反编译 java---class(字节码文件)---反编译(IDEA)
case穿透:
public class Switch {
public static void main(String[] args) {
char grade = 'C';
// case穿透 switch 匹配一个具体的值
switch (grade){
case 'A':
System.out.println("优秀");
break; //可选 但是如果不写 满足了A会把后面的BCD都穿透 会输出及格 再接再厉 无
case 'B':
System.out.println("良好");
case 'C':
System.out.println("及格");
case 'D':
System.out.println("再接再厉");
default:
System.out.println("无");
}
}
}
反编译
从左侧project打开路劲 将.calss文件丢到IDEA里面打开就能看到反编译文件
增强for循环
JDK5引入,用于遍历数组和集合
int[] numbers = {10,20,30,40,50};
//遍历数组的元素
for (int x:numbers){
System.out.println(x);
}
//等价于
for (int i = 0;i<5;i++){
System.out.println(numbers[i]);
}