The Scanner class is used for keyboard input and needs to import the java.util.Scanner package when using it. Here are several commonly used keyboard input methods:
method | description |
nextBoolean() | Scan the next tag entered as a Boolean value and return that value |
nextByte() | Scan the next tag entered as byte |
nextDouble() | Scan the next token entered as double |
nextFloat | Scan the next tag entered as a float |
nextInt () | Scan the next token entered as int |
nextLine() | Advance this scanner to the current line and return the skipped input |
nextLong() | Scan the input next token as long |
nextShort() | Scan the next token entered as short |
next() | Find and return the next full token for this scanner |
Among them, the return values of next() and nextLine() are both string types. There are some disadvantages when using both:
nextLine()的缺点: 1)nextLine()方法前面不能出现其他的键盘输入方法 2)nextLine()方法前面可以有一个nextLine()方法 next()的缺点: 不能接受空格和回车
nextLine():
package com.itheima;
import java.util.Scanner;
public class Test {
// nextLine()的缺点:
// nextLine()方法前面不能出现其他的键盘输入方法
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入一个整数:");
int num=scanner.nextInt();
System.out.println(num);
System.out.println("请输入一个字符串:");
String s=scanner.nextLine();
System.out.println(s);
}
}
But if nextLine() is still a nextLint() method, the output is normal
package com.itheima;
import java.util.Scanner;
public class Test {
// nextLine()的缺点:
// nextLine()方法前面不能出现其他的键盘输入方法
// nextLine()前面可以在有一个nextLine()
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入一个字符串:");
String num=scanner.nextLine();
System.out.println(num);
System.out.println("请输入一个字符串:");
String s=scanner.nextLine();
System.out.println(s);
}
}
next():
package com.itheima;
import java.util.Scanner;
public class Test {
// next()的缺点:
// 不能接受空格和回车
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入一个字符串:");
String num=scanner.next();
System.out.println(num);
}
}