Error of int cannot be dereferenced?

后端 未结 3 1436
面向向阳花
面向向阳花 2021-01-06 19:51

I am getting an error with this constructor, and i have no idea how to fix? I am a beginner at java. This is from an example exercise that i was trying to learn:

<         


        
相关标签:
3条回答
  • 2021-01-06 20:10

    int is not an object in java (it's a primitive), so you cannot invoke methods on it.

    One simple way to solve it is using Integer.toString(intArray[i])

    0 讨论(0)
  • 2021-01-06 20:22

    I would write it more like this

    public String[] convertToStrings(int... ints) {
        String[] ret = new String[ints.length];
        for(int i = 0; i < intArray.length; ++i)
            ret[i] = "" + ints[i];
        return ret;
    }
    

    Or in Java 8 you might write

    public List<String> convertToStrings(int... ints) {
        return IntStream.of(ints).mapToObj(Integer::toString).collect(toList());
    }
    

    This uses;

    • Java coding conventions,
    • limited scope for the variable i,
    • we do something with the String[],
    • give the method a meaningful name,
    • try to use consist formatting.

    If we were worried about efficiency it is likely we could do away with the method entirely.

    String.valueOf(int) is not faster than Integer.toString(int). From the code in String you can see that the String implementation just calls Integer.toString

    /**
     * Returns the string representation of the {@code int} argument.
     * <p>
     * The representation is exactly the one returned by the
     * {@code Integer.toString} method of one argument.
     *
     * @param   i   an {@code int}.
     * @return  a string representation of the {@code int} argument.
     * @see     java.lang.Integer#toString(int, int)
     */
    public static String valueOf(int i) {
        return Integer.toString(i);
    }
    
    0 讨论(0)
  • 2021-01-06 20:27

    You code tries to call the toString() method of an int value. In Java, int is a primitive type and has no methods. Change the line:

    Array[i] = intArray[i].toString();
    

    to

    Array[i] = String.valueOf(intArray[i]);
    

    and the code should run. By the way, you should use lowerCamelCase for variables and fields.

    Edit: For what it's worth, String.valueOf(int) is a bit faster than Integer.toString(int) on my system (Java 1.7).

    0 讨论(0)
提交回复
热议问题