In: Computer Science
JAVA
In this PoD you will use an ArrayList to store different pet names (there are no repeats in this list). This PoD can be done in your demo program (where your main method is) – you don’t have to create a separate class for today.
Details
Create an arraylist of Strings, then using a Scanner object you will first read in a number that will tell you how many pet names (one word) you will add to the arraylist.
Once you have added all the names, print the list.
Then read in one more pet name. If this is pet name already exists, do nothing, but if the pet name isn’t in the list, add it to the front of the list (e.g., the first position).
Print the list again.
Next read in two more pet names. If the first pet name is in the list, replace it with the second pet name. If the first pet name isn’t in the list, add the second pet name to the end of the list.
Print the list again.
Input
Example Input:
5 Whiskers Benji Lassie Smokey Bob Triffy Bob Max
Output
Example Output:
[Muffin, Benji, Snowball, Fluffy]
[Muffin, Benji, Snowball, Fluffy]
[Muffin, Benji, Snowball, Whiskers, Fluffy]
import java.util.ArrayList;
import java.util.Scanner;
public class PetsTest {
public static void main(String[] args) {
ArrayList<String>list= new
ArrayList<String>();
int num;
String str;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of pets");
num=sc.nextInt();
sc.nextLine();
// reading names
System.out.println("Enter "+num+" pet names");
for(int i=0;i<num;i++){
list.add(sc.next());
}
//reading another pet name
System.out.println("Enter petname");
str=sc.next();
// checking if it is in list , if not adding to
front
if(!list.contains(str)){
list.add(0, str);
}
// prints list
System.out.println(list);
//reading more 2 pet names
System.out.println("Enter 2 pet names");
str=sc.next();
//
String str1=sc.next();
// checking if it is in list , if yes than replacing
it with second one,
if(list.contains(str)){
list.set(list.indexOf(str),
str1);
}
// else adding it in the end
else{
list.add(str1);
}
System.out.println(list);
}
}