Home > Software design >  The terminal says it cannot convert from Int to String in Java when I want the integer only?
The terminal says it cannot convert from Int to String in Java when I want the integer only?

Time:08-15

So i'm trying to add an extra number to an array (I want to 1 to create an array of 1, 2, 3, 4), using the method down below, but I've run into an error. First off my static method says it cannot convert itself to a String, but I only want an Integer. I also don't know what i'm doing wrong on line 12. I tried other tactics that didn't seem to work, and looked online for possible help. I'm new to Java so I don't really fully understand it. I need to create two more methods but first I should get this right. The Terminal output is down below. (I'm using Visual Studio on Mac if you need this information). Thanks for the help.

public class Arrays {
  
  public static int[] add(int[] arr, int val)
  {
      int[] newArray = Arrays.copyOf(arr, arr.length   1);
      newArray[arr.length] = val;
      return newArray;
  }
  
  public static void main(String[] args ){
    int array[] = {1, 2, 3};
    String new_array = add(array, 0);
    System.out.print(array);
    add(3, 4);
  }

}
/usr/bin/env /Library/Java/JavaVirtualMachines/jdk-18.0.1.1.jdk/Contents/Home/
bin/java -agentlib:jdwp=transport=dt_socket,server=n,suspend=y,address=localhost:64984 --enable-preview -XX: Sho
wCodeDetailsInExceptionMessages -cp /private/var/folders/hx/s_5smg5s6510w9_szj6xk8200000gn/T/vscodesws_37f78/jdt
_ws/jdt.ls-java-project/bin Arrays 
Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
        Type mismatch: cannot convert from int[] to String
        The method add(int[], int) in the type Arrays is not applicable for the arguments (int, int)

        at Arrays.main(Arrays.java:12)

CodePudding user response:

Naming your class Arrays did you no favors, because that shadows java.util.Arrays which contains the copyOf routine you are trying to use. Further, an int[] is an Object in Java. It is not a pointer to an int (which seems to be what you expected). To prevent name clashes, I have explicitly called the methods in java.util.Arrays below. I have also made it a complete example.

public static int[] add(int[] arr, int val) {
    int[] newArray = java.util.Arrays.copyOf(arr, arr.length   1);
    newArray[arr.length] = val;
    return newArray;
}

public static void main(String[] args) {
    int[] array = { 1, 2, 3 };
    System.out.println(java.util.Arrays.toString(array));
    int[] new_array = add(array, 99);
    System.out.println(java.util.Arrays.toString(new_array));
}

Which outputs

[1, 2, 3]
[1, 2, 3, 99]
  • Related