流程控制
1.用户交互Scanner
Java5新特性,java.util.Scanner,可通过Scanner类来获取用户的输入
基本语法:
Scanner s = new Scanner(System.in);
通过Scanner类的next()和nextLine()方法来接收用户输入的字符串,接收前一般使用hasNext()和hasNextLine()方法判断是否还有输入
Demo01
package com.shifan.scanner;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
//创建一个扫描器对象,用于接收键盘数据
//输入new Scanner(System.in);后按住alt+Enter再回车即可自动补充代码
Scanner scanner = new Scanner(System.in);
//next方法遇到空格停止接收数据,自动去除前置空格
System.out.println("使用next方法接收:");
//判断用户是否输入字符串
if (scanner.hasNext()){
String string = scanner.next();
System.out.println("输入的字符串为"+string);
}
//凡是属于io流的类使用完一定要关闭掉,否则会一直占用资源
//注意这里是使用对象scanner调用close()方法关闭
scanner.close();
}
}
Demo02
package com.shifan.scanner;
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) {
//从键盘接收数据
Scanner scanner = new Scanner(System.in);
//nextLine方法以Enter结束
System.out.println("使用nextLine接收:");
//判断是否还有输入
if (scanner.hasNextLine()){
String string1 = scanner.nextLine();
//equals判断字符串是否相等
System.out.println(string1.equals("hello"));
System.out.println("输出字符串为:"+string1);
}
scanner.close();
}
}
Demo03
package com.shifan.scanner;
import java.util.Scanner;
public class Demo03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextInt()) {
int i = scanner.nextInt();
System.out.println(i);
}
if (scanner.hasNextFloat()) {
float f = scanner.nextFloat();
System.out.println(f);
}
scanner.close();
}
}
Demo04
package com.shifan.scanner;
import java.util.Scanner;
public class Demo04 {
public static void main(String[] args) {
//输入多个数,计算总和、平均值、统计输入的数个数
Scanner scanner = new Scanner(System.in);
//和
double sum = 0;
//个数
int num = 0;
//通过循环判断是否还有输入,并计算统计
while (scanner.hasNextDouble()){
double x = scanner.nextDouble();
sum += x;
num++;
}
System.out.println(num+"个数的和为:"+sum);
System.out.println(num+"个数的平均值为:"+sum/num);
scanner.close();
}
}
switch语句中的变量类型从JavaSE 7开始支持使用字符串
package com.shifan.struct;
public class SwitchDemo01 {
public static void main(String[] args) {
String s = "时帆";
switch (s){
case "时帆":
System.out.println(s);
break;
case "时间":
System.out.println(s);
break;
default:
System.out.println(s);
}
//输出时帆
}
}
Java5引入了一种主要用于数组和集合的增强型for循环
package com.shifan.struct;
public class ForDemo01 {
public static void main(String[] args) {
int[] numbers ={1,2,3,4,5};
//遍历数组元素
for (int x : numbers){
System.out.println(x);
}
}
}