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 inputString = scanner.nextLine();
System.out.println("你输入的字符串是:" + inputString);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个整数:");
int inputInt = scanner.nextInt();
System.out.println("你输入的整数是:" + inputInt);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个浮点数:");
float inputFloat = scanner.nextFloat();
System.out.println("你输入的浮点数是:" + inputFloat);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个双精度浮点数:");
double inputDouble = scanner.nextDouble();
System.out.println("你输入的双精度浮点数是:" + inputDouble);
}
}
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 inputBoolean = scanner.nextBoolean();
System.out.println("你输入的布尔值是:" + inputBoolean);
}
}
注意:在读取数据之前,需要确保输入流中有数据。否则,nextInt()
、nextFloat()
等方法会抛出NoSuchElementException
异常。如果需要处理这种异常,可以使用try-catch
语句。