Day07-User Interaction Scanner, Sequence Structure, Selection Structure

Day07-User Interaction Scanner, Sequence Structure, Selection Structure

User interaction Scanner

Obtain user input through the Scanner class.

The basic syntax for creating Scanner objects:

import java.util.Scanner;
//导入 java.util 包下的 Scanner类

Scanner s = new Scanner(System.in);
//创建一个对象s,来获取用户输入

Get the input string through the next() and nextLine() methods of the Scanner class. Before reading, we generally need to use hasNext() and hasNextLine() to determine whether there is still input data.

Example 1: hasNext(), next() methods

import java.util.Scanner;     //导入 java.util 包下的 Scanner类
public class Scanner{
    
    
    public static void main(String[] args){
    
    
        Scanner scanner = new Scanner(System.in);
        //创建一个对象scanner,来获取用户输入
        if(scanner.hasNext()){
    
       //用hasNext()判断是否还有输入
            String str = scanner.next();
            //使用next()方法获取用户输入,并储存到字符串str
            System.out.println(str);
        }
        scanner.close();//IO流的类会一直占用资源,需要手动关闭
    }
}//输入: Hello World ; 输出: Hello

Example 2: hasNextLine (), nextLine () method

//例1第6~10行:
if(scanner.hasNextLine()){
    
    
    //用hasNextLine()判断是否还有输入
    String str = scanner.nextLine();
    //使用nextLine()方法获取用户输入,并储存到字符串str
    System.out.println(str);
}//输入: Hello World ; 输出: Hello World

The two inputs are the same, but the output is different:

  • The next() method must have input, and it will end automatically when it encounters a space

  • The nextLine() method ends with Enter, so you can enter a space or no input

  • To determine whether there are other types of data input such as int or float, use hasNextInt(), nextInt(), hasNextFloat(), nextFloat(), etc.

[Example 3] Enter multiple numbers, and find the sum and average of them. Use Enter to confirm each number entered. End the input and output the execution result by entering a non-number:

import java.util.Scanner;
public class Num{
    
    
    public static void main(String[] args) {
    
    
        double num = 0;
        int i = 0;
        Scanner s = new Scanner(System.in);
        while(s.hasNextDouble()){
    
    
            double digtal = s.nextDouble();
            num += digtal;
            i++;
        }
        System.out.println(i +"个数的和为:" + num);
        System.out.println(i +"个数的平均数为:" + num / i);
        s.close();
    }
}//输入10	20	30	40	a	
//输出4个数的和为:100.0	4个数的平均数为:25.0

Sequence structure

The sequence structure is the simplest algorithm structure and the basic structure of Java.

Between sentence and sentence, proceed from top to bottom.

Choose a structure

if select structure

  1. if single selection structure:

    if(布尔表达式){
          
          
        语句1;
    }//布尔表达式为true时,执行语句1; 否则不执行
    
  2. if double selection structure:

    if(布尔表达式){
          
          
        语句1;
    }else{
          
          
        语句2;
    }//布尔表达式为true时,执行语句1; 否则执行语句2。
    
  3. if multiple selection structure:

    if(布尔表达式1){
          
          
        语句1;
    }else if(布尔表达式2){
          
          
        语句2;
    }else if(布尔表达式3){
          
          
        语句3;
    }else{
          
          
        语句4;
    }//布尔表达式1为true时,执行语句1; 否则判断布尔表达式2,若为true,执行语句2;否则判断布尔表达式3,若为true,执行语句3;否则执行语句4。
    
  • Difference from nested structure

    The condition for executing statement 1 is that Boolean expression 1 is true;

    The condition for executing statement 2 is that the boolean expression 1 is false and 2 is true;

    The condition for executing statement 3 is that Boolean expressions 1 and 2 are both false and 3 is true;

    The condition for executing statement 4 is that the Boolean expressions 1, 2, and 3 are all false.

    [Example] Test scores are 100 full marks, 80 or more are excellent, 60 to 80 are good, and 60 or less fail.

    import java.util.Scanner;
    public class Demo{
          
          
        public static void main(String[] args){
          
          
           Scanner s =  new Scanner(System.in);
            int score = s.nextInt();
            if(score == 100){
          
          
                System.out.println("恭喜满分!");
            }else if(score >= 80 && score < 100){
          
          
                System.out.println("优秀!");
            }else if(score >= 60 && score < 80){
          
          
                System.out.println("表现良好");
            }else if(score >= 0 && score < 60){
          
          
                System.out.println("不及格,仍需努力。");
            }else{
          
          
                System.out.println("成绩格式错误!");
            }
            s.close();
        }
    }
    
  1. if nested structure:

    if(布尔表达式1){
          
          
        if(布尔表达式2){
          
          
            语句1;
        }else{
          
          
            语句2;
        }
    }else{
          
          
        语句3;
    }
    
  • Different from if multiple selection structure

    The condition for executing statement 1 is that Boolean expressions 1 and 2 are both true;

    The condition for executing statement 2 is that Boolean expression 1 is true and 2 is false;

    The condition for executing statement 3 is that Boolean expression 1 is false.

switch multiple selection structure

Another implementation of the multiple-choice structure is the switch case statement.

The switch case statement determines whether a variable is equal to a certain value in a series of values, and each value is called a branch.

switch(expression){
    
    
	case value 1 :
	//语句
	break; //可有可无
	case value 2 :
	//语句
	break; //可有可无
	...
    ...
	default : //可有可无
	//语句
}
  • The variable type in the switch statement can be byte, short, int or char. Starting from Java SE 7, switch supports the String type.

  • The switch statement can have multiple case statements. Each case is followed by a value to be compared and a colon.

  • The data type of the value in the case statement must be the same as the data type of the variable.

  • When the value of the variable is equal to the value of the case statement, the statement after the case statement starts to execute, and the switch statement will not jump out until the break statement appears. [case penetration]**, otherwise the program will continue to execute the next case statement. Until the break statement appears.

  • The switch statement can contain a default branch, which is usually the last branch. default in no case statement and variable values to match the execution time. The default branch does not require a break statement.

Example 1: [case penetration]

public static void main(String args[]){
    
    
	int i = 1;
	switch(i){
    
    
		case 0:
			System.out.println("0");
		case 1:
			System.out.println("1");
		case 2:
			System.out.println("2");
		case 3:
			System.out.println("3");
			break;
		default:
			System.out.println("default");
	}
}//输出1	 2	 3。【case穿透】	

Example 2: [JDK7 adds String expressions]

public static void main(String[] args) {
    
    
	String name = "Crown";
	switch (name) {
    
         //JDK7的新特性,表达式的内容可以是字符串。
		case "明天也有晚霞嘛":
			System.out.println("输入为:明天也有晚霞嘛");
			break;
		case "Crown":
			System.out.println("输入为:Crown");
			break;
		default:
			System.out.println("无法匹配");
			break;
	}
}

Guess you like

Origin blog.csdn.net/weixin_46330563/article/details/114859686