Home >Java >JavaBase >How to enter numbers in java

How to enter numbers in java

尚
Original
2019-12-04 10:52:449886browse

How to enter numbers in java

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn