Reputation: 438
In the below code, it calls an element exactly once. How can i make it print out "this is the last element in the arraylist" when everything has been removed, and there is only one element remaining.
ArrayList<String> Responselist = new ArrayList<String>();
Responselist.add(CommentResponse());
Responselist.add(TriviaResponse());
Responselist.add(CriticResponse());
String[] SelectRand = new String [3];
for (int i = 0; i < SelectRand.length; ++i)
{
int rnd = (int) (Math.random() * Responselist.size());
SelectRand[i] = Responselist.get(rnd);
Responselist.remove(rnd);
}
for (String x : SelectRand)
{
if (!(Responselist.isEmpty()))
{
System.out.println(x);
}
}
Upvotes: 6
Views: 43322
Reputation: 15552
Try and stick to conventions in java
instead of
ArrayList<String> Responselist = new ArrayList<String>();
Then code to an interface rather than a concrete class.
List<String> Responselist = new ArrayList<String>();
Also by standard java variables are camel case so it would be
List<String> responselist = new ArrayList<String>();
I think the other asnswer are sufficient to answer you original query.
Upvotes: -2
Reputation: 1526
You can resolve this with the following if-construct
if(responseList.size() == 1)
{
System.out.println("this is the last element in the arraylist")
}
You should start the variable with a lower case.
Upvotes: 1
Reputation: 286
You can make a control on the size of the arraylist, id est
if (arraylist.size()==1){
System.out.println("this is the last element in the arraylist");
}
and if you want to print the last element you can access it as (index=0 in case it is just one element)
arraylist.get(arraylist.size()-1);
Upvotes: 6
Reputation: 3827
This should do it I guess:
if (list.size() == 1) {
System.out.println(list.get(list.size() - 1)) // or just .get(0) of course...
} else {
System.out.println("List is empty or bigger than one")
}
Upvotes: 1