Java数据输入(Java data input)

Java数据输入

Scanner使用的基本步骤

  • 导包(一般自动导入)

    import java.util.Scanner;

  • 创建对象

    Scanner sc = new Scanner(System.in);

    上面这个格式,只有sc是变量名,可以变,其它的都不允许变

  • 接收数据

    int i = sc.nextInt();

    上面这个格式,只有i是变量名,可以变,其它都不允许变

注:

  • nextInt()只读取数值,读取完后\n没有读取并且光标放在本行(空格及回车不会被读取)
  • nextDouble()的用法同理nextInt(),(nextInt无法读取小数,否则会报错。)
  • next()方法遇到第一个扫描有效字符,即第一个非空格非换行符后面开始,一直获取到下一个空格,换行符之前的,单个字符串。
  • nextLine()可以扫描到一行内容(当前行,光标所在行的内容,包括空格、回车)并作为一个字符串而被获取到。

使用nextLine()方法时,不将空格看做是两个字符串的间隔,而是看作字符串的一部分
使用next()方法时,将空格看作是两个字符串的间隔
使用nextInt()方法时,与next()方法类似,只是它的返回值是int类型的,依旧将空格看作是两个输入的数据的间隔

使用nextLine()方法时,不将空格看做是两个字符串的间隔,而是看作字符串的一部分

使用next()方法时,将空格看作是两个字符串的间隔

使用nextInt()方法时,与next()方法类似,只是它的返回值是int类型的,依旧将空格看作是两个输入的数据的间隔

————————

Java data input

Basic steps for scanner

  • 导包(一般自动导入)

    import java.util.Scanner;

  • create object
    Scanner sc = new Scanner(System.in);
    In the above format, only SC is the variable name, which can be changed, and others are not allowed to be changed
  • receive data
    int i = sc.nextInt();
    In the above format, only I is the variable name, which can be changed, and others are not allowed to be changed

Note:

  • Nextint() only reads the value. After reading, it \ NIS not read and the cursor is placed on the line (spaces and carriage returns will not be read)
  • The usage of nextdouble() is the same as that of nextint(), (nextint cannot read decimals, otherwise an error will be reported.)
  • The next () method encounters the first valid character to be scanned, that is, it starts after the first non space non newline character, and obtains a single string until the next space and before the newline character.
  • Nextline() can scan a line of content (the current line, the content of the line where the cursor is located, including space and carriage return) and get it as a string.

When using the nextline () method, spaces are not treated as spaces between two strings, but as part of a string
When you use the next () method, you treat spaces as spaces between two strings
When using the nextint () method, it is similar to the next () method, except that its return value is of type int, and spaces are still regarded as the interval between two input data

When using the nextline () method, spaces are not treated as spaces between two strings, but as part of a string

When you use the next () method, you treat spaces as spaces between two strings

When using the nextint () method, it is similar to the next () method, except that its return value is of type int, and spaces are still regarded as the interval between two input data