In: Computer Science
Using an ArrayList, create a program which does the following: If the user enters quit, the program ends. If the user enters add followed by a string, program adds the string only to your ArrayList. If the user enters print, the program prints out the ArrayList contents. If the user enters size, the program prints out size of ArrayList, If the user enters remove followed by string, it removes all strings.
interface example:
**** Welcome to my List Program ****
Options: quit, add and a string, size, and print
Enter option: add bill jackson
bill jackson added to list
Enter option: print
[bill jackson]
Enter option: size
Size of List is: 1
Enter option: add jim jones
jim jones added to list
Enter option: print
[bill jackson, jim jones]
Enter option: search jim jones
jim jones found in index 1
Enter option: search billy billkins
billy billkins not found
Enter option: remove jim jones
jim jones removed
Enter option: print
[bill jackson]
Enter option: remove nick
nick not found - not removed
Enter option: remove all nick
all nick removed
Enter option: quit
Thank You!
please give thumbs up, thanks
code:
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author VISHAL
*/
public class WordProgram {
ArrayList A;
public WordProgram()
{
A=new ArrayList();
}
public void add(String str)
{
A.add(str);
}
public int search(String str)
{
for(int i=0; i<A.size();i++)
{
if(A.get(i)==str)
{
return i;
}
}
return -1;
}
public int size()
{
return A.size();
}
public void print()
{
for(int i=0; i<A.size(); i++)
{
System.out.println(A.get(i));
}
}
public static void main(String[]args)
{
WordProgram P=new WordProgram();
Scanner scan=new Scanner(System.in);
String choice;
while(true)
{
System.out.println("Options: quit, add and a string, size, and
print");
choice=scan.nextLine();
String[]data=choice.split(" ");
if("add".equals(data[0]))
{
String word = "";
for(int i=1; i<data.length; i++)
word+=data[i];
P.add(word);
}
else if("size".equals(data[0]))
{
System.out.println("Size of the List is = "+P.size());
}
else if("print".equals(data[0]))
{
P.print();
}
else if("search".equals(data[0]))
{
String word = "";
for(int i=1; i<data.length; i++)
word+=data[i];
if(P.search(word)!=-1)
{
System.out.println(word+" found in index "+P.search(word));
}
else
{
System.out.println("not found");
}
}
else if("quit".equals(data[0]))
{
return;
}
}
}
}