Operators textbook series (seven) - Use Scanner to read integer

Operators textbook series (seven) - Use Scanner to read integer

More, click here to learn, sign up for

So far, we learned to use System.out.println ( "") the output data to the console.

In the next exercise, the need to use input data from the console, so the need to use Scanner class
Step 1: Scanner reading integers
Step 2: Use Scanner reads float
Step 3: Use string read Scanner
Step 4 : after reading the integer, then reads string
step 1: Scanner reads integer
Note: use Scanner class, need to add on top
import java.util.Scanner;

This class represents the introduction, to be able to use the normal

Use Scanner to read integer

import java.util.Scanner;
 
public class HelloWorld {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int a = s.nextInt();
        System.out.println("第一个整数:"+a);
        int b = s.nextInt();
        System.out.println("第二个整数:"+b);
    }
}

Step 2: Use Scanner reads float

Use Scanner to read a float

import java.util.Scanner;
  
public class HelloWorld {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        float a = s.nextFloat();
        System.out.println("读取的浮点数的值是:"+a);
 
    }
}

Step 3: Use string read Scanner

Use Scanner to read a string

import java.util.Scanner;
  
public class HelloWorld {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String a = s.nextLine();
        System.out.println("读取的字符串是:"+a);
    }
}

Step 4: After reading the integer, then reads the character string
to be noted that, if after reading by the nextInt integer (), and then re-read the string read out of the carriage return line: "\ r \ n ", because only nextInt reading digital information without reading carriage return" \ r \ n ".

So, if the business needs to read an integer, then read the string, then it should be continuously performed twice nextLine (), the first carriage return line is removed, the second is to read the real character string

After reading integer, then reads the string

import java.util.Scanner;
   
public class HelloWorld {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int i = s.nextInt();
        System.out.println("读取的整数是"+ i);
        String rn = s.nextLine();
        String a = s.nextLine();
        System.out.println("读取的字符串是:"+a);
    }
}
Published 32 original articles · won praise 182 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_44092440/article/details/102971178