Java's Scanner class provides nextInt, nextFloat, nextDouble and other methods, which can read numbers of specified types like scanf in C language. (Recommended: java video tutorial)
First define a Scanner object:
Scanner sn = new Scanner(System.in);
Use sn.nextInt to read integer numbers. Note that if the input is not an integer number, This function throws InputMismatchException and should be caught.
System.out.print("请输入一个整数:"); try{ intVal = sn.nextInt(); System.out.println("你输入了:" + intVal); } catch(InputMismatchException e){ System.out.println("必须输入整数!"); }
Use sn.nextFloat to read single-precision floating point numbers. If the input is not a number, an InputMismatchException will also be thrown and should be caught.
System.out.print("请输入一个浮点数:"); try{ floatVal = sn.nextFloat(); System.out.println("你输入了:" + floatVal); } catch(InputMismatchException e){ System.out.println("必须输入数!"); }
Use sn.nextDouble to read double-precision floating-point numbers. The operation is similar to single-precision.
System.out.print("请输入一个浮点数:"); try{ doubleVal = sn.nextDouble(); System.out.println("你输入了:" + doubleVal); }catch(InputMismatchException e) { System.out.println("必须输入数!"); }
The stream should be closed after use: sn.close();
For more java knowledge, please pay attention to the java basic tutorial column.
The above is the detailed content of How to enter numbers in java. For more information, please follow other related articles on the PHP Chinese website!