How to check if a String is numeric in Java

Question: How would you check if a String was a number before parsing it?
Comment: All the solutions proposed with regular expresions will not work for hexadecimal numbers.
Comment: and passing null string in matches(...) function will throw NullPointer  exception.
Comment: See Max Malysh's answer for a concise Java 8 solution without third-party libraries.
Comment: @HiteshSahu null strings seem to be gracefully handled in latest version (including Java 6.x and 7.x)
Comment: All the solutions proposed to use `Integer.parseInt()` will fail to parse mobile numbers with `NumberFormatException`.
Comment: @OscarCastiblanco _All_ strings are numbers in a given base.
Answer: This is generally done with a simple user-defined function (i.e. Roll-your-own "isNumeric" function).
Something like:
public static boolean isNumeric(String str) {
  try {
    Double.parseDouble(str);
    return true;
  } catch(NumberFormatException e){
    return false;
  }
}

However, if you're calling this function a lot, and you expect many of the checks to fail due to not being a number then performance of this mechanism will not be great, since you're relying upon exceptions being thrown for each failure, which is a fairly expensive operation.
An alternative approach may be to use a regular expression to check for validity of being a number:
public static boolean isNumeric(String str) {
  return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
}

Be careful with the above RegEx mechanism, though, as it will fail if you're using non-Arabic digits (i.e. numerals other than 0 through to 9).  This is because the "\d" part of the RegEx will only match [0-9] and effectively isn't internationally numerically aware.  (Thanks to OregonGhost for pointing this out!)
Or even another alternative is to use Java's built-in java.text.NumberFormat object to see if, after parsing the string the parser position is at the end of the string.  If it is, we can assume the entire string is numeric:
public static boolean isNumeric(String str) {
  ParsePosition pos = new ParsePosition(0);
  NumberFormat.getInstance().parse(str, pos);
  return str.length() == pos.getIndex();
}

Comment: Note that the `.` in your regex will match any character, not just the decimal separator character.
Comment: Note that there are no such things as "latin numerals", and the numerals 0-9 are in fact Arabic numerals. People are probably familar with Roman numerals, which were used by people who spoke Latin, in the form I, II, III, IV, V, VI, etc. https://en.wikipedia.org/wiki/Arabic_numerals; https://en.wikipedia.org/wiki/Roman_numerals
Comment: +1 for realizing the expense of try/catch.  This is actually a horrible approach to use in the long run for repeated use, but really we are stuck with that in Java.
Comment: Does \d in Java Regex match only latin digits? If it's like .NET regexes, you'll run into a problem with other (e.g. arabic) digits, as explained here: http://blogs.msdn.com/oldnewthing/archive/2004/03/09/86555.aspx
Comment: the numberFormatter solution is probably only marginally better than catching the NumberFormatException one. I suspect the best way is to use regex one.
Comment: In the last proposition (NumberFormat), you are missing a null check at the parse method. Otherwise isNumeric("") will return true as position index will stay unchanged !
Comment: Both solutions are bad if used extensibly. Throwing exception is costly and creating a regular expressions is costly as well. The regular expression must be created once and reused.
Comment: To handle exponent (**+1.3E10**): `return str.matches("\\d") && str.matches("^[+-]?\\d*\\.?\\d*([eE]\\d)?\\d*$");`
Comment: also, don't forget `.006` and `0.`- those are valid too.
Comment: I would use the regex of `(\\+|-)?\\d+(\\.\\d+)?` as `"+1.20"` is a valid numeric value.
Comment: Keep in mind that: Double.parseDouble("NaN") <-- doesn't throw and Exception.
Comment: @user1096901 I'm well aware of the consequences of using exceptions to validate data, and I even say why it's not necessarily the best approach within my answer. I then go on to offer alternatives thatare probably better options. All approaches are detailed to give as complete and balanced an answer as possible
Comment: @fchen, right idea, but the 'E' in a scientific notation may also be followed by a '+' or '-'.
Comment: In this case the RegEx is 10 times slower than processing the exception. See for yourself with the code in my answer below.
Comment: Brilliant, even working for foreign numbers, like Gujarati (૧૦૦) , Asturian (২০১৯), Tibetan (৬৫), Bengali (႑), Hebrew (8), Japanese (15), Khmer (២០១៥),,, let's say most
Comment: @OregonGhost - Oops.. Good catch.  You're right. \d will only match latin digits (i.e. 0 through to 9 effectively) and fail with arabic ones.  I've edited my posted to make this clear.  Thanks!
Comment: what if the string is 2.2E8
Comment: What if the string uses a different decimal separator such as `,`?
Comment: @Eddnav  The first approach (using Double.parseDouble) will not work for numbers with different decimal separators, however, the last approach shown in my answer (using the java.text.NumberFormat class) does work correctly for alternative decimal separators (at least it works for a comma).  See here: https://ideone.com/vaOEae
Comment: Ran this (the Double.parseDouble and regex) in comparison to converting string to char[] and running isDigit over it, and running the char[] vs. an array of acceptable chars. Comparison was done via running time with System.nanoTime(). They all came out to about the same with a 2500 character long string with either no non-digits, or at least 1 non digit.
Comment: the first is numeric with: double d = Double.parseDouble(str);
returns true if the string is like this "0F" :-)
Comment: It is self0evidently self-evidently pointless to call `Integer.parseInt()` twice on the same input. The correct solution is to call it once, when needed, and catch and deal with the `NumberFormatException` as it arises.
Comment: This(your first approach) is exactly how I did it when creating a mathematical parser about 11 years ago. You can find the project at https://github.com/gbenroscience/ParserNG
Answer: With Apache Commons Lang 3.5 and above: NumberUtils.isCreatable or StringUtils.isNumeric.
With Apache Commons Lang 3.4 and below: NumberUtils.isNumber or StringUtils.isNumeric.
You can also use StringUtils.isNumericSpace which returns true for empty strings  and ignores internal spaces in the string. Another way is to use NumberUtils.isParsable which basically checks the number is parsable according to Java. (The linked javadocs contain detailed examples for each method.)
Comment: `StringUtils.isNumeric()` probably wouldn't be appropriate here since it only checks if the string is a sequence of digits.  Would be fine for most ints but not so for numbers with decimals, group separators, etc.
Comment: reinvent the wheel because you don't include a whole library because you need a 3 line function in one place.
Comment: Is it really worth adding a **whole** library for this feature though? Obviously if it's used with other stuff that's great, but it's probably overkill considering people have solved this in one line of code.
Comment: @PaulDraper: You're right, `StringUtils` does not support leading signs but you should check `NumberUtils.isCreatable`, it supports negatives properly.
Comment: Doesn't work with negatives. And half of all numbers are negative, so.....
Comment: @JUG: thx for the heads up. Strange enough, the doc linked says the opposite, maybe because of a newer version (note that the answer was edited just a few days after your comment was posted)
Comment: @JUG: searched into it & that's what I thought, some previous versions ie. [Commons Lang version 2.4 stringutils.isNumeric() behaves as you said (return true for empty String)](http://commons.apache.org/proper/commons-lang/javadocs/api-2.4/org/apache/commons/lang/StringUtils.html#isNumeric(java.lang.String))
Comment: NumberUtils.isParsable(String str)  method could be used to check if the given string is numeric, which would work for all the scenarios.
Comment: Pretty old question but just for anyone who is reading for help - StringUtils.isNumeric won't work also if it is empty String. It will return true for empty String for StringUtils.isNumeric().
Comment: Here is all the ways:
https://www.baeldung.com/java-check-string-number
Comment: Why does isNumeric return true for question marks? https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isNumeric(java.lang.CharSequence)
Comment: @pete: Those question marks seem to be Devanagari digits (which probably are not supported by our fonts/browser). See: https://issues.apache.org/jira/browse/LANG-1017
Comment: Adding a dependency to check if a string is a number... Wow
Comment: In this case I would add a library dependency even though not enough programmers scrutinize doing so (if you have to support exponents). For those who really don't want to, you could copy and paste the source directly: https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/math/NumberUtils.java#L1622
Answer: Java 8 lambda expressions.
String someString = "123123";
boolean isNumeric = someString.chars().allMatch( Character::isDigit );

Comment: What will it produce for "-1"?
Comment: This answer is concise, simple and readable. You can almost read it like English -- "chars all match digits". It requires no third-party libraries. It does not use exceptions in non-exceptional cases. This should become the accepted answer.
Comment: Not the right answer. A numeric string can have non-numeric characters (ex. "." or "-") and still be perfectly numerical. For example 0.5, -1, and 1,000 will all fail with this answer and yet they are perfectly numerical.
Comment: You can use a method reference, too: someString.chars().allMatch(Character::isDigit)
Comment: Nice but still it's reinventing the wheel as almost all "solutions" here. Also, fails on 'null' (as almost all the others).
Comment: @Adrian here is a benchmark: https://gist.github.com/maxmalysh/8f656be2843b7c35849a2eae2683df0e . 9ms for a 1 million character length string. 169ms for a 5k character length string is something way too off the mark.
Comment: @Adrian - In a universe of 10^80 atoms, there aren't that many useful 5135-character numbers. If candidate strings can be long, a length test could be applied beforehand. Optimization can be necessary. It can also be premature. Correctness may be a larger issue. It's worth noting that this answer (and some others) only detect positive integers. It will fail if required to detect negatives, reals, hexadecimal, scientific notation ...
Comment: It won't work for Negative Numbers, nor for decimal numbers.
Comment: @AndyThomas for a 5135 character length string of numbers it takes 169,424,664 nanoseconds, or 169.424664 milliseconds (on my machine). This is way too inefficient. You can get 15 ms times or less running a nested for-loop to compare characters against a char[] of acceptable characters.
Answer: if you are on android, then you should use:
android.text.TextUtils.isDigitsOnly(CharSequence str)

documentation can be found here
keep it simple. mostly everybody can "re-program" (the same thing).
Comment: Note: this results in NPE for null input. Also, doesn't work with negative numbers or decimals.
Comment: @kape123 :) sure "123.456" doesn´t contain digits.
Comment: I like it!! I think this is absolutely for digits. Not for `.`, `-`
Comment: This is just what I was looking for. Something simple to check for only digits 0-9. I set a filter in the declaration of my EditText but just in case that get's changed or replaced down the road it's nice to have a simple programmatic check as well.
Comment: Why this method returns true for empty strings?
Answer: As @CraigTP had mentioned in his excellent answer, I also have similar performance concerns on using Exceptions to test whether the string is numerical or not. So I end up splitting the string and use java.lang.Character.isDigit().
public static boolean isNumeric(String str)
{
    for (char c : str.toCharArray())
    {
        if (!Character.isDigit(c)) return false;
    }
    return true;
}

According to the Javadoc, Character.isDigit(char) will correctly recognizes non-Latin digits. Performance-wise, I think a simple N number of comparisons where N is the number of characters in the string would be more computationally efficient than doing a regex matching.
UPDATE: As pointed by Jean-François Corbett in the comment, the above code would only validate positive integers, which covers the majority of my use case. Below is the updated code that correctly validates decimal numbers according to the default locale used in your system, with the assumption that decimal separator only occur once in the string.
public static boolean isStringNumeric( String str )
{
    DecimalFormatSymbols currentLocaleSymbols = DecimalFormatSymbols.getInstance();
    char localeMinusSign = currentLocaleSymbols.getMinusSign();

    if ( !Character.isDigit( str.charAt( 0 ) ) && str.charAt( 0 ) != localeMinusSign ) return false;

    boolean isDecimalSeparatorFound = false;
    char localeDecimalSeparator = currentLocaleSymbols.getDecimalSeparator();

    for ( char c : str.substring( 1 ).toCharArray() )
    {
        if ( !Character.isDigit( c ) )
        {
            if ( c == localeDecimalSeparator && !isDecimalSeparatorFound )
            {
                isDecimalSeparatorFound = true;
                continue;
            }
            return false;
        }
    }
    return true;
}

Comment: Calling `toCharArray()` will create a copy of the array in the String object because Strings are immutable. Probably faster to use the `charAt(int index)` method on the String object directly.
Comment: Does -ve sign fail this function?
Comment: Will generate `StringIndexOutOfBoundsException` when passed a string with length 0. Can be fixed with `if(str.length() == 0) return false;`
Comment: I think this should be the accepted answer because it is the lightest solution. Using an exception or a regex are both really heavy to check if a string is numeric. Iterating over the characters is nice and simple!
Comment: The above code accepts a single '-' as numeric and will return true. change first `if` to something like: `boolean isMinus = str.charAt(0) == localeMinusSign; if ((isMinus && str.length() < 2) || ((!isMinus) && !Character.isDigit(str.charAt(0)))) { return false; }`
Answer: Google's Guava library provides a nice helper method to do this: Ints.tryParse. You use it like Integer.parseInt but it returns null rather than throw an Exception if the string does not parse to a valid integer. Note that it returns Integer, not int, so you have to convert/autobox it back to int.
Example:
String s1 = "22";
String s2 = "22.2";
Integer oInt1 = Ints.tryParse(s1);
Integer oInt2 = Ints.tryParse(s2);

int i1 = -1;
if (oInt1 != null) {
    i1 = oInt1.intValue();
}
int i2 = -1;
if (oInt2 != null) {
    i2 = oInt2.intValue();
}

System.out.println(i1);  // prints 22
System.out.println(i2);  // prints -1

However, as of the current release -- Guava r11 -- it is still marked @Beta.
I haven't benchmarked it. Looking at the source code there is some overhead from a lot of sanity checking but in the end they use Character.digit(string.charAt(idx)), similar, but slightly different from, the answer from @Ibrahim above. There is no exception handling overhead under the covers in their implementation.
Comment: Beware that this would throw NPE in case argument is null.
Answer: Do not use Exceptions to validate your values.
Use Util libs instead like apache NumberUtils:
NumberUtils.isNumber(myStringValue);

Edit:
Please notice that, if your string starts with an 0, NumberUtils will interpret your value as hexadecimal.
NumberUtils.isNumber("07") //true
NumberUtils.isNumber("08") //false

Comment: The accepted answer, three years earlier, already covered `Number.isNumber()`.
Comment: @Goot - The history of the accepted answer shows that `Number.isNumber()` was present from the first version of the answer, dated Sep 24 '12 at 17:01.
Comment: I don't think so. It was updated or op changed the accepted answer. I remember the accepted answer didn't covered NumberUtils thats why I added my answer. But thanks for the comment
Comment: @Goot, this is pretty good as it also covers the decimal value check, unlike StringUtils.
Answer: Why is everyone pushing for exception/regex solutions?
While I can understand most people are fine with using try/catch, if you want to do it frequently... it can be extremely taxing.
What I did here was take the regex, the parseNumber() methods, and the array searching method to see which was the most efficient. This time, I only looked at integer numbers.
public static boolean isNumericRegex(String str) {
    if (str == null)
        return false;
    return str.matches("-?\\d+");
}

public static boolean isNumericArray(String str) {
    if (str == null)
        return false;
    char[] data = str.toCharArray();
    if (data.length <= 0)
        return false;
    int index = 0;
    if (data[0] == '-' && data.length > 1)
        index = 1;
    for (; index < data.length; index++) {
        if (data[index] < '0' || data[index] > '9') // Character.isDigit() can go here too.
            return false;
    }
    return true;
}

public static boolean isNumericException(String str) {
    if (str == null)
        return false;
    try {
        /* int i = */ Integer.parseInt(str);
    } catch (NumberFormatException nfe) {
        return false;
    }
    return true;
}

The results in speed I got were:
Done with: for (int i = 0; i < 10000000; i++)...

With only valid numbers ("59815833" and "-59815833"):
    Array numeric took 395.808192 ms [39.5808192 ns each]
    Regex took 2609.262595 ms [260.9262595 ns each]
    Exception numeric took 428.050207 ms [42.8050207 ns each]
    // Negative sign
    Array numeric took 355.788273 ms [35.5788273 ns each]
    Regex took 2746.278466 ms [274.6278466 ns each]
    Exception numeric took 518.989902 ms [51.8989902 ns each]
    // Single value ("1")
    Array numeric took 317.861267 ms [31.7861267 ns each]
    Regex took 2505.313201 ms [250.5313201 ns each]
    Exception numeric took 239.956955 ms [23.9956955 ns each]
    // With Character.isDigit()
    Array numeric took 400.734616 ms [40.0734616 ns each]
    Regex took 2663.052417 ms [266.3052417 ns each]
    Exception numeric took 401.235906 ms [40.1235906 ns each]

With invalid characters ("5981a5833" and "a"):
    Array numeric took 343.205793 ms [34.3205793 ns each]
    Regex took 2608.739933 ms [260.8739933 ns each]
    Exception numeric took 7317.201775 ms [731.7201775 ns each]
    // With a single character ("a")
    Array numeric took 291.695519 ms [29.1695519 ns each]
    Regex took 2287.25378 ms [228.725378 ns each]
    Exception numeric took 7095.969481 ms [709.5969481 ns each]

With null:
    Array numeric took 214.663834 ms [21.4663834 ns each]
    Regex took 201.395992 ms [20.1395992 ns each]
    Exception numeric took 233.049327 ms [23.3049327 ns each]
    Exception numeric took 6603.669427 ms [660.3669427 ns each] if there is no if/null check

Disclaimer: I'm not claiming these methods are 100% optimized, they're just for demonstration of the data
Exceptions won if and only if the number is 4 characters or less, and every string is always a number... in which case, why even have a check?
In short, it is extremely painful if you run into invalid numbers frequently with the try/catch, which makes sense. An important rule I always follow is NEVER use try/catch for program flow. This is an example why.
Interestingly, the simple if char <0 || >9 was extremely simple to write, easy to remember (and should work in multiple languages) and wins almost all the test scenarios.
The only downside is that I'm guessing Integer.parseInt() might handle non ASCII numbers, whereas the array searching method does not.

For those wondering why I said it's easy to remember the character array one, if you know there's no negative signs, you can easily get away with something condensed as this:
public static boolean isNumericArray(String str) {
    if (str == null)
        return false;
    for (char c : str.toCharArray())
        if (c < '0' || c > '9')
            return false;
    return true;

Lastly as a final note, I was curious about the assigment operator in the accepted example with all the votes up. Adding in the assignment of
double d = Double.parseDouble(...)

is not only useless since you don't even use the value, but it wastes processing time and increased the runtime by a few nanoseconds (which led to a 100-200 ms increase in the tests). I can't see why anyone would do that since it actually is extra work to reduce performance.
You'd think that would be optimized out... though maybe I should check the bytecode and see what the compiler is doing. That doesn't explain why it always showed up as lengthier for me though if it somehow is optimized out... therefore I wonder what's going on. As a note: By lengthier, I mean running the test for 10000000 iterations, and running that program multiple times (10x+) always showed it to be slower.
EDIT: Updated a test for Character.isDigit()
Comment: Doesn't this compile a new regular expression every time?  That doesn't seem very efficient.
Comment: @SamuelEdwinWard Thats the *whole* reason I made this post... the regex example used other people's provided answers and showed how inefficient it is. Even if you attempt regex with pre-compiling it ahead of time and only using that, the time differences are: 2587 ms for the regex I posted from other provided people, 950 ms when compiled ahead of time, 144 ms when doing it as a numeric array (for 1 mil iterations of the same string). Compiling ahead of time obviously would help, but sadly it's still quite inferior to the array way... unless there's some insane optimization I don't know of.
Comment: Believing that Regex makes things faster is almost a fallacy. If its a one off search, yeah, I get it... but I have noticed efficiently written code actually outdoes regex enough to shock you! Great post @Water
Answer: public static boolean isNumeric(String str)
{
    return str.matches("-?\\d+(.\\d+)?");
}

CraigTP's regular expression (shown above) produces some false positives.  E.g. "23y4" will be counted as a number because '.' matches any character not the decimal point.
Also it will reject any number with a leading '+'
An alternative which avoids these two minor problems is
public static boolean isNumeric(String str)
{
    return str.matches("[+-]?\\d*(\\.\\d+)?");
}

Comment: you should change it to `matches("-?\\d+([.]\\d+)?")`
Comment: this will return `true` for a single plus `"+"` or minus `"-"`, and `false` for `"0."`
Comment: Good catch on the single plus or minus. Is "0." a valid number ?
Comment: `"0."` is valid for `Double.parseDouble()` and is a valid literal according the JLS ([§3.10.2](http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.2))!
Comment: Creating a regular expressions is costly as well. The regular expression must be created once and reused
Comment: Also, this matches an empty string. `[+-]?(\\d\\.)?\\d+` should work better
Comment: Why is every Regex solution supposing the Local Decimal format to be a '.'(dot) and not a ','(comma) like in some EU countries?!
Answer: We can try replacing all the numbers from the given string with ("") ie blank space and if after that the length of the string is zero then we can say that given string contains only numbers.
Example:
boolean isNumber(String str){
        if(str.length() == 0)
            return false; //To check if string is empty

        if(str.charAt(0) == '-')
            str = str.replaceFirst("-","");// for handling -ve numbers

        System.out.println(str);

        str = str.replaceFirst("\\.",""); //to check if it contains more than one decimal points

        if(str.length() == 0)
            return false; // to check if it is empty string after removing -ve sign and decimal point
        System.out.println(str);

        return str.replaceAll("[0-9]","").length() == 0;
    }

Comment: So `""` is a number but `"3.14"` and `"-1"` aren't?
Comment: Evidently doesn't apply to all number forms, but here's an upvote for thinking differently...if the original thought was yours, that is.
Answer: You can use NumberFormat#parse:
try
{
     NumberFormat.getInstance().parse(value);
}
catch(ParseException e)
{
    // Not a number.
}

Comment: Costly if used extensibly
Comment: It also will pass if there are garbage characters at the end of `value`.
Comment: This worked for the number format 0x0001 where Double.parseDouble wasn't working. +1
Comment: Offered an edit - .getInstance() was missing. +1 as this was the answer I went with when finding this question.
Comment: It would create a sonar issue if you don't log the exception
Answer: If you using java to develop Android app, you could using TextUtils.isDigitsOnly function.
Comment: already posted here: https://stackoverflow.com/a/20154903/191761 see the comments for some issues with this solution
Answer: Here was my answer to the problem.
A catch all convenience method which you can use to parse any String with any type of parser: isParsable(Object parser, String str). The parser can be a Class or an object. This will also allows you to use custom parsers you've written and should work for ever scenario, eg:
isParsable(Integer.class, "11");
isParsable(Double.class, "11.11");
Object dateFormater = new java.text.SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
isParsable(dateFormater, "2001.07.04 AD at 12:08:56 PDT");

Here's my code complete with method descriptions.
import java.lang.reflect.*;

/**
 * METHOD: isParsable

 *
 * This method will look through the methods of the specified from parameter
 * looking for a public method name starting with "parse" which has only one String
 * parameter.

 *
 * The parser parameter can be a class or an instantiated object, eg:
 * Integer.class or new Integer(1). If you use a
 * Class type then only static methods are considered.

 *
 * When looping through potential methods, it first looks at the Class associated
 * with the parser parameter, then looks through the methods of the parent's class
 * followed by subsequent ancestors, using the first method that matches the criteria specified
 * above.

 *
 * This method will hide any normal parse exceptions, but throws any exceptions due to
 * programmatic errors, eg: NullPointerExceptions, etc. If you specify a parser
 * parameter which has no matching parse methods, a NoSuchMethodException will be thrown
 * embedded within a RuntimeException.

 *
 * Example:

 * isParsable(Boolean.class, "true");

 * isParsable(Integer.class, "11");

 * isParsable(Double.class, "11.11");

 * Object dateFormater = new java.text.SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");

 * isParsable(dateFormater, "2001.07.04 AD at 12:08:56 PDT");

 *

 *
 * @param parser    The Class type or instantiated Object to find a parse method in.
 * @param str   The String you want to parse
 *
 * @return true if a parse method was found and completed without exception
 * @throws java.lang.NoSuchMethodException If no such method is accessible
 */
public static boolean isParsable(Object parser, String str) {
    Class theClass = (parser instanceof Class? (Class)parser: parser.getClass());
    boolean staticOnly = (parser == theClass), foundAtLeastOne = false;
    Method[] methods = theClass.getMethods();

    // Loop over methods
    for (int index = 0; index < methods.length; index++) {
        Method method = methods[index];

        // If method starts with parse, is public and has one String parameter.
        // If the parser parameter was a Class, then also ensure the method is static.
        if(method.getName().startsWith("parse") &&
            (!staticOnly || Modifier.isStatic(method.getModifiers())) &&
            Modifier.isPublic(method.getModifiers()) &&
            method.getGenericParameterTypes().length == 1 &&
            method.getGenericParameterTypes()[0] == String.class)
        {
            try {
                foundAtLeastOne = true;
                method.invoke(parser, str);
                return true; // Successfully parsed without exception
            } catch (Exception exception) {
                // If invoke problem, try a different method
                /*if(!(exception instanceof IllegalArgumentException) &&
                   !(exception instanceof IllegalAccessException) &&
                   !(exception instanceof InvocationTargetException))
                        continue; // Look for other parse methods*/

                // Parse method refuses to parse, look for another different method
                continue; // Look for other parse methods
            }
        }
    }

    // No more accessible parse method could be found.
    if(foundAtLeastOne) return false;
    else throw new RuntimeException(new NoSuchMethodException());
}

/**
 * METHOD: willParse

 *
 * A convienence method which calls the isParseable method, but does not throw any exceptions
 * which could be thrown through programatic errors.

 *
 * Use of {@link #isParseable(Object, String) isParseable} is recommended for use so programatic
 * errors can be caught in development, unless the value of the parser parameter is
 * unpredictable, or normal programtic exceptions should be ignored.

 *
 * See {@link #isParseable(Object, String) isParseable} for full description of method
 * usability.

 *
 * @param parser    The Class type or instantiated Object to find a parse method in.
 * @param str   The String you want to parse
 *
 * @return true if a parse method was found and completed without exception
 * @see #isParseable(Object, String) for full description of method usability
 */
public static boolean willParse(Object parser, String str) {
    try {
        return isParsable(parser, str);
    } catch(Throwable exception) {
        return false;
    }
}

Answer: A well-performing approach avoiding try-catch and handling negative numbers and scientific notation.
Pattern PATTERN = Pattern.compile( "^(-?0|-?[1-9]\\d*)(\\.\\d+)?(E\\d+)?$" );

public static boolean isNumeric( String value )
{
    return value != null && PATTERN.matcher( value ).matches();
}

Answer: To match only positive base-ten integers, that contains only ASCII digits, use:
public static boolean isNumeric(String maybeNumeric) {
    return maybeNumeric != null && maybeNumeric.matches("[0-9]+");
}

Answer: Here is my class for checking if a string is numeric. It also fixes numerical strings:
Features:

Removes unnecessary zeros ["12.0000000" -> "12"]
Removes unnecessary zeros ["12.0580000" -> "12.058"]
Removes non numerical characters ["12.00sdfsdf00" -> "12"]
Handles negative string values ["-12,020000" -> "-12.02"]
Removes multiple dots ["-12.0.20.000" -> "-12.02"]
No extra libraries, just standard Java

Here you go...
public class NumUtils {
    /**
     * Transforms a string to an integer. If no numerical chars returns a String "0".
     *
     * @param str
     * @return retStr
     */
    static String makeToInteger(String str) {
        String s = str;
        double d;
        d = Double.parseDouble(makeToDouble(s));
        int i = (int) (d + 0.5D);
        String retStr = String.valueOf(i);
        System.out.printf(retStr + "   ");
        return retStr;
    }

    /**
     * Transforms a string to an double. If no numerical chars returns a String "0".
     *
     * @param str
     * @return retStr
     */
    static String makeToDouble(String str) {

        Boolean dotWasFound = false;
        String orgStr = str;
        String retStr;
        int firstDotPos = 0;
        Boolean negative = false;

        //check if str is null
        if(str.length()==0){
            str="0";
        }

        //check if first sign is "-"
        if (str.charAt(0) == '-') {
            negative = true;
        }

        //check if str containg any number or else set the string to '0'
        if (!str.matches(".*\\d+.*")) {
            str = "0";
        }

        //Replace ',' with '.'  (for some european users who use the ',' as decimal separator)
        str = str.replaceAll(",", ".");
        str = str.replaceAll("[^\\d.]", "");

        //Removes the any second dots
        for (int i_char = 0; i_char < str.length(); i_char++) {
            if (str.charAt(i_char) == '.') {
                dotWasFound = true;
                firstDotPos = i_char;
                break;
            }
        }
        if (dotWasFound) {
            String befDot = str.substring(0, firstDotPos + 1);
            String aftDot = str.substring(firstDotPos + 1, str.length());
            aftDot = aftDot.replaceAll("\\.", "");
            str = befDot + aftDot;
        }

        //Removes zeros from the begining
        double uglyMethod = Double.parseDouble(str);
        str = String.valueOf(uglyMethod);

        //Removes the .0
        str = str.replaceAll("([0-9])\\.0+([^0-9]|$)", "$1$2");

        retStr = str;

        if (negative) {
            retStr = "-"+retStr;
        }

        return retStr;

    }

    static boolean isNumeric(String str) {
        try {
            double d = Double.parseDouble(str);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }

}

Answer:
Regex Matching

Here is another example upgraded "CraigTP" regex matching with more validations.
public static boolean isNumeric(String str)
{
    return str.matches("^(?:(?:\\-{1})?\\d+(?:\\.{1}\\d+)?)$");
}

Only one negative sign - allowed and must be in beginning.
After negative sign there must be digit.
Only one decimal sign . allowed.
After decimal sign there must be digit.

Regex Test

1                  --                   **VALID**
1.                 --                   INVALID
1..                --                   INVALID
1.1                --                   **VALID**
1.1.1              --                   INVALID

-1                 --                   **VALID**
--1                --                   INVALID
-1.                --                   INVALID
-1.1               --                   **VALID**
-1.1.1             --                   INVALID

Answer: Exceptions are expensive, but in this case the RegEx takes much longer. The code below shows a simple test of two functions -- one using exceptions and one using regex. On my machine the RegEx version is 10 times slower than the exception.
import java.util.Date;

public class IsNumeric {

public static boolean isNumericOne(String s) {
    return s.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
}

public static boolean isNumericTwo(String s) {
    try {
        Double.parseDouble(s);
        return true;
    } catch (Exception e) {
        return false;
    }
}

public static void main(String [] args) {

    String test = "12345.F";

    long before = new Date().getTime();
    for(int x=0;x<1000000;++x) {
        //isNumericTwo(test);
        isNumericOne(test);
    }
    long after = new Date().getTime();

    System.out.println(after-before);

}

}

Comment: Generally, I think this sort of code would be used to check things like typed input. In that case speed is not a consideration and doing something as ugly as throwing an exception to check for number or non-number is wrong.
Comment: Maybe not. Typed input is generally checked by the UI component where errors can be immediately shown before submitting the value. It might be more common to be validating strings from large input text files -- where performance matters. The goal in my answer here is to address the "exceptions are slow" statement in the accepted answer. Complex regex is much more expensive. And there is no "ugly throw" in my code at all -- just a faster way to detect violations. With a check-first-then-calculate approach you make two passes through the input: one to verify and then another to convert.
Comment: "On my machine the RegEx version is 10 times slower than the exception." - that's only because you test value that is numeric, so exception in never thrown. Test this on not numeric value, and version with exception will be slower than regex one.
Comment: Excellent point. I thought that adding an "F" on the end would make it not numeric, but the java "parseDouble" likes it. I stand corrected.
Answer: // please check below code
public static boolean isDigitsOnly(CharSequence str) {
    final int len = str.length();
    for (int i = 0; i < len; i++) {
        if (!Character.isDigit(str.charAt(i))) {
            return false;
        }
    }
    return true;
}

Comment: The question says "numeric" which could include non-integer values.
Answer: You can use the java.util.Scanner object.
public static boolean isNumeric(String inputData) {
      Scanner sc = new Scanner(inputData);
      return sc.hasNextInt();
    }

Answer: I have illustrated some conditions to check numbers and decimals without using any API,
Check Fix Length 1 digit number
Character.isDigit(char)

Check Fix Length number (Assume length is 6)
String number = "132452";
if(number.matches("([0-9]{6})"))
System.out.println("6 digits number identified");

Check Varying Length number between (Assume 4 to 6 length)
//  {n,m}  n <= length <= m
String number = "132452";
if(number.matches("([0-9]{4,6})"))
System.out.println("Number Identified between 4 to 6 length");

String number = "132";
if(!number.matches("([0-9]{4,6})"))
System.out.println("Number not in length range or different format");

Check Varying Length decimal number between (Assume 4 to 7 length)
//  It will not count the '.' (Period) in length
String decimal = "132.45";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "1.12";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "1234";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "-10.123";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "123..4";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");

String decimal = "132";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");

String decimal = "1.1";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");

Hope it will help manyone.
Answer: // only int
public static boolean isNumber(int num)
{
    return (num >= 48 && c <= 57); // 0 - 9
}

// is type of number including . - e E
public static boolean isNumber(String s)
{
    boolean isNumber = true;
    for(int i = 0; i < s.length() && isNumber; i++)
    {
        char c = s.charAt(i);
        isNumber = isNumber & (
            (c >= '0' && c <= '9') || (c == '.') || (c == 'e') || (c == 'E') || (c == '')
        );
    }
    return isInteger;
}

// is type of number
public static boolean isInteger(String s)
{
    boolean isInteger = true;
    for(int i = 0; i < s.length() && isInteger; i++)
    {
        char c = s.charAt(i);
        isInteger = isInteger & ((c >= '0' && c <= '9'));
    }
    return isInteger;
}

public static boolean isNumeric(String s)
{
    try
    {
        Double.parseDouble(s);
        return true;
    }
    catch (Exception e)
    {
        return false;
    }
}

Answer: This a simple example for this check:
public static boolean isNumericString(String input) {
    boolean result = false;

    if(input != null && input.length() > 0) {
        char[] charArray = input.toCharArray();

        for(char c : charArray) {
            if(c >= '0' && c <= '9') {
                // it is a digit
                result = true;
            } else {
                result = false;
                break;
            }
        }
    }

    return result;
}

Answer: Based off of other answers I wrote my own and it doesn't use patterns or parsing with exception checking.
It checks for a maximum of one minus sign and checks for a maximum of one decimal point.
Here are some examples and their results:
"1", "-1", "-1.5" and "-1.556" return true
"1..5", "1A.5", "1.5D", "-" and "--1" return false
Note: If needed you can modify this to accept a Locale parameter and pass that into the DecimalFormatSymbols.getInstance() calls to use a specific Locale instead of the current one.
 public static boolean isNumeric(final String input) {
    //Check for null or blank string
    if(input == null || input.isBlank()) return false;

    //Retrieve the minus sign and decimal separator characters from the current Locale
    final var localeMinusSign = DecimalFormatSymbols.getInstance().getMinusSign();
    final var localeDecimalSeparator = DecimalFormatSymbols.getInstance().getDecimalSeparator();

    //Check if first character is a minus sign
    final var isNegative = input.charAt(0) == localeMinusSign;
    //Check if string is not just a minus sign
    if (isNegative && input.length() == 1) return false;

    var isDecimalSeparatorFound = false;

    //If the string has a minus sign ignore the first character
    final var startCharIndex = isNegative ? 1 : 0;

    //Check if each character is a number or a decimal separator
    //and make sure string only has a maximum of one decimal separator
    for (var i = startCharIndex; i < input.length(); i++) {
        if(!Character.isDigit(input.charAt(i))) {
            if(input.charAt(i) == localeDecimalSeparator && !isDecimalSeparatorFound) {
                isDecimalSeparatorFound = true;
            } else return false;
        }
    }
    return true;
}

Answer: For non-negative number use this
public boolean isNonNegativeNumber(String str) {
  return str.matches("\\d+");
}

For any number use this
public boolean isNumber(String str) {
  return str.matches("-?\\d+");
}

Answer: Parse it (i.e. with Integer#parseInt ) and simply catch the exception. =)
To clarify: The parseInt function checks if it can parse the number in any case (obviously) and if you want to parse it anyway, you are not going to take any performance hit by actually doing the parsing.
If you would not want to parse it (or parse it very, very rarely) you might wish to do it differently of course.
Comment: Costly if used extensibly
Comment: It would create a sonar issue if you don't log the exception
Comment: Double.parseDouble
Answer: That's why I like the Try* approach in .NET. In addition to the traditional Parse method that's like the Java one, you also have a TryParse method. I'm not good in Java syntax (out parameters?), so please treat the following as some kind of pseudo-code. It should make the concept clear though.
boolean parseInteger(String s, out int number)
{
    try {
        number = Integer.parseInt(myString);
        return true;
    } catch(NumberFormatException e) {
        return false;
    }
}

Usage:
int num;
if (parseInteger("23", out num)) {
    // Do something with num.
}

Comment: I like C# as much as the next guy, but its no use adding a .NET C# code snippet for a Java question when the features don't exist in Java
Comment: yep, there's no "out parameters" in Java and since the Integer wrapper is immutable (thus cannot be used as a valid reference to store the output), the sensible idiomatic option would be to return an Integer object that could be null if the parse failed. An uglier option could be to pass an int[1] as output parameter.
Comment: Yes, I remember a discussion about why Java has no output parameters. but returning an Integer (as null, if needed) would be fine too, I guess, though I don't know about Java's performance with regard to boxing/unboxing.
Comment: It would create a sonar issue if you don't log the exception
Answer: I modified CraigTP's solution to accept scientific notation and both dot and comma as decimal separators as well
^-?\d+([,\.]\d+)?([eE]-?\d+)?$

example
var re = new RegExp("^-?\d+([,\.]\d+)?([eE]-?\d+)?$");
re.test("-6546"); // true
re.test("-6546355e-4456"); // true
re.test("-6546.355e-4456"); // true, though debatable
re.test("-6546.35.5e-4456"); // false
re.test("-6546.35.5e-4456.6"); // false

Answer: Java 8 Stream, lambda expression, functional interface
All cases handled (string null, string empty etc)
String someString = null; // something="", something="123abc", something="123123"

boolean isNumeric = Stream.of(someString)
            .filter(s -> s != null && !s.isEmpty())
            .filter(Pattern.compile("\\D").asPredicate().negate())
            .mapToLong(Long::valueOf)
            .boxed()
            .findAny()
            .isPresent();

Answer: You can use NumberUtils.isCreatable() from Apache Commons Lang.
Since NumberUtils.isNumber will be deprecated in 4.0, so use  NumberUtils.isCreatable() instead.
Answer: I think the only way to reliably tell if a string is a number, is to parse it. So I would just parse it, and if it's a number, you get the number in an int for free!
Answer: You could use BigDecimal if the string may contain decimals:
try {
    new java.math.BigInteger(testString);
} catch(NumberFormatException e) {
    throw new RuntimeException("Not a valid number");
}

Comment: Welcome to stackoverflow. Generally, it is best to avoid resurrecting old threads unless the response adds something significantly different to the thread. While valid, that approach was already mentioned in the accepted answer.
Comment: It would create a sonar issue if you don't log the exception
Answer: Here are two methods that might work. (Without using Exceptions).
Note : Java is a pass-by-value by default and a String's value is the address of the String's object data.
So , when you are doing
stringNumber = stringNumber.replaceAll(" ", "");

You have changed the input value to have no spaces.
You can remove that line if you want.
private boolean isValidStringNumber(String stringNumber)
{
    if(stringNumber.isEmpty())
    {
        return false;
    }

    stringNumber = stringNumber.replaceAll(" ", "");

    char [] charNumber = stringNumber.toCharArray();
    for(int i =0 ; i<charNumber.length ;i++)
    {
        if(!Character.isDigit(charNumber[i]))
        {
            return false;
        }
    }
    return true;
}

Here is another method in case you want to allow floats
This method allegedly allows numbers in the form to pass
1,123,123,123,123,123.123
i have just made it , and i think it needs further testing to ensure it is working.
private boolean isValidStringTrueNumber(String stringNumber)
{
    if(stringNumber.isEmpty())
    {
        return false;
    }

    stringNumber = stringNumber.replaceAll(" ", "");
    int countOfDecimalPoint = 0;
    boolean decimalPointPassed = false;
    boolean commaFound = false;
    int countOfDigitsBeforeDecimalPoint = 0;
    int countOfDigitsAfterDecimalPoint =0 ;
    int commaCounter=0;
    int countOfDigitsBeforeFirstComma = 0;

    char [] charNumber = stringNumber.toCharArray();
    for(int i =0 ; i<charNumber.length ;i++)
    {
        if((commaCounter>3)||(commaCounter<0))
        {
            return false;
        }
        if(!Character.isDigit(charNumber[i]))//Char is not a digit.
        {
            if(charNumber[i]==',')
            {
                if(decimalPointPassed)
                {
                    return false;
                }
                commaFound = true;
                //check that next three chars are only digits.
                commaCounter +=3;
            }
            else if(charNumber[i]=='.')
            {
                decimalPointPassed = true;
                countOfDecimalPoint++;
            }
            else
            {
                return false;
            }
        }
        else //Char is a digit.
        {
            if ((commaCounter>=0)&&(commaFound))
            {
                if(!decimalPointPassed)
                {
                    commaCounter--;
                }
            }

            if(!commaFound)
            {
                countOfDigitsBeforeFirstComma++;
            }

            if(!decimalPointPassed)
            {
                countOfDigitsBeforeDecimalPoint++;
            }
            else
            {
                countOfDigitsAfterDecimalPoint++;
            }
        }
    }
    if((commaFound)&&(countOfDigitsBeforeFirstComma>3))
    {
        return false;
    }
    if(countOfDecimalPoint>1)
    {
        return false;
    }

    if((decimalPointPassed)&&((countOfDigitsBeforeDecimalPoint==0)||(countOfDigitsAfterDecimalPoint==0)))
    {
        return false;
    }
    return true;
}

Comment: Oh , Good question.
I guess this one only works normal type integers.
The method were initially created to filter input phone numbers , and count numbers.
Answer: If you want to do the check using a regex you should create a final static Pattern object, that way the regex only needs to be compiled once. Compiling the regex takes about as long as performing the match so by taking this precaution you'll cut the execution time of the method in half.
final static Pattern NUMBER_PATTERN = Pattern.compile("[+-]?\\d*\\.?\\d+");

static boolean isNumber(String input) {
    Matcher m = NUMBER_PATTERN.matcher(input);
    return m.matches();
}

I'm assuming a number is a string with nothing but decimal digits in it, possibly a + or - sign at the start and at most one decimal point (not at the end) and no other characters (including commas, spaces, numbers in other counting systems, Roman numerals, hieroglyphs).
This solution is succinct and pretty fast but you can shave a couple of milliseconds per million invocations by doing it like this
static boolean isNumber(String s) {
    final int len = s.length();
    if (len == 0) {
        return false;
    }
    int dotCount = 0;
    for (int i = 0; i < len; i++) {
        char c = s.charAt(i);
        if (c < '0' || c > '9') {
            if (i == len - 1) {//last character must be digit
                return false;
            } else if (c == '.') {
                if (++dotCount > 1) {
                    return false;
                }
            } else if (i != 0 || c != '+' && c != '-') {//+ or - allowed at start
                return false;
            }

        }
    }
    return true;
}

Answer: Try this:
public  boolean isNumber(String str)
{
    short count = 0;
    char chc[]  = {'0','1','2','3','4','5','6','7','8','9','.','-','+'};
    for (char c : str.toCharArray())
    {
        for (int i = 0;i < chc.length;i++)
        {
            if( c  == chc[i]){
                count++;
            }
         }
    }
    if (count != str.length() )
        return false;
    else
        return true;
}

Answer: This is the fastest way i know to check if String is Number or not:
public static boolean isNumber(String str){
  int i=0, len=str.length();
  boolean a=false,b=false,c=false, d=false;
  if(i<len && (str.charAt(i)=='+' || str.charAt(i)=='-')) i++;
  while( i<len && isDigit(str.charAt(i)) ){ i++; a=true; }
  if(i<len && (str.charAt(i)=='.')) i++;
  while( i<len && isDigit(str.charAt(i)) ){ i++; b=true; }
  if(i<len && (str.charAt(i)=='e' || str.charAt(i)=='E') && (a || b)){ i++; c=true; }
  if(i<len && (str.charAt(i)=='+' || str.charAt(i)=='-') && c) i++;
  while( i<len && isDigit(str.charAt(i)) ){ i++; d=true;}
  return i==len && (a||b) && (!c || (c && d));
}
static boolean isDigit(char c){
  return c>='0' && c<='9';
}

Comment: Instead of having these many checks we can simply have
if (ch >= '0' && ch <= '9') {}
Answer: Parallel checking for very long strings using IntStream
In Java 8, the following tests if all characters of the given string are within '0' to '9'. Mind that the empty string is accepted:
string.chars().unordered().parallel().allMatch( i -> '0' <= i && '9' >= i )

Answer: String text="hello 123";
if(Pattern.matches([0-9]+))==true
System.out.println("String"+text);

Answer: If you guys using the following method to check:
public static boolean isNumeric(String str) {
    NumberFormat formatter = NumberFormat.getInstance();
    ParsePosition pos = new ParsePosition(0);
    formatter.parse(str, pos);
    return str.length() == pos.getIndex();
}

Then what happend with the input of very long String, such as I call this method:
System.out.println(isNumeric("94328948243242352525243242524243425452342343948923"));

The result is "true", also it is a too-large-size number!
The same thing will happen if you using regex to check!
So I'd rather using the "parsing" method to check, like this:
public static boolean isNumeric(String str) {
    try {
        int number = Integer.parseInt(str);
        return true;
    } catch (Exception e) {
        return false;
    }
}

And the result is what I expected!
Comment: _"it is a too-large-size number"_ → There is no such thing as a "too-large-size number". Numbers are infinite. `7645` is a number and `92847294729492875982452012471041141990140811894142729051` is also a number. The first can be represented as an `Integer` and the second can be represented as a `BigDecimal`. And even if they could not be represented as an object in Java, they are still numbers -- which is what the question asks.
Comment: Also, don't misuse exceptions. Java isn't python. At least use more specific `NumberFormatException`
Answer: private static Pattern p = Pattern.compile("^[0-9]*$");

public static boolean isNumeric(String strNum) {
    if (strNum == null) {
        return false;
    }
    return p.matcher(strNum).find();
}

Comment: While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply.
Answer: import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
        boolean flag = true;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the String:");
        String str = sc.nextLine();

        for (int i = 0; i < str.length(); i++) {
            if(str.charAt(i) > 48 && str.charAt(i) < 58) {
                flag = false;
                break;
            }
        }

        if(flag == true) {
            System.out.println("String is a valid String.");
        } else {
            System.out.println("String contains number.");
        }
    }
}


openssl can be found by yum but can't be found by pkg-config

Question: I found openssl is already installed on my server
# yum list installed | grep openssl
openssl.x86_64                          1:1.0.2k-26.el7_9        @updates
openssl-libs.x86_64                     1:1.0.2k-26.el7_9        @updates

However, it couldn't be found by pkg-config
# pkg-config --libs --cflags openssl
Package openssl was not found in the pkg-config search path.
Perhaps you should add the directory containing `openssl.pc'
to the PKG_CONFIG_PATH environment variable
No package 'openssl' found

I want to know what's wrong and how to fix it.
Answer: The command pkg-config is used for develop libraries and have (directly) nothing to do with system packages, installed in the OS.
Comment: I tried, and it works now, thank you
Comment: do you mean I have to install something like `openssl-devel`?
Comment: AFAIK - yes, this util search for dev libraries and it is mostly in use when you compile something


Asking for someone to review Bishop movement logic

Question: I'm making a chess program and currently have the movement done for the pawn and knight, however I'm having a little trouble with the bishop. I'm creating my chess game with the MVC approach and have it creating a 2D array of BoardSquares which store information such as location, a piece (if there is one), and if it's empty. For the moment I have the board take in input from a text file line-by-line. The current line I'm working on for the bishop movement is from c8 to a6, so moving Down and to the Left.
My movement is simple, where it takes the input from the file, translates it to 2D array coordinates and passes it into the model's move method (along with the model) which calls a piece's move method.
// In the File I/O Class
public void passinMove(BoardModel bm) {
    generateOriginRC(input, START_LOC1, END_LOC1);
    generateDestRC(input, START_LOC2, END_LOC2);
    System.out.println("Origin C/R: "+oCol+"/"+oRow);
    System.out.println("Dest C/R: "+dCol+"/"+dRow);
    bm.movePiece(bm.getBoard(), oRow, oCol, dRow, dCol);
}

// In the BoardModel Class
public void movePiece(BoardSquare[][] board, int oRow, int oCol, int dRow, int dCol){

    board[oRow][oCol].getPiece().move(board, board[dRow][dCol]);

As of now to move I have my pieces each generate their own array of valid moves; which is a list of BoardSquares by moving it VIA brute force one square at a time until it hits a piece or the end of the board. Then I have it compare it's desired destination square to that list.
@Override
void move(BoardSquare[][] board, BoardSquare target) {
    if (!getPossibleMove(board).contains(target)) {
        System.out
                .println("Sorry. Not a valid move, please enter a new move");

    } else {
        target.setSquare(board[col][row]);
    }
}

For the bishop I have it grab it's position and manipulate it accordingly to move it. (To move up I subtract to go down the array, etc.).
However it seems my logic is flawed somewhere; since when it starts checking down and to the right it moves from 0/2 to 1/2. Then continues until it hits the right side wall and goes straight down into the corner.
@Override
Collection<BoardSquare> getPossibleMove(BoardSquare[][] board) {
    BoardSquare[][] copy = board;
    ArrayList<BoardSquare> validMoves = new ArrayList<BoardSquare>();

    // Checks spaces to the Up-Right of the Bishop by moving the Bishop
    // until it hits the end of the board or a piece
    for (int goUp = getCol(); goUp > -1; goUp--) {
        for (int goRight = getRow(); goRight < 8; goRight++) {
            System.out.println("Doing Up-Right C/R: "+getCol()+" / "+getRow());
            System.out.println("Moving to C/R: "+goUp+" / "+goRight);
            tempCol = getCol();
            tempRow = getRow();
            if (moveValidator(copy[goUp][goRight])) {
                validMoves.add(copy[goUp][goRight]);
                copy[goUp][goRight].setSquare(copy[tempCol][tempRow]);
            } else {
                break;
            }
        }
    }

    // Checks spaces to the Up-Left of the Bishop by moving the Bishop
    // until it hits the end of the board or a piece
    for (int goUp = getCol(); goUp > -1; goUp--) {
        for (int goLeft = getRow(); goLeft > -1; goLeft--) {
            System.out.println("Doing Up-Left C/R: "+getCol()+" / "+getRow());
            System.out.println("Moving to C/R: "+goUp+" / "+goLeft);
            tempCol = getCol();
            tempRow = getRow();
            if (moveValidator(copy[goUp][goLeft])) {
                validMoves.add(copy[goUp][goLeft]);
                copy[goUp][goLeft].setSquare(copy[tempCol][tempRow]);
            } else {
                break;
            }
        }
    }

    // Checks spaces to the Down-Right of the Bishop by moving the Bishop
    // until it hits the end of the board or a piece
    for (int goDown = getCol(); goDown < 8; goDown++) {
        for (int goRight = getRow(); goRight < 8; goRight++) {
            System.out.println("Doing Down-Right C/R: "+getCol()+" / "+getRow());
            System.out.println("Moving to C/R: "+goDown+" / "+goRight);
            tempCol = getCol();
            tempRow = getRow();
            if (moveValidator(copy[goDown][goRight])) {
                validMoves.add(copy[goDown][goRight]);
                copy[goDown][goRight].setSquare(copy[tempCol][tempRow]);
            } else {
                break;
            }
        }
    }

    // Checks spaces to the Down-Left of the Bishop by moving the Bishop
    // until it hits the end of the board or a piece
    for (int goDown = getCol(); goDown < 8; goDown++) {
        for (int goLeft = getRow(); goLeft > -1; goLeft--) {
            System.out.println("Doing Down-Left C/R: "+getCol()+" / "+getRow());
            System.out.println("Moving to C/R: "+goDown+" / "+goLeft);
            tempCol = getCol();
            tempRow = getRow();
            if (moveValidator(copy[goDown][goLeft])) {
                validMoves.add(copy[goDown][goLeft]);
                copy[goDown][goLeft].setSquare(copy[tempCol][tempRow]);
            } else {
                break;
            }
        }
    }
    return validMoves;
}

Some notes:
The tempCol and tempRow variable are just used to acquire the location the piece is on to move it to the "new" destination.
I'm still trying to figure it out, however I would like someone to review my code incase there's something I'm not noticing or forgetting. Any tips or suggestions are much appreciated. Thanks.
Comment: `goLeft = getRow()` wouldn't you use columns for left/right mouvements?
Comment: @MichaelLaffargueEasysport.fr Normally yes it should be. However when I generated mine and began adding pieces they became mixed up somewhere and I ended up re-factoring to what you currently see. I could go change it. However for now it's all uniform and works since my pieces use to be set left side to right side oppose to what it is now, top and bottom.
Answer: I think the problem you describe would happen if the moveValidator function returns always false until your piece reach the wall.
You'll have
For1 --> goDown=0
For2 --> goRight=2 --> moveValidator is false so break;
For1 --> goDown=1
For2 --> goRight=2 --> moveValidator is false so break;
...
And when goDown = 8
For2 --> goRight=2 --> moveValidator is true
For2 --> goRight=3 --> moveValidator is true
...

So you may want to validate my guess debugging and trying to verify the moveValidator function (you didn't give it in your code)
Comment: I went back through my whole project and fixed the mixed row and col's and found several code breaking bugs. Thanks again.
Answer: I think the logic may be more simple with a single counter.  Also, since you are breaking out anyway, you can further simplify the logic by counting to 8.      When I read copy[goUp][goRight] I wondered if you meant copy[goRight][goUp] since usually I set up my game board variables like with x,y and row,col.  I am new myself and I apologize in advance if I misunderstood any or all of the question.  Good luck with your chess game!
    // Checks spaces to the Up-Right of the Bishop by moving the Bishop
    // until it hits the end of the board or a piece
    for (int go = 1; go < 8; go++){
        int testRow = getRow();
        int testCol = getCol();
        testRow-=go; //looking upwards
        testCol+=go; //looking rightwards


why $\{f<1\} =(-\infty,0]?$ why not $\{f<1\} =(0,\infty)$?

Question: MIT  source :  Question $2$c link and Solution $2$c link pdf
Question :let $\{f_n\}$ be  sequence  of real value function ,nonnegative  function on $\mathbb{R}$. Prove or disprove  each of the  following statement

If each  $f_n$ is upper semicontnious ,then  $\sum_{n=1}^{\infty} f_n$ is uppers semicontnious

I have some confusion in this image
My  confusion :  Im not getting  why $\{f<1\} =(-\infty,0]?$ why not $\{f<1\} =(0,\infty)$?
My thinking : It is given  that  $f(x)=\sum_{n} f_n(x)$  where  $f_n(x)=\begin{cases}  1  \ \text{if x}  \in [\frac{1}{n+1} ,\frac{1}{n}] \\ 0  \ \text{if  x} \notin [\frac{1}{n+1} ,\frac{1}{n}] \end{cases}$
This implies   $f(x)  \in \{0,1,2\} $ for all  $x \in \mathbb{R}$
Suppose    $x =\frac{1}{\pi} \neq 1/k$  for  any $k \in \mathbb{N}$
Then $f_1(x)=1$ and $f_n(x)=0$ for all $n\gt 1$.
This implies  $\{f<1\} =(0,1)$
Comment: What's the underlying domain? Because $f<1$ would just be the complement of the union of the intervals $[1/(n+1),1/n]$ which assuming $n$ starts at $1$ will be the complement of $(0,1]$, whatever that is in the domain.
Comment: @jasmine: I guess the goal of the exercise what to show that infinite the supremum of upper semicontinuous functions is not necessarily upper semicontinuous. Considering the $f_n$'s in your posting as defines over all the real line, $\max_{1\leq k\leq n}f_k(x)=\mathbb{1}_{[\tfrac{1}{n+1},1]}(x)$ which is upper semicontinuous (being the indicator function if a closed interval). However $f(x)=\sup_nf_n(x)=\mathbb{1}_{(0,1]}$ is not upper semicontinuous as $\{f<1\}=(-\infty,0]\cup(1,\infty)$ which is not open in $\mathbb{R}$.
Comment: @jasmine: I have no issue with references. After all this is a textbook problem and not a deep theorem in a paper by Andrei Kolmogorov.
Comment: @Ian $\{f_n\}$   is  sequence  of real nonnegative function on $\mathbb{R}$
Comment: Yes, you are right!@Ian  I think something is wrong in a given solution. It contained a typo.
Comment: you  are right @OliverDiaz I think there's a typo  in a given solution
Comment: @jasmine How do you find that $f(x) = 0 $ for all $x \in \{ \frac{1}{n} \}$? Is not $f(1) = 1$, $f(1/2) = 2$ and so on?
Comment: @user2005142 see my  [post](https://math.stackexchange.com/questions/4222830/find-the-sum-1n-f-k-and-find-the-sum-1-infty-f-k?rq=1)
Comment: @jasmine but for instance, $\frac{1}{2} \in [\frac{1}{n+1}, \frac{1}{n}]$ only for $n = 1, 2$. So $\sum_{n = 1}^{N} f_n(\frac{1}{2}) = 2$ for all $N \geq 2$, since  $f_n(\frac{1}{2}) = \begin{cases}1,& n \in \{1, 2\} \\ 0 & \text{else} \\\end{cases}$
Comment: yes you  are right @user2005142    same logic I've often said in my question
Comment: @user2005142 I have assume  $x \neq \frac{1}{k}$
Comment: @user2005142 i edited
Comment: @OliverDiaz I have added a reference
Answer: If $x>0$ (and $x \le 1$) then for some $n$, $x$ will be in $[\frac{1}{n+1}, \frac1n]$ for some $n$ and then $f_n(x) =1$ there and so $f(x) \ge 1$ for those $x$. $f_n(0)=0$ for all $n$ so $f(0) =0 < 1$ and so on the domain $(-\infty, 1]$ we have $\{x\mid f(x) < 1\} = (-\infty, 0]$ as claimed. But in the example I don't see an explicit domain for the $f_n$, but if $x>1$ would have been allowed all $f_n(x)=0$ for $x$ there as well and we'd add $(1, +\infty)$ to the inverse image.


Move cursor to placeholder element in a contentEditable DIV

Question: I have a contentEditable DIV and, when the user presses a key, the underlying code is processed and replaced by updated code.  Alas, this causes the cursor position to be lost.
However, in order to preserve the cursor position, I am successfully inserting a  into the DIV at the correct position before processing begins.  This preserves the cursor's intended position, but now I can't seem to set the range to select it.
Here's what I currently have:
function focusOnPlaceholder() {

    var placeholder = document.getElementById('placeholder');

    if( !placeholder ) return;

    var sel, range;

    if (window.getSelection && document.createRange) {
        range = document.createRange();
        range.selectNodeContents(placeholder);
        range.collapse(true);
        sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(placeholder);
        range.select();
    }

}

Any help would be appreciated, and a cross-browser solution would be incredible :)
Answer: A cross-browser solution would be to use my Rangy library and specifically the selection save/restore module, which uses a similar placeholder technique and is well tested. However, this can probably be fixed without using a library by putting some content (for example, a non-breaking space (\u00A0 or   in HTML) inside your placeholder element. You may want to remove the placeholder in focusOnPlaceholder() after selecting the range.
Comment: The non-breaking space addition did the trick.  Going to look into Rangy now.  Thanks!


Pass a selected value through ajax onchange event

Question: I have a select form:
<form id="form" name="nameForm">

<select id="selectId" onchange="loadAjax('url.php');return false;">
<option>One</option
<option>Two</option>
</select>

</form>

I want that when the user changes the selected option, it loads the ajax function with the value in the url (trough GET).
So I tried several things and this was my last try:
onchange="
var e = document.getElementById('form');
var strSel = e.form.selectId.value;
loadAjax('url.php?v='+strSel);
return false;
">

Not really correct. Does someone know how to do this correctly ?
Comment: take a look at `jquery` your life will be much easier.
Comment: thanks but I'm not using Jquery
Answer: You are missing value attribute in options
I tried it and it works after adding value, like,
<select id="selectId" onchange="alert('url.php?v='+this.value);return false;">
   <option value="one">One</option>
   <option value="two">Two</option>
</select>

You should try this,
<select id="selectId" onchange="loadAjax('url.php?v='+this.value);return false;">
   <option value="one">One</option>
   <option value="two">Two</option>
</select>

Working Fiddle
Answer: According to your code sample this will work
onchange="
var e = document.getElementById('selectId');
var strSel = e.options[e.selectedIndex].value;
loadAjax('url.php?v='+strSel);
return false;
">


Load view with ajax and contextual/exposed filters

Question: I am trying to access content, that is provided via and can be filtered via a view. I want to load this content dynamically with Ajax. My problem now is, that I can access the view without problems using the following ajax-call:
$.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'post',
    data: {
        view_name: 'search',
        view_display_id: 'block_1',
        filterName: value
    },
        success: function(data,jqxhr) {
            $("#ajax-test").html(data)
            console.log(data[1])
        },
        error: function(error) {
            console.log(error)
        }
    });

This works fine, but it ignores the value of filterName (Which corresponds to the according input in the view form). Unfortunately using Better Exposed Filters and Links is not an option since I need to access many filters at once.
Also building an URL like so:
$.get(Drupal.settings.basePath + 'views/ajax/search/block_1/', "filterName[0]=filterValue" ,resultFunction);

did not work for me. Thanks ahead for any pointers!
Answer: If you call a display_id of block_1 the block does not have the exposed_form created to be evaluated by default in Views (views blocks cant have exposed forms out of the box) -- so your AJAX views calls knows nothing about any exposed form.
You need to either call a Views Page url where the exposed form is set on the page. Or, you need to use Views hooks to create/attach the exposed form to the View when your Ajax call is made.


Show that $T \mathbb{R}^n$ is diffeomorphic to $\mathbb{R}^{2n}$

Question: $T \mathbb{R}^n$ is the tangent bundle to $\mathbb{R}^n$. How do I show that is is diffeomorphic to $\mathbb{R}^{2n}$? I know that there is an isomorphism (and therefore a diffeomorphism) between $\mathbb{R}^n$ and $T_p \mathbb{R}^n$, can I conclude from here, using the fact that $TM$ is the disjoint union of all $T_pM$s?
Alternatively: I know that, if $M$ is an $n$-dimensional differentiable manifold, then $TM$ is a $2n$-dimensional differentiable manifold. I have seen the construction given in Warner, Foundations of Differentiable Manifolds and Lie Groups, page 19, complete with proof. It really shouldn't be hard to explicitely construct the diffeomorphism, but I'm struggling for ideas.
Comment: There *always* is an isomorphism between $T_pM$ and *some* $\Bbb R^n$ (the same $n$ for all $p$-s), but not all tangent bundles are diffeomorphic to $M\times\Bbb R^n$.
Answer: If $M$ is an $n$-dimensional manifold defined by the atlas $(U_i,f_i:U_i\rightarrow\mathbb{R}^n)_{i\in I}$ then $TM$ is the manifold defined by $(U_i\times\mathbb{R}^n,g_i)$ where $g_i(x,y)=f_i\circ f_j^{-1}(x), d(f_i\circ f_j^{-1})_{f_j(x)}(y))$. $\mathbb{R}^n$ is an $n$-dimensional manifold defined by the chart $(\mathbb{R}^n, Id_{\mathbb{R}^n})$, therefore $T\mathbb{R}^n$ is defined by the chart $(\mathbb{R}^n\times\mathbb{R}^n, Id_{\mathbb{R}^{2n}})$.
Comment: Thank you for your answer. Could you please clarify what you exactly mean by "$TM$ is the manifold defined by $(U_i \times \mathbb{R}^n, g_i)$"? My definition is a little different, $TM$ being the manifold with charts $(\pi^{-1}(U), \tilde{\phi})$, where $\pi$ is the projection $TM \mapsto M$, $(U, \phi)$ is a chart on $M$ and, if $(x, v) \in TM$, $\tilde{\phi} (x, v) = (x_1(\pi(v)), \dots, x_n(\pi(v)), (dx_1)_|{p} (v), \dots, (dx_n)_{|p} (v))$
Answer: Going by Lee's definition, the tangent bundle is, by definition, disjoint union of all $T_pM  $s.
Let $(U,\phi)$ be in atlas of M. Define map $f: \pi^{-1}(U) \rightarrow R^{2n} $ as $$f\Bigg(v^i|\frac{\partial}{\partial x^i}\Bigg|_p \Bigg)=(p,v) $$
Now write down the inverse of $f$ and observe that it is a bijection. Now write down the map $ id\circ f\circ\phi^{-1}$. This should in fact turn out to be identity map.


Magento Child Theme Creation Issue

Question: I've a fresh installation of Magento ver 184.108.40.206 on localhost. I'm following this tutorial closely to create a child theme of Magento responsive theme.
I've followed all steps clearly. I've created Magento directory structure, using this approach
[Magento Directory]/app/design/frontend/{package_name}/{theme_name}/etc

and created theme.xml file there. As can be seen

Exact location of the theme.xml file is:
[Magento Directory]/app/design/frontend/tutsplus/vstyle/etc

as my package name is 'tutsplus' and theme name is 'vstyle'. I've also correctly enabled this theme from admin panel. As can be seen in below screenshot:

The code of theme.xml file is:
<?xml version="1.0"?>
<theme>
    <parent>rwd/default</parent>
</theme>

Can someone point out what am I missing?
Comment: can you tell me what is the issue
Comment: Page appears broken, with no style.
Comment: On the tutorial I'm following it is written:

 If styles.css is loading from a path similar to the following, theme.xml is most likely not loading.

`http://www.example.com/magento/skin/frontend/base/default/css/styles.css`

This is precisely the problem I'm facing
Answer: Same problem. But here I had put comments  in theme.xml. I had to just strip them.
Your file may be unreadable or corrupted.
Comment: This was my problem as well, the [tutorial I followed](http://alanstorm.com/magento_parent_child_themes/) had the first line as a comment, removing it fixed it the theme.
Answer: Exactly the same issue here but here's how I solved it.
In addition to adding the package name and template name at System > Configuration > Design, you need to go to System > Design and add your new theme there too.
system > design
add package
Comment: That worked. I had to go to System > Design then Add design Changes and choose the new child theme and only the start date then save.
Answer: If you haven't seen it already, check out http://www.magentocommerce.com/knowledge-base/entry/ee114-ce19-rwd-dev-guide.
The guide has additional information you'll need to get started.
Comment: I've not only read it, but also followed it step by step, as you can see from the steps I've explained in the question. I don't know why it isn't working.
Comment: Another interesting thing to note is that even when I created new local.xml file in layout directory that also doesn't seem to be working. In fact I think no xml file is working. While the phtml files under template directory are just working fine.
Comment: @GnMcVey 's Suggestion worked. Check my comment there. BTW disable all cache in your local or flush cache after saving the design change
Answer: Additionally, if the theme.xml file was formatted like this:
<theme>
    <parent>
        packagename/actualtheme
    </parent>
</theme>

It will not work. It needs to be formatted:
<theme>
    <parent>packagename/actualtheme</parent>
</theme>

Not sure why; maybe someone with more advanced knowledge could comment.

Magento Child Theme Creation Issue


How to print date in image in Event List in Drupal

Question: How can I print a date like JAN 28 in the provided Event list, using Drupal Views?
The example image taken from the Drupal website is attached below
Answer: Navigate to /admin/config/regional/date-time/formats/add and add a new date format. For the replacement pattern use: M t then click save.
then navigate to: /admin/config/regional/date-time and create a human readable name for your custom date format, then select the date format you created inside the select box. click save.
Create your view add your date field and then in the field settings give it your custom date format for the format section.
Style with CSS. You're done.
You may need to create two different date formats to achieve the styling you want. One for M and one for t. Then add your date field to the view twice and add the date formats on the fields, then you can easily target the two different date elements and use css to position them the way they are in the image you provided.
Answer:
Create a new content type for events (e.g. 'events') and add starting and ending date fields. You can create now create your desired event content.
Add a new calendar view from the existing template in the calendar module(admin/structure/views add-template). From the list, you should select "A calendar view of the 'field_yourfieldname' field in the 'node' base table."(Display type of the view: Month)
In the edit mode of your calendar view, under filter criteria, select the event content type that you created above. Also add a contextual filter - 'Content: Nid'. Save the view.
Create a new view for your event listing. This view should have a page display. Under filter criteria, select the event content type that you created above. Add 'Content: Nid' as a new field and tick the option 'Exclude from display' in the configuration page. Add another field, 'Global: PHP', for grabbing the current date and passing it as argument to the calendar view. you should write 'print date("Y-m")' in the Output Code field and tick the option 'Exclude from display' in the configuration page.
Embed the calendar view in your event listing by adding a new field: 'Global: View'. (See the attached image for the configuration of this field.) Here you should specify the name of your calendar view in the View setting section and also specify the views display type. Then, you should add '[%php]/[%nid]' as a contextual filter for the calendar view. Save the view. Your customized event listing is now ready!


Trying to make two sql queries, but always landing with error

Question: $query=mysqli_query($conn,"INSERT INTO bus_info(bus_id,route_num,school_name) values('$BusNum','$RouteNum','$SchoolName'); INSERT INTO bus_loc(bus_id,lat,lon) values ((SELECT bus_id from bus_info where bus_info.bus_id='$BusNum'),'$latitude','$longitude')");

PHP
$BusNum = $_POST["BusNum"];
$SchoolName = $_POST["SchoolName"];
$RouteNum = $_POST["RouteNum"];
$latitude = $_POST["lat"];
$longitude = $_POST["lng"];

Database is connected i.e. returned true.enter code here
Fails with :
Error sending data:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near INSERT INTO bus_loc(bus_id,lat,lon) values ((SELECT bus_id from bus_info where b at line 1
Answer: From: http://php.net/manual/de/mysqli.query.php#87203

mysqli::query() can only execute one SQL statement.
Use mysqli::multi_query() when you want to run multiple SQL statements within one query.

How to use mysqli_multi_query: http://php.net/manual/de/mysqli.multi-query.php
Answer: This query is missing a where clause condition
SELECT bus_id from bus_info where b

change it to like:
SELECT bus_id from bus_info where b = 'something'

but you should not execute two queries like this but execute this first save the result in a variable and then execute the next one like
 $query =   SELECT bus_id from bus_info where b = 'something'
 $saved = $mysqli_query($yourconnection, $query);
 $row = mysqli_fetch_assoc();
 $fetched = row['columnnamehere'];

and then
INSERT INTO bus_loc(bus_id,lat,lon) values ('$fetched');

Comment: I added the 'WHERE' clause
    where bus_info.bus_id='$BusNum'.
Trying your variable method.
Comment: The "where b" reported in the error is just the MySQL server truncating the string at that point for the purposes of reporting an error; if you check the PHP core in the question, you can see that the query has a proper where clause.
Answer: For better understanding split query into two parts and use them like :-
$query =   mysqli_query($conn,"INSERT INTO bus_info (bus_id,route_num,school_name) values('$BusNum','$RouteNum','$SchoolName')");

$query2 =  mysqli_query($conn,"INSERT INTO bus_loc (bus_id,lat,lon) values ((Select bus_id from `bus_info` where bus_id = '$BusNum'),'$latitude','$longitude')");

Comment: Thats a better and cleaner way! Thanks mate!


Relating the order of a multiplicative character to the image of the character

Question: Let $F_{p} = \mathbb{Z} / p \mathbb{Z}$ and $\chi$ be a multiplicative character on $F_{p}$ of order $k$, i.e. $\underbrace{\chi \chi \cdots \chi}_{k\text{-times}} = \chi_{0}$ where $\chi_{0}$ is the trivial character. After computing several examples by hand, it seems that $Im(\chi)$ is isomorphic to the $k$th roots of unity, which we will denote $\Gamma_{k}$, but I am having a hard time proving this.
It is easy to see that $Im(\chi) \subseteq \Gamma_{k}$ because for any $a \in F_{p}$, we have $$\underbrace{\chi(a) \chi(a) \cdots \chi(a)}_{k\text{-times}} = \chi^k(a) = \chi_{0}(a) = 1. $$
However given an arbitrary $z \in \Gamma_{n}$, how can one show that $z \in Im(\chi)$?
Answer: $\mathbb{F}_p^\times$ is cyclic and a multiplicative character $\chi$ is determined by where it sends a chosen generator: if the generator is sent to an element of order $k$, then $\chi$ and its image will have order $k$. Indeed, the generator can be sent to any element of order dividing $|\mathbb{F}_p^\times|=p-1$, so this not only establishes what order $\chi$ can have in the dual group, it sets up a bijection between the multiplicative characters $\chi$ and $(p-1)$st roots of unity. (The bijection depends on choice of generator though.)


UIView and XIB connections.Displaying it?

Question: How can i display an XIB/NIB file on a UIView?I've searched but i didn't found this.I want to display the xib interface on a main view,i have five xib files and i need to each one be displayed on a UIView!Some people talked about this code code but where i implement this:
NSArray *screens=[[NSBundle mainBundle] loadNibNamed:@"JaneiroClass" owner:self options:nil];
        [self addSubview:[screens objectAtIndex:0]];

Answer: This will load a view from a XIB.  UINib also caches so you can stamp them out quickly.
UINib *nib = [UINib nibWithNibName:@"TestView" bundle:nil];
UIView *myView = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0]];

instantiateWithOwner returns an array of the top level objects in the XIB.  In the case above, there was only one view (with other objects from the library on it) so we retrieved objectAtIndex:0.
Once you have the view, you can add it to other views.  For example, you can call addSubView on another view passing this:
[someView addSubView:myView];

Comment: Can you be more specific,i'm very confused!
Answer: I posted an article about loading custom views from a nib in my blog http://effectivemobility.blogspot.com/2011/05/using-custom-cells-in-your-uitableview.html
The key part is this method
+ (id)customViewForClass:(Class)customClass {
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(customClass) owner:nil options:nil];
    for ( id currentObject in topLevelObjects ) {
        if ( [currentObject isKindOfClass:customClass] ) {
            return currentObject;
        }
    }

    return nil;
}

Comment: Please,you gave some examples,but how exactly i can display an xib in a UIView?