Linux 拨号vps windows公众号手机端

scanner如何输入字符串

lewis 8年前 (2017-12-26) 阅读数 12 #程序编程
文章标签 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()方法,都需要在输入字符串之前输出提示信息,以便用户知道需要输入什么类型的数据。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门