新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

scanner如何输入字符串,scanner如何输入多个值

发布时间:2023-10-16 18:21:57

scanner如何输入字符串

要使用Scanner类输入字符串,可使用next()还是nextLine()方法。

  1. 使用next()方法输入字符串:该方法会读取输入的字符串直到遇到空格还是换行符为止。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入字符串:");
String str = scanner.next();
System.out.println("输入的字符串是:" + str);
}
}
  1. 使用nextLine()方法输入字符串:该方法会读取输入的一行字符串,包括空格和换行符。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入字符串:");
String str = scanner.nextLine();
System.out.println("输入的字符串是:" + str);
}
}

不管使用next()或nextLine()方法,都需要在输入字符串之前输出提示信息,以便用户知道需要输入甚么类型的数据。