用Scanner类读取用户输入Java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用Scanner类读取用户输入Java相关的知识,希望对你有一定的参考价值。

This snippet will allow you to read user's input when they write in the console. This method uses the Scanner class, which is my favorite way of doing instead of using the Buffered Reader, with the Scanner, you can also read from a file.
  1. import java.util.Scanner;
  2. public class ReadUserInput {
  3.  
  4. public static void main(String[] args) {
  5.  
  6. Scanner sc = new Scanner(System.in); //Creates the scanner and tells it
  7. //to read from the keyboard(System.in)
  8. String name; // The variable which is going to store the user's input
  9. System.out.println("Enter your name.");
  10. name = sc.nextLine(); //Sets name equal to user's input
  11. //if you just call the "next" method, the Scanner will read up to the first space.
  12. System.out.println("Hello " + name);//Greets the user
  13.  
  14. }
  15.  
  16. }

以上是关于用Scanner类读取用户输入Java的主要内容,如果未能解决你的问题,请参考以下文章

Java中的Scanner类

JAVA作业

Java Scanner 类

Java Scanner 类

Java Scanner 类

Scanner 类