1,sc.next
String s = sc.next();
方法用于读取下一个完整的单词(由空格、制表符或换行符分隔)。它不会读取行尾的换行符
如输入:hello world
使用 sc.next()
第一次会返回 "Hello",然后光标会停留在 "World" 之前。
返回结果为:hello
代码演示:
import java.util.Scanner;
public class test02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word:");
String word = sc.next(); // 读取一个单词
System.out.println(word);
}
}
运行结果:
2,sc.nextline();
String s1 = sc.nextLine();
sc.nextLine()
方法用于读取整行,包括行尾的换行符。在读取之后,它会将光标移动到下一行。
如输入:hello world
返回结果为:hello world
代码演示:
import java.util.Scanner;
public class test02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine(); // 读取一行
System.out.println(line);
}
}
运行结果: