Home > Java > JavaBase > body text

How to enter numbers in java

Release: 2019-12-04 10:52:44
Original
9853 people have browsed it

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);
Copy after login

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("必须输入整数!");  
       }
Copy after login

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("必须输入数!"); 
        }
Copy after login

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("必须输入数!");  
    }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template