Sumit Yadav Posted April 1, 2023 Report Share Posted April 1, 2023 Hello all, I am new here and i am learning java from the scratch. I was writing a java code about replace the second element of a ArrayList with the specified element. Here is my Code: import java.util.ArrayList; public class program { public static void main(String[] args){ ArrayList<String> color = new ArrayList<String>(); color.add("Red"); color.add("Green"); System.out.println("Original array list: " + color); String color = "White"; color.set(1,new_color); int num=color.size(); System.out.println("Replace second element with 'color'."); for(int i=0;i<num;i++) System.out.println(color.get(i)); } } While run the code it shows an error. i am not understand how to resolve this, can any one please help me on this, I was taking reference from here Quote Link to comment Share on other sites More sharing options...
jontomonta Posted April 27, 2023 Report Share Posted April 27, 2023 Yes, there are a few errors in the code. Here are the issues I found: The variable new_color is not defined. It seems like you meant to use the variable color instead of new_color when calling the set method on the color ArrayList. The variable color is already defined as an ArrayList of Strings. You cannot redefine it as a String on the line String color = "White";. The set method of an ArrayList takes two arguments: the index of the element to replace and the new element. In this case, you should replace color.set(1,new_color); with color.set(1, color);. Here is the corrected version of the code: import java.util.ArrayList; public class program { public static void main(String[] args){ ArrayList<String> color = new ArrayList<String>(); color.add("Red"); color.add("Green"); System.out.println("Original array list: " + color); String newColor = "White"; color.set(1,newColor); int num=color.size(); System.out.println("Replace second element with 'White'."); for(int i=0;i<num;i++) System.out.println(color.get(i)); } } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.