Check first two digit number lies between 00 && 99 - java

I develop a function that reject number starting with 00 and 99.
public Boolean valideCode(EditText code_postal){
String number = code_postal.getText().toString();
if (number.charAt(0)==00){
}
return false;
}
How can i implement this function properly.

that if statement will always returns false.
One solution:
if (number.trim().startsWith("00") || number.trim().startsWith("99")){
System.out.println("not valid");
}

Use .startsWith():
if (number.startsWith("00") || number.startsWith("99")) ...
.charAt() returns a single character, not a string.
(out of sheer curiosity, why this? code_postal.getText().toString(); From the name of .getText(), you'd have figured out that it already returned a String... Bah.)
EDIT So, on demand, another version which checks by converting to an int first...
final int begin = Integer.parseInt(number.subString(0, 2));
if (begin % 99 == 0) // can only be true if number is 0 or 99
// etc

If I understand your question specially heading "lies between 00 && 99" you want this
try
{
String s = "45Abc";
Integer i = Integer.parseInt(s.substring(0,2));
if (i>00 && i<99)
System.out.println("True");
}catch (NumberFormatException e)
{
// TODO Auto-generated catch block
System.out.println("First two characters are not numbers");
}

Use your logic look like below
private boolean isValid(String str) {
if (str == null)
return false;
String tempStr = null;
try {
if (str.length() > 2) {
tempStr = str.substring(0, 2);
} else {
tempStr = str;
}
int number = Integer.parseInt(tempStr);
if (number >= 0 && number <= 99) {
return false; //in between 0 to 99
} else {
return true;
}
} catch (NumberFormatException e) {
}
return false;
}

You can use String class indexOf() method :
if (number.indexOf("00")==0 || number.indexOf("99")==0)
EDITED: - You need this as I understood from your question subject line "Check first two digit number lies between 00 && 99".
public static boolean isValid(String name) {
boolean isValid = true;
if(name.length()>2){
name = name.substring(0, 2);
}
try {
int number = Integer.parseInt(name);
if(number>-1 || number<100){
isValid = false;
}
}
catch(Exception e){
isValid = false;
}
return isValid;
}

To check if the Entered number starts with "00" or "99"
public Boolean valideCode(EditText code_postal){
String number = code_postal.getText().toString();
if(number.startsWith("00") || number.startsWith("99")){
return true;
}
return false;
}
To check if the Entered number is between "00" and "99"
public Boolean valideCode(EditText code_postal){
String number = code_postal.getText().toString();
String firstTwoDigits = number.substring(0,2);
if (Integer.valueOf(firstTwoDigits )>=0 && Integer.valueOf(firstTwoDigits )<=99){
return true;
}
return false;
}
Note: The title of your question and description are different. hence two answers.

Just to be different (and inefficient and impenetrable):
return !number.matches("^\s?(00|99).+");

Related

How to catch a NumberFormatException?

I'm trying to figure out how to catch a numberformat exception error within my code such that if the user inputs a letter within a string and my program tries to parse it to an int my program won't throw up an error but instead stop and return a Boolean value. I'm also trying to understand that if the try statement works I'd like it to continue to execute the following code.
if (counter == 3) {
int compare;
boolean check = true;
String[] newip = IpAddress.split("\\.");
if (newip.length == 4) {
for (int index = 0; index < newip.length; index++) {
//There should be a try statement here.
// if the try statement fails then I'd like for it to catch
// the numberformatexception and evaluate my boolean to
//false;
//but if it passes I'd like for it to continue to execute
//the following code.
compare = Integer.parseInt(newip[index]);
if (compare >= 0 & (compare <= 255)) {
check = true;
}
else{
check = false;
}
}
if (check)
return true;
else
return false;
}
else {
check = false;
return check;
}
}
else{
return false;
}
}
Surround that line with try/catch:
try {
compare = Integer.parseInt(newip[index]);
} catch (NumberFormatException e) {
check = false;
}
and then:
if (check) {
if (compare >= 0 & (compare <= 255)) {
check = true;
} else {
check = false;
}
} else {
return false;
}
Instead of catching NumberFormatException, you can use NumberUtils from commons-lang 3.x to check if the input is a number.
NumberUtils.isNumber(newip[index])
However as per the documentation, it would be deprecated in 4.x and you would need to use isCreatable
NumberUtils.isCreatable(newip[index])

Checking if an IPv4 address is valid

I am trying to write a basic program in Java that checks if an IP address is valid. I am trying to use no external classes other than the Scanner class and also no regular expressions.
My code, available at this gisttakes in 4 integers as input, one for each octet. I also have this codewhich is a little more readable than the first but is longer.
My question is, is there any other way to implement this idea in significantly fewer lines, and if so, how would I accomplish this?
While this code segment is a bit verbose, it is simple, self-descriptive, and has proven to be tight.
private static boolean isIPAddressValid(String ip) {
boolean result = true;
int i = 0;
int [] val = new int[4];
if ((ip == null) || (ip.trim().length() == 0))
{
//null ip address entered
result = false;
}
else
{
if (!(ip.contains(".")))
{
//no '.' found
result = false;
}
else
{
String [] parts = ip.split("\\.");
if (!(parts.length == 4))
{
//not 4 quadrants
result = false;
}
else
{
for (String s : parts) {
try {
val[i] = Integer.parseInt(s);
if ((val[i] < 0) || (val[i] > 255))
{
//this quadrant's value exceeds limits
result = false;
}
i++;
} catch (Exception e) {
//failed to parse quadrant to an integer");
result = false;
}
}
}
}
}
return result;
}
only some minor enhancements (i think your code looks very good - my opinio so far) it is clearly to read and all work blocks are properly to understand....
boolean isFailed = false;
if (first < 0 || first > 255) {
System.out.println("Octet 1 is invalid");
isFailed = true;
}
if (second < 0 || second > 255) {
System.out.println("Octet 2 is invalid");
isFailed = true;
}
if (third < 0 || third > 255) {
System.out.println("Octet 3 is invalid");
isFailed = true;
}
if (fourth < 0 || fourth > 255) {
System.out.println("Octet 4 is invalid");
isFailed = true;
}
if (!isFailed){
System.out.println("IP Address: " + first + "." + second + "." + third + "." + fourth);
}
so i simply invert the order of printing - that saves you only that big check before...
your approach was to can check each octet...
you can simply do this 4 times or write a method for it:
private static boolean check(int octet, int index){
if (0xFF & octet < 256) return true;
System.out.println("Octet "+index+" is invalid";
return false;
}
and use this method in your main method
if (check(first,0) && check (second, 2) && check (third, 3) && check(fourth, 4) ){
System.out.println("your ip is valid");
}
note - this only reveals the first invalid octet - if you want to check all you need another boolean
boolean result = check(first,0) &&
check (second, 2) &&
check (third, 3) &&
check(fourth, 4); //reveals all errors
a totally different approach would be to use http://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html#getByName%28java.lang.String%29
try{
/*InetAdress adress =*/ InetAdress.
getByName(""+first+"."+second+"."+third+"."+forth)
System.out.println("your ip is valid");
}catch (UnknownHostException e){
//TODO represent that error message into a nice expression
System.out.println("your ip is invalid");
}
but this as well doesn't provide information about that octet which is invalid...
(by the way - what is wrong with your code? it's fine, really!)
I was just bored and wrote this regexp
public static boolean isValid(String ip) {
boolean isvalid;
isvalid = ip.matches(
"(([0-9]|[0-9]{0,2}|1[0-9]*{0,2}|2[0-5][0-5]|0{0,3}).){3}" +
"([0-9]|[0-9]{0,2}|1[0-9]*{0,2}|2[0-5][0-5]|0{0,3})"
);
return isvalid;
}
And it was tested on the following dataset:
String[] ips = {
"0.0.0.0",
"0.111.222.0",
"0.0.0.000",
"0.00.0.000",
"1.1.1.1",
"2.2.2.2",
"12.13.14.15",
"29.29.29.29",
"99.99.000.1",
"111.102.144.190",
"255.255.199.199",
"266.255.255.255", //inv
"255.265.255.255", //inv
"255.255.258.255", //inv
"255.255.255.259", //inv
"299.100.110.255" //inv
};
for (String s : ips) {
if (isValid(s) == false) {
System.err.println(s + " is invalid");
}
}

How to prevent my program from crashing due to a user's input

I am trying to implement an algorithm "recongnizng strings in a language "
L = {'w$w' : w is a possible empty string of characters other than $,
w' = reverse(w)}
my problem is whenever i input anything without having $, it crashes on the while loop. what will be the best way to prevent it from crashing?
public boolean isInLanguage(String inputString)
{
StackReferenceBased stack1 = new StackReferenceBased();
StackReferenceBased stack2 = new StackReferenceBased();
Object qItem;
Object sItem;
int index = 0;
if (inputString.length() == 0)
{
return false; // empty string not in L
}
else if (inputString.length() == 1)
{
return true;
}
**while (inputString.charAt(index) != '$')**
{
// save the first half of the string
stack1.push(inputString.charAt(index));
++index;
}
// index points to '$' or its value > than inputString.length()
while (index < inputString.length()-1)
{
// save the second half of the string
++index;
stack2.push(inputString.charAt(index));
}
do
{
// match the first half of the string with the second half
if ((stack1.isEmpty() && !stack2.isEmpty()) ||(!stack1.isEmpty() && stack2.isEmpty()))
{
return false;
}
qItem = stack1.peek();
sItem = stack2.peek();
if (qItem != sItem)
{
return false;
}
if (!stack1.isEmpty())
{
stack1.pop();
}
if (!stack2.isEmpty())
{
stack2.pop();
}
}while (!stack1.isEmpty() || !stack2.isEmpty());
if (stack1.isEmpty() && stack2.isEmpty())
{
return true;
}
else
{
return false;
}
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 4 at java.lang.String.charAt(Unknown
Source) at
assignmnet5.StackReferenceBased.isInLanguage(StackReferenceBased.java:87)
at assignmnet5.Question3.main(Question3.java:19)
this is my main:
public static void main(String[]args)
{
StackReferenceBased stack = new StackReferenceBased();
String str;
boolean bool;
Scanner kb = new Scanner(System.in);
System.out.println( "Enter a string to be checked by the algorithm : ");
str = kb.next();
**bool = stack.isInLanguage(str);**
if (bool == true)
System.out.println( "The string is in language");
else
System.out.println("The string is not in language");
}
It sounds like this might suffice:
if (inputString == null || !inputString.contains("$")) {
return false; // empty string not in L
}
possible issue is a null pointer exception, try to add this line in the top of your function
public boolean isInLanguage(String inputString)
{
if(inputString == null){
return false;
}
...
...
complete your code
if you still have crashes, you will need to provide the error you've got when you run the code.

Is there a Java utility to verify if a string is a valid HTML escape character?

I want a method in the following format:
public boolean isValidHtmlEscapeCode(String string);
Usage would be:
isValidHtmlEscapeCode("A") == false
isValidHtmlEscapeCode("&#1513;") == true // Valid unicode character
isValidHtmlEscapeCode("&#x5E9;") == true // same as 1513 but in HEX
isValidHtmlEscapeCode("&#78975332;") == false // Invalid unicode character
I wasn't able to find anything that does that - is there any utility that does that?
If not, is there any smart way to do it?
public static boolean isValidHtmlEscapeCode(String string) {
if (string == null) {
return false;
}
Pattern p = Pattern
.compile("&(?:#x([0-9a-fA-F]+)|#([0-9]+)|([0-9A-Za-z]+));");
Matcher m = p.matcher(string);
if (m.find()) {
int codePoint = -1;
String entity = null;
try {
if ((entity = m.group(1)) != null) {
if (entity.length() > 6) {
return false;
}
codePoint = Integer.parseInt(entity, 16);
} else if ((entity = m.group(2)) != null) {
if (entity.length() > 7) {
return false;
}
codePoint = Integer.parseInt(entity, 10);
} else if ((entity = m.group(3)) != null) {
return namedEntities.contains(entity);
}
return 0x00 <= codePoint && codePoint < 0xd800
|| 0xdfff < codePoint && codePoint <= 0x10FFFF;
} catch (NumberFormatException e) {
return false;
}
} else {
return false;
}
}
Here's the set of named entities http://pastebin.com/XzzMYDjF
you might want to have a look at Apache commons StringUtils:
http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/StringEscapeUtils.html#unescapeHtml(java.lang.String)
with the unescapeHtml you could do sth. like:
String input = "A";
String unescaped = StringEscapeUtils.unescapeHtml(input);
boolean containsValidEscape = !input.equals(a);
Not sure if this is a perfect solution, but you can use Apache Commons Lang:
try {
return StringEscapeUtils.unescapeHtml4(code).length() < code.length();
} catch (IllegalArgumentException e) {
return false;
}
This should be the method you wanted:
public static boolean isValidHtmlEscapeCode(String string) {
String temp = "";
try {
temp = StringEscapeUtils.unescapeHtml3(string);
} catch (IllegalArgumentException e) {
return false;
}
return !string.equals(temp);
}
Try matching using a regular expression:
public boolean isValidHtmlEscapeCode(String string) {
return string.matches("&;#([0-9]{1,4}|x[0-9a-fA-F]{1,4});");
}
Or to save some processing cycles you can reuse the regex for multiple comparisons:
Pattern pattern = Pattern.compile("&;#([0-9]{1,4}|x[0-9a-fA-F]{1,4});");
public boolean isValidHtmlEscapeCode(String string) {
return pattern.matches(string);
}
The source of the regex can be found at RexLib.com

Combine 2 Boolean statements to make another one

I am trying to combine two boolean statements in order to validate a number.
This is the code for the two functions:
public boolean numberOne(String number)
{
int a = Integer.parseInt(number);
if(a >= 0 && a <= 7 && number.length() <= 1) {
return true;
}
else {
return false;
}
}
public boolean numberTwo(String number)
{
int b = Integer.parseInt(number);
if(b >= 01 && b <= 15 && number.length() <= 2) {
return true;
}
else {
return false;
}
}
Now I want to create another Boolean function to validate this number when both combined e.g. 215 would be true and 645 would be false.
How can I do this?
Thanks
Two changes. The first is a side note. This code
if (long_test) {
return true;
} else {
return false;
}
should be rewritten as this:
return long_test;
The other change described by dampee once he gets his variable names to match.
Ok. So you want to split the string and have the first number of the string compared to the first function and the last two numbers compared to the second function?
public boolean numberThree (String number) {
String part1 = number.substring(0, 1);
String part2 = number.substring(1);
return numberOne(part1) && numberTwo(part2);
}

Categories

Resources