- 1Import the Scanner class. You can either choose to import the
java.util.Scanner
class or the entirejava.util
package. To import a class or a package, add one of the following lines to the very beginning of your code:import java.util.Scanner; // This will import just the Scanner class. import java.util.*; // This will import the entire java.util package.
Ad - 2Initialize a new Scanner object by passing the
System.in
input stream to the constructor.System.in
is the standard input stream that is already open and ready to supply input data. Typically this stream corresponds to keyboard input.Scanner userInputScanner = new Scanner(System.in);
- 3You can now read in different kinds of input data that the user enters. The Scanner class supports getting primitives such as int, byte, short, long in addition to getting strings. Here are some methods that are available through the Scanner class:
- Read a byte -
nextByte()
- Read a short -
nextShort()
- Read an int -
nextInt()
- Read a long -
nextLong()
- Read a float -
nextFloat()
- Read a double -
nextDouble()
- Read a boolean -
nextBoolean()
- Read a complete line -
nextLine()
- Read a word -
next()
import java.util.Scanner; public class ScannerExample { public static void main(String[] args) { // Initiate a new Scanner Scanner userInputScanner = new Scanner(System.in); // Testing nextLine(); System.out.print("\nWhat is your name? "); String name = userInputScanner.nextLine(); // Testing nextInt(); System.out.print("How many cats do you have? "); int numberOfCats = userInputScanner.nextInt(); // Testing nextDouble(); System.out.print("How much money is in your wallet? $"); double moneyInWallet = userInputScanner.nextDouble(); System.out.println("\nHello " + name + "! You have " + numberOfCats + (numberOfCats > 1 ? " cats" : " cat") + " and $" + moneyInWallet + " in your wallet.\n"); } }
- Read a byte -
'Java' 카테고리의 다른 글
자바에서 10진수를 16진수로 변환시 (0) | 2015.07.16 |
---|---|
<Handmade> 10진수변환 프로그램 (0) | 2015.07.16 |
unmappable character for encodinig MS949 (0) | 2015.07.06 |
'javac'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는 배치 파일이 아닙니다. (0) | 2015.05.31 |