2021-3-1# java process control

User interaction Scanner

  1. Obtain user input through the Scanner class (java.util.Scanner)

  2. Get the input string through the next() and nextLine() methods of the Scanner class. Generally, you need to use hasNext() and hasNextLine() to determine whether there is input data before reading.

  3. next() cannot accept a string with spaces, it will end after reading a valid character, and automatically remove the space before the valid character

  4. nextLine() takes Enter as the terminator, accepts the characters before Enter, and can have spaces

  5. Basic grammar

    public class Demo{
          
          
        public static void main(String[] args){
          
          
            //创建一个扫描对象,用于接收键盘数据
            Scanner scanner = new Scanner(System.in);
          
            System.out.println("接收数据");
            //判断用户有没有输入字符串
            if(scanner.hasNext()){
          
          
                //使用next方式接收
                String str = scanner.next();
                System.out.println("输出的内容为:"+str);
            }  
            //凡是属于IO流的类如果用完不关闭会一直占用资源,养成好习惯用完要关掉
            scanner.close();
        }
    }
    

Advanced Scanner

  1. import java.util.Scanner;
    
    public class Demo {
          
          
    	//通过输入多个数字计算和与平均值,每个数字用回车键确认,通过输入非数字来结束输入
    	public static void main(String[] args) {
          
          
    		Scanner scanner = new Scanner(System.in);
    		//和
    		double sum = 0;
    		//计算输入了多少个数字
    		int m = 0;
    		//通过循环判断是否还有输入,并在里面对每一次进行求和统计
    		while(scanner.hasNextDouble()){
          
          	
    			double x = scanner.nextDouble();
    			m = m+1;//m++
    			sum=sum+x;
    		}
    		
    		System.out.println(m+"个数的和为"+sum);
    		System.out.println(m+"个数的平均数是"+sum/m);		
    		scanner.close();
    	}
    }
    		
    
  2. import java.util.Scanner;
    
    public class Demo02 {
          
          
    
    	public static void main(String[] args) {
          
          
    		Scanner scanner = new Scanner(System.in);
    	
    		//从键盘接收数据
    		int i = 0;
    		float f = 0.0f;
    		
    		System.out.println("请输入整数:");
    		
    		//如果...那么...
    		if(scanner.hasNextInt()){
          
          
    			i = scanner.nextInt();
    			System.out.println("整数:"+i);
    		}else{
          
          
    			System.out.println("输入的不是整数数据!"+i);
    
    		}
    		
    		System.out.println("请输入小数:");
    		
    		//如果...那么...
    		if(scanner.hasNextFloat()){
          
          
    			f = scanner.nextFloat();
    			System.out.println("小数数据:"+f);
    		}else{
          
          
    			System.out.println("输入的不是小数数据!"+f);
    		}
    	}
    }
    
    

Guess you like

Origin blog.csdn.net/qq_52332852/article/details/114248920