Get the App
SLTechnology News&Howtos  ›  Development  › 

How Java uses the Scanner class to get user input

Shulou Source: shulou.com Published: 2022-06-03 09:41:14 10月04日 Update

Editor to share with you how Java uses the Scanner class to get user input, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

The basic syntax for creating a Scanner object:

Scanner s = new Scanner (System.in)

The next () method of the Scanner class

Import java.util.Scanner;class Test {public static void main (String [] args) {String s; Scanner userInput = new Scanner (System.in); System.out.print ("Input String:"); if (userInput.hasNext ()) {s = userInput.next (); System.out.println (s);} userInput.close ();}}

If you run the result as follows, you will find that the English after the space has not been printed:

PS C:\ Users\ admin\ Desktop\ java_code\ user input > java TestInput String: Hello WorldHelloPS C:\ Users\ admin\ Desktop\ java_code\ user input >

NextLine method of the Scanner class

Modify the code on the basis of the above:

Import java.util.Scanner;class Test {public static void main (String [] args) {String s; Scanner userInput = new Scanner (System.in); System.out.print ("Input String:"); if (userInput.hasNextLine ()) {s = userInput.nextLine (); System.out.println (s);} userInput.close ();}}

As a result, the English after the space can also be printed:

PS C:\ Users\ admin\ Desktop\ java_code\ user input > javac Test.javaPS C:\ Users\ admin\ Desktop\ java_code\ user input > java TestInput String: Hello WorldHello World

The above is all the content of the article "how Java uses the Scanner class to get user input". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: User input article content method space result English run not much code foundation most object more knowledge industry grammar information information channel Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple vpn Huawei Shulou Technology Microsoft