https://www.kuangstudy.com/course
用户交互Scanner
import java.util.Scanner;public class Demo01 { public static void main(String[] args) { // 创建一个扫描器对象,用于接收键盘数据 // IDEA提供了CTRL+ALT+V对该行快速根据变量类型自动生成变量. Scanner scanner = new Scanner(System.in); System.out.println("使用next方式接受:"); //判断用户有没有输入字符串 if(scanner.hasNext()){ // 使用next方式接受 String str=scanner.next(); System.out.println("输入的内容为:"+str); } // 凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉 scanner.close(); }}
import java.util.Scanner;public class Demo02 { public static void main(String[] args) { // 创建一个扫描器对象,用于接收键盘数据 // IDEA提供了CTRL+ALT+V对该行快速根据变量类型自动生成变量 Scanner scanner = new Scanner(System.in); System.out.println("使用nextLine方式接受:"); //判断用户有没有输入字符串 if(scanner.hasNextLine()){ // 使用next方式接受 String str=scanner.nextLine(); System.out.println("输入的内容为:"+str); } // 凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉 scanner.close(); }}
Scanner进阶使用
public class Demo03 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 从键盘j接收数据 int i=0; float f=0.0f; System.out.println("请输入整数:"); if(scanner.hasNextInt()){ i=scanner.nextInt(); System.out.println("整数数据:"+i); }else{ System.out.println("输入的不是整数数据!"); } System.out.println("请输入小数:"); if(sca.........