Java Judgment Integer method

Source: Internet
Author: User

Today, when writing code, it suddenly occurred to me how to judge an integer, and then to handle the related operation by judging whether it was an integer.
began to think of a few methods, such as Baidu to the X (int) instanceof Integer, but then the program will be error, there is a problem is I started when the scanner input directly into the integer, so that before the judgment on the direct operation of the exception, obviously is wrong. Well, nonsense not much to say, directly on the code:

Package Com.java;

Import Java.util.Scanner;

/**
* Implement a digital cipher, the encryption rule is: Encryption result = (integer *10+5)/2 + 3.14159 encryption result is still an integer
*
* @author tding
*/
public class Digitaldevice {
public static void Main (string[] args) {
Scanner s = new Scanner (system.in);
System.out.println ("Please enter an integer:");
String num = S.next ();
boolean results=num.matches ("[0-9]+$");

The matching method is used here to determine whether the number you entered is a number that contains only 0-9, and if there are others, execute the code in the else.
if (results) {
int nums = Integer.parseint (num);
int result = (int) ((Nums * 10 + 5)/2 + 3.14159);
SYSTEM.OUT.PRINTLN (result);
} else {
SYSTEM.OUT.PRINTLN ("You entered the wrong number!") ");
}
}
}

Note: In this case I input the string, when judging to the int type, so that you can avoid errors in the input.

Java Judgment Integer method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.