Scanner基本学习代码
时间: 2023-09-08 21:09:31 浏览: 34
Sure, here is a basic code snippet for learning how to use the Scanner class in Java:
```java
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer: ");
int num = sc.nextInt();
System.out.println("You entered " + num);
System.out.print("Enter a double: ");
double d = sc.nextDouble();
System.out.println("You entered " + d);
System.out.print("Enter a string: ");
String str = sc.next();
System.out.println("You entered " + str);
sc.close();
}
}
```
This code prompts the user to enter an integer, a double, and a string, and then prints out what was entered. The Scanner class is used to read input from the console, and the `nextInt()`, `nextDouble()`, and `next()` methods are used to read integers, doubles, and strings respectively. The `close()` method is called at the end to release any resources used by the Scanner object.