Java的Scanner类提供了一系列方法来简化输入操作。以下是一些常用的方法:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一行文本:");
String input = scanner.nextLine();
System.out.println("你输入的是:" + input);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个整数:");
int number = scanner.nextInt();
System.out.println("你输入的整数是:" + number);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个双精度浮点数:");
double decimal = scanner.nextDouble();
System.out.println("你输入的双精度浮点数是:" + decimal);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个单精度浮点数:");
float singleDecimal = scanner.nextFloat();
System.out.println("你输入的单精度浮点数是:" + singleDecimal);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个布尔值(true或false):");
boolean flag = scanner.nextBoolean();
System.out.println("你输入的布尔值是:" + flag);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一行文本:");
scanner.nextLine(); // 消耗换行符
System.out.println("请输入一个整数:");
int number = scanner.nextInt();
System.out.println("你输入的整数是:" + number);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一行文本:");
scanner.nextLine(); // 消耗换行符
if (scanner.hasNextInt()) {
System.out.println("请输入一个整数:");
int number = scanner.nextInt();
System.out.println("你输入的整数是:" + number);
} else {
System.out.println("没有下一个整数");
}
}
}