Checking if the entity is on the list - java

I'm programming a friend system for my "forcefield" in a game called Minecraft. My idea is that if the player is not on the friend list, the player will it attack. The follow is all the code for my friend system and forcefield.
public static boolean friends = true;
public static List friend = new ArrayList();
public static void friendsList(){
if(friends){
try{
File file = new File("friends.txt");
BufferedWriter bufferedwriter = new BufferedWriter(new FileWriter(file));
for(int i = 0; i < friend.size(); i++){
bufferedwriter.write((new StringBuilder()).append((String) friend.get(i)).append("\r\n").toString());
}
bufferedwriter.close();
}
catch(Exception exception){
System.err.print(exception.toString());
}
}
Forcefield:
if(Camb.nocheat){
if (Camb.killaura)
{
hitDelay++;
for(Object o: mc.theWorld.loadedEntityList){
Entity e = (Entity)o;
if(e != this && *******CHECK IF PLAYER IS NOT ON LIST******* && e instanceof EntityPlayer &&getDistanceToEntity(e) < 3.95D){
if(e.isEntityAlive()){
if(hitDelay >= 4){
if(Camb.criticals){
if(mc.thePlayer.isSprinting()==false){
if(mc.thePlayer.isJumping==false){
if(mc.thePlayer.onGround){
mc.thePlayer.jump();
}
}
}
}
swingItem();
mc.playerController.attackEntity(this, e);
hitDelay = 0;
break;
}
}
}
}
}
}
Adding/removing/clearing the friend list:
if(par1Str.startsWith("&friendadd")){
Camb.friends = true;
String as0[] = par1Str.split("");
Camb.friend.add(as0[1]);
mc.thePlayer.addChatMessage((new StringBuilder()).append("\2479[CAMB]\247e Added Friend.").append("").toString());
Camb.friendsList();
Camb.friends = false;
return;
}
if(par1Str.startsWith("&friendremove")){
Camb.friends = true;
String as0[] = par1Str.split("");
Camb.friend.remove(as0[1]);
mc.thePlayer.addChatMessage((new StringBuilder()).append("\2479[CAMB]\247e Removed Friend.").append("").toString());
Camb.friendsList();
Camb.friends = false;
return;
}
if(par1Str.startsWith("&friendclear")){
Camb.friends = true;
Camb.friend.clear();
Camb.friendsList();
mc.thePlayer.addChatMessage("\2479[CAMB]\247e Friends list cleared.");
return;
}
par1Str is the string entered in chat. Basically commands. Additionally, the &friendremove system is broken as well. I'm unsure why.
Thanks,
Brad

Use friend.contains(e). It checks for equality albeit by iteration.
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

I'm not too familiar with the SDK you're using to make this, but you can use this oneliner to check if an element is in an ArrayList.
myList.contains("friendname");
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#contains(java.lang.Object)

Related

Unable to write values into excel using multiple workbook.write methods

The below code is working without any runtime error if I call the owb.write(fileOut) and fileOut.close() method only once at at the ending (commented as write and close positioning) but the problem here is that the first value to be set when k=1, is not being printed in the workbook. It works fine when the iteration is in other columns and k=1.Only the first iteration is not being printed. Rest of the values are being set correctly.
I tried using multiple workbook.write() method. If you look at the below code, commented as [1], I had to invoke owb.write(fileOut) separately in the if condition(commented as if condition[1]) and else condition(commented as else condition [2]) because as I said, first value was not getting set in the workbook. I am getting the following runtime error while trying to execute the code in this scenario: Fail to save: an error occurs while saving the package : The part /docProps/app.xml fail to be saved in the stream with marshaller org.apache.poi.openxml4j.opc.internal.marshallers.DefaultMarshaller#3740f768
for(int i=0;i<noOfCols1;i++)
{
for(int j=1;j<=noOfRows1;j++)
{
value1 = formatter.formatCellValue(sheet1.getRow(j).getCell(i));
for(int m=1;m<=noOfRows2;m++)
{
value2 = formatter.formatCellValue(sheet2.getRow(m).getCell(i));
value1= value1.trim();
value2=value2.trim();
int value2Position = sheet2.getRow(m).getCell(i).getRowIndex();
if(!positions.contains(value2Position))
{
if(value1.contentEquals(value2))
{
positions.add(value2Position);
matched = true;
}
else{
matched = false;
}
}
if(matched==true)
{
break;
}
}
if(matched == false)
{
int k=1;
if(cFilledPositions.isEmpty()) //If condition[i]
{
rowHead = sheet.createRow((short)k);
rowHead.createCell(i).setCellValue(value1);
owb.write(fileOut); //[1]
}
else //else condition [1]
{
int l = cFilledPositions.size()-1;
k = cFilledPositions.get(l)+1;
rowHead = sheet.createRow((short)k);
rowHead.createCell(i).setCellValue(value1);
owb.write(fileOut);
}
cFilledPositions.add(k);
}
matched = false;
}
cFilledPositions.clear();
positions.clear();
}
//write and close positioning
fileOut.close();
I tried debugging and found that the createRow() method deletes the values previously created if called again on the same row.
To elaborate this, suppose the sheet.createRow() sets the value of a cell in the first iteration, and when it finishes its iteration in the j for loop, the cFilledPositions list is cleared and while it comes back after going to the main loop, 'cFilledPositionswill be empty and the integerkwill again be initialized to1. This is whencreateRow(k)` which is 1 is called again. This would flush out the previously existing values in the 1st row. I am trying to figure out a work around for this and will edit my answer with the solution if I my code works.
Below was the work around. I checked if the row is empty. The createRow function is called only when the row is empty. I have added the comments for the new code.
for(int i=0;i<noOfCols1;i++)
{
for(int j=1;j<=noOfRows1;j++)
{
value1 = formatter.formatCellValue(sheet1.getRow(j).getCell(i));
for(int m=1;m<=noOfRows2;m++)
{
value2 = formatter.formatCellValue(sheet2.getRow(m).getCell(i));
value1= value1.trim();
value2=value2.trim();
int value2Position = sheet2.getRow(m).getCell(i).getRowIndex();
if(!positions.contains(value2Position))
{
if(value1.contentEquals(value2))
{
positions.add(value2Position);
matched = true;
}
else{
matched = false;
}
}
if(matched==true)
{
break;
}
}
if(matched == false)
{
int k=1;
if(cFilledPositions.isEmpty())
{
try{
isEmpty = checkIfRowIsEmpty(sheet,k,formatter);
if(isEmpty)
{
rowHead = sheet.createRow(k);
}
rowHead.createCell(i).setCellValue(value1);
}
catch (Exception e){
try{
rowHead = sheet.createRow(k);
rowHead.createCell(i).setCellValue(value1);
}
catch (Exception e1){
}
}
}
else
{
int l = cFilledPositions.size()-1;
k = cFilledPositions.get(l)+1;
try{
isEmpty = checkIfRowIsEmpty(sheet,k,formatter);
if(isEmpty)
{
rowHead = sheet.createRow(k);
}
rowHead.createCell(i).setCellValue(value1);
}
catch (Exception e)
{
try{
rowHead = sheet.createRow(k);
rowHead.createCell(i).setCellValue(value1);
}
catch (Exception e1){
}
}
}
cFilledPositions.add(k);
}
matched = false;
}
cFilledPositions.clear();
positions.clear();
}

Using a for-each loop to return largest value in arraylist

I'm having trouble writing a for-each loop that searches the arraylist and returns the county's name within the continent that has the highest gdp. Here's my code for it right now. (ElementsList is the original ArrayList)
public Country highestGdp(String continent) {
boolean flag;
for (Country cont : ElementsList) {
if (cont.getContinent().equals(continent)) {
ArrayList<Country> TMP1 = new ArrayList<Country>();
TMP1.add(cont);
for (Country gdp : TMP1) {
double max = 0;
if (max < gdp.getGDP()) {
max = gdp.getGDP();
}
if (gdp.getGDP() == max) {
ArrayList<Country> TMP2 = new ArrayList<Country>();
TMP2.add(gdp);
}
return gdp;
}
}
}
return null;
}
Each time you find a country in the right continent, you can check to see if it is greater than the max so far. Don't need to loop through all of them each time.
public Country highestGdp(String continent) {
boolean flag;
Country maxCountry = null;
for (Country cont : ElementsList) {
if (cont.getContinent().equals(continent)) {
if (maxCountry == null) maxCountry = cont;
if (maxCountry.getGDP() < gdp.getGDP()) {
maxCountry = cont;
}
}
}
return maxCountry;
}
Sorry for saying it but Your code is a little messy ;)
To shortly solve Your problem, try to move max declaration before the loop like this:
[...]
double max = 0;
for(Country gdp : TMP1){
[...]
We can see that TMP2 is completely useless, remove it:
// ArrayList<Country> TMP2 = new ArrayList<Country>();
// TMP2.add(gdp);
You create TMP1 list always with only 1 element and then iterate over it. This is also useless, You can do the code directly on the element You are adding to the list.
First iteration over ElementList is a list of Country elements, but the element You iterate is called cont (=continent) which is a Continent and not the Country. Is it intended to use Country class to cover both: Countries and Continents? Do You plan to have a tree structure like "Continents contains many Countries"?
Final code to solve problem from Your original question should be like this:
public Country highestGdp(String continent){
Country countryWithMaxGdp = null;
for(Country cont: ElementsList ){
if(cont.getContinent().equals(continent)){
if(countryWithMaxGdp == null || countryWithMaxGdp.getGDP() < cont.getGDP()){
countryWithMaxGdp = cont;
}
}
}
return countryWithMaxGdp;
}

Comparing information in nested loops and marking when they match

data is an array carrying:
observation1, observation2, observation3, observation4, observation5
stringarray2 an array which may contain any of the above, eg:
observation1, observation4
I am trying to add items into countryList, setting them true if they appear in both arrays, otherwise setting false.
I need help setting up the nested loops.
I currently have the below setup which is really close, but this only adds the last item in array 2 as true (eg, observation4)
Can you see where I am going wrong please?
while (data.moveToNext()){
if (data.moveToFirst()){
do{
observation = data.getString(1);
if (editing.equals("yes")) {
stringarray2
Boolean test = false;
for (String name:stringarray2)
{
if (observation.equals(name)){
test = true;
}else{
test = false;
}
}
Country country = new Country(null,observation,test);
countryList.add(country);
}else{
Country country = new Country(null,observation,false);
countryList.add(country);
}
}while(data.moveToNext());
}
}
Try this
if (data.moveToFirst())
{
do
{
observation = data.getString(1);
if (editing.equals("yes"))
{
stringarray2 //random word here?
Boolean test = false;
for (String name:stringarray2)
{
if (observation.equals(name))
{
test = true;
break;
}
}
Country country = new Country(null,observation,test);
countryList.add(country);
}
else
{
Country country = new Country(null,observation,false);
countryList.add(country);
}
}
while (data.moveToNext())
}
I think you problem is in your while and if condition.
With your first loop you have
while (data.moveToNext())
moveToNext() already checks if there is a next and moves to it, you shouldn't be moving to first again, just start using the value
You need something like
try {
while (data.moveToNext()) {
observation = data.getString(1);
if (editing.equals("yes")) {
stringarray2
Boolean test = false;
for (String name:stringarray2)
{
if (observation.equals(name)){
test = true;
}else{
test = false;
}
}
Country country = new Country(null,observation,test);
countryList.add(country);
}else{
Country country = new Country(null,observation,false);
countryList.add(country);
}
}
} finally {
data.close();
}
Assuming your inner logic is working fine.
P.S I added a try finally, because you need to close your cursor after your're done with the query result.

Merge two sorted linked lists in java

I need to merge two sorted linked list into one sorted list. I've been trying to do so for hours, but when I reach the end of one of the list I always have some trouble. This is the best I could do. My filaA and filaB are liked lists of data type "long".
LinkedList<Long> result= new LinkedList<Long>();
iterA = filaA.listIterator();
iterB = filaB.listIterator();
while (iterA.hasNext() && iterB.hasNext()) {
n = iterA.next();
m = iterB.next();
if (n <= m) {
filafusion.add(n);
n = iterA.next();
} else {
filafusion.add(m);
m = iterB.next();
}
}
if (iterA.hasNext()) {
while (iterA.hasNext()) {
filafusion.add(iterA.next());
}
} else {
while (iterB.hasNext()) {
filafusion.add(iterB.next());
}
}
iterfusion = filafusion.listIterator();
while (iterfusion.hasNext()) {
System.out.print(iterfusion.next());
}
}
The general idea here is to compare one by one and then move the iterator to the next. But they are moving at the same time, so I'm only comparing first with first, second with second, and so on.
I also tried to move the n = iterA.next();m = iterB.next(); before the while loop, which makes it work much better, but then I don't know which list runs out of elements. Only works if the lists are the same lenght but then one of the elements won't enter the result.
I've seen many codes for this here, but they all use Nodes and recursion and stuff I'm not familiar with. I think using iterators will make it more efficient, but that's what's got me so confused, I'm not iterating where I should :(
Any suggestions will be appreciated.
You can use the standard java.util.TreeSet to do the job.
here is a full example :
LinkedList<Long> filaA = new LinkedList<>();
filaA.add(1l);
filaA.add(3l);
filaA.add(5l);
LinkedList<Long> filaB = new LinkedList<>();
filaB.add(2l);
filaB.add(4l);
filaB.add(6l);
Set<Long> result = new TreeSet<>();
result.addAll(filaA);
result.addAll(filaB);
System.out.println(result);
TreeSet use natural order.
I just adapted your code. If you are able to use Java 8, then I have a much shorter solution below.
Iterator iterA = filaA.listIterator();
Iterator iterB = filaB.listIterator();
Long n = (Long)iterA.next();
Long m = (Long)iterB.next();
while (true) {
if (n <= m) {
filafusion.add(n);
if(iterA.hasNext()){
n = (Long)iterA.next();
}
else{
filafusion.add(m);
while(iterB.hasNext()){
filafusion.add((Long)iterB.next());
}
break;
}
} else {
filafusion.add(m);
if(iterB.hasNext()){
m = (Long)iterB.next();
}
else{
filafusion.add(n);
while(iterA.hasNext()){
filafusion.add((Long)iterA.next());
}
break;
}
}
}
Iterator iterfusion = filafusion.listIterator();
while (iterfusion.hasNext()) {
System.out.println(iterfusion.next());
}
Here is the Java 8 way to do it. And it also works for unsorted input lists:
Stream stream = Stream.concat(filaA.stream(), filaB.stream());
stream.sorted().forEach(System.out::println);
public static <T extends Comparable<T>> List<T> mergeSortedLists(List<T> list1, List<T> list2) {
List<T> result = new ArrayList<>();
Iterator<T> iterator1 = list1.iterator();
Iterator<T> iterator2 = list2.iterator();
boolean hasNext1 = iterator1.hasNext();
boolean hasNext2 = iterator2.hasNext();
T next1 = hasNext1 ? iterator1.next() : null;
T next2 = hasNext2 ? iterator2.next() : null;
while (hasNext1 || hasNext2) {
if (!hasNext1) {
result.add(next2);
hasNext2 = iterator2.hasNext();
next2 = hasNext2 ? iterator2.next() : null;
} else if (!hasNext2) {
result.add(next1);
hasNext1 = iterator1.hasNext();
next1 = hasNext1 ? iterator1.next() : null;
} else {
if (next1.compareTo(next2) < 0) {
result.add(next1);
hasNext1 = iterator1.hasNext();
next1 = hasNext1 ? iterator1.next() : null;
} else {
result.add(next2);
hasNext2 = iterator2.hasNext();
next2 = hasNext2 ? iterator2.next() : null;
}
}
}
return result;
}

searching a particular input against an arraylist of object type

public void searchWatch(long srch){
long s = srch;
boolean found = false;
for(int i = 0; i<watchStore.size();i++){
Watch fd = watchStore.get(i);
if(fd.equals(s)){
System.out.print("item found");
found = true;
}
if(!found){
System.out.println("no such record");
}
}
}
this is a code fragment from one of my class. my question here is I want to test a particular input of type long against an arraylist of type Watch. whether the serial number exist in the arraylist.
but it fails due to an error " .equal() on incompatible types" whats the problem with the above code
the following is the revised code
public Watch findWatchBySerialNumber(long srch){
long s = srch;
Watch watch = null;
for(int i = 0; i<watchStore.size();i++){
watch = watchStore.get(i);
if(watchStore.contains(s)){ // this pop an error called suspicious call to java.utit.Collection.contains
System.out.print("item found");
return watch;
}
}
System.out.print("item not found");
return null; // watch is not found.
}
please how can I fix that.
When u do if(fd.equals(s)){ you are trying to match A String with another object of type Watch and that is why you are getting the error.
You need to get the String representation of fd and then match it with s.
'fd' is an object of Watch and 's' is an object of String. Since these are two different classes, running a fd.equals(s) will throw the error.
To get it working, try overriding the toString() method in the Watch class and then do
fd.toString().equals(s)
If you try to find by serial number then:
public void searchWatch (long srch){
boolean isFound = false;
Watch fd = null; // declaring variable out of the loop is better.
for(int i = 0; i<watchStore.size();i++){
fd = watchStore.get(i);
if(fd.getSerialNumber.equals(srch)){
System.out.print("item found");
isFound = true;
}
if(!found){
System.out.println("no such record");
}
}
}
My suggestion: if you write your method name as search or find you should return an object. If you only need to know "is it exist", you can give a name to your method: isWatchExist() and add a boolean return type.
public boolean isWatchExist (long serialNumber) {
Watch watch = null; // declaring variable out of the loop is better.
for(int i = 0; i < watchStore.size(); i++){
watch = watchStore.get(i);
if(watch.getSerialNumber.equals(serialNumber)){
System.out.print("item found");
return true;
}
}
System.out.println("no such record");
return false;
}
If you need to find object, you should add a return type of your object. Give a name that describes your method goal clearly.
public Watch findWatchBySerialNumber (long serialNumber){
boolean isFound = false;
Watch watch = null; // declaring variable out of the loop is better. and name of you variable should describe your object, same name is better.
for(int i = 0; i < watchList.size(); i++){ // your list name should be "watchList".
watch = watchList.get(i);
if(fd.getSerialNumber.equals(serialNumber)){
System.out.print("item found");
return watch;
}
}
System.out.print("item not found");
return null; // watch is not found.
}
Replace:
Watch fd = watchStore.get(i);
With:
Watch fd = watchStore.get(i);`
// use getter method
String fdString = fd.getSerial();
if(fdString.equals(s)){
System.out.print("item found");
found = true;
}
See if that helps.

Categories

Resources