Java indexOf not working as expected on object list - java

I few days ago I started messing around with Javas, wanting to create a small tool for League of Legends. Now I encountered a very frustrating error.
indexOf stopped working, but I just can't figure out why. Every time I check the list "players" for the position of the entered name (l1v3 in this case) it just responds with -1. So item not found. Even though is shows up when printing the "players" list.
What did I do wrong? I'm new to coding so thanks for the help in advance!
This is the output I get:
Name: Abanke
Summoner ID: QvpMxe-XUEfD2WQujoDzHg9q4_co-7A1B6QC4W51qh8r1B0
[kus olan kumru, Abanke, Al Muqtadir, Lilipp, Solalicious, Young BuII, Nimecchii, imapz, FSL Nubels, Ulanbator Raimi]
Enemies[Young BuII, Nimecchii, imapz, FSL Nubels, Ulanbator Raimi]
-1
Code:
package leaguetimer;
import java.util.ArrayList;
import java.util.List;
import net.rithms.riot.api.ApiConfig;
import net.rithms.riot.api.RiotApi;
import net.rithms.riot.api.RiotApiException;
import net.rithms.riot.api.endpoints.summoner.dto.Summoner;
import net.rithms.riot.constant.Platform;
import net.rithms.riot.api.endpoints.spectator.dto.CurrentGameInfo;
public class LeagueTimer {
/**
* #param args the command line arguments
* #throws net.rithms.riot.api.RiotApiException
*/
public static void main(String[] args) throws RiotApiException {
// TODO code application logic here
ApiConfig config = new ApiConfig().setKey("RGAPI-9aa36868-192b-481b-b9c7-a04facf84ce1");
RiotApi api = new RiotApi(config);
Summoner summoner = api.getSummonerByName(Platform.EUW, "Abanke");
System.out.println("Name: " + summoner.getName());
System.out.println("Summoner ID: " + summoner.getId());
CurrentGameInfo match = api.getActiveGameBySummoner(Platform.EUW, summoner.getId());
List players = new ArrayList();
players = match.getParticipants();
System.out.println(players);
int check = players.indexOf(summoner.getName());
if (check < 5) {
List subList = match.getParticipants().subList(5, 10);
System.out.println("Enemies" + subList);
System.out.println(check);
}
else {
List subList = match.getParticipants().subList(0, 4);
System.out.println("Enemies" + subList);
}
}
}

Related

How to iterate over List of Lists in Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am reading a CSV file into a List<String>. However, my program creates a new List for each row in the CSV file. structure of the CSV file is shown below:
[KI , -3.370417, -168.734039, Kiribati]
[KM , -11.875001, 43.872219, Comoros]
[KN , 17.357822, -62.782998, Saint Kitts and Nevis]
[KP , 40.339852, 127.510093, North Korea]
[KR , 35.907757, 127.766922, South Korea]
[KW , 29.31166, 47.481766, Kuwait]
[KY , 19.513469, -80.566956, Cayman Islands]
[KZ , 48.019573, 66.923684, Kazakhstan]
[LA , 19.85627, 102.495496, Laos]
I want to be able to iterate over each of these lists and access items such as the "South Korea" or "KI".
However I cannot find an efficient way of doing so. My attempt is shown below for traversing the Lists in the method distance():
import java.util.*;
import java.io.*;
public class Main {
public static void distance(List<String> list) {
//attempt
for (List row : list) {
for (Object item : row) {
System.out.println(item + "\t");
}
System.out.println();
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
String file = "countries.csv";
List<String> countries;
BufferedReader reader = null;
String line = "";
reader = new BufferedReader(new FileReader(file));
while ( (line = reader.readLine()) != null ) {
List<String> nodes = Arrays.asList(line.split(","));
countries = nodes;
//System.out.println(countries);
// System.out.println(Arrays.toString(nodes));
}
System.out.println();
distance(countries);
}
}
Is there a way of iterating over and accessing elements of List of Lists?
.
I don't quite understand your question, but in any case, your code does not compile because you are treating countries as a list of lists while it is only a list of String! here is a working version of your application:
package com.company;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void distance(List<List<String>> list) {
for (List row : list) {
for(Object item: row)
System.out.println(item + "\t");
System.out.println();
}
}
public static void main(String[] args) throws IOException {
String file = "countries.csv";
List<List<String>> countries = new ArrayList<>();
BufferedReader reader = null;
String line = "";
reader = new BufferedReader(new FileReader(file));
while ( (line = reader.readLine()) != null ) {
List<String> nodes = Arrays.asList(line.split(","));
countries.add(nodes);
//System.out.println(countries);
// System.out.println(Arrays.toString(nodes));
}
System.out.println();
distance(countries);
}
}
I changed countries = nodes; to countries.add(nodes); which creates a list of List<string>, now if you want to access the last element of the inner list, you can do so like this:
System.out.println("Country: " + row.get(3));
I believe you would benefit a lot by reading on:
how to initialize objects in Java.
data structures such as Array, LinkedList and ArrayList.
You can use jackson (here you'll find documention of it https://github.com/FasterXML/jackson-dataformats-text/tree/master/csv) to read CSV file.
you can try this code, in this way you can iterate the list easily.
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class CsvUtils {
private final static CsvMapper mapper = new CsvMapper();
/**
* function to read SCV
* #param clazz {#link Class}
* #param file {#link File}
* #param <T> {#link T}
* #return List of object
* #throws IOException must catch it
*/
public static <T> List<T> read(Class<T> clazz, File file) throws IOException {
CsvSchema schema = mapper.schemaFor(clazz).withHeader().withColumnSeparator(',');
return mapper.readerFor(clazz).with(schema).<T>readValues(file).readAll();
}
}

Need help in minecraft bukkit java development with kit command

I have made plugin that have 2 kits first with name Iron and the other with the name DProtect
so i want them to give items and i made everything and i made a cool down the problem is when i type /kit Iron or /kit DProtect it doesn't work i tried to do a lot of things and doesn't work this is the code can i have some help ?
package Rivals.iSryMan.Kits.commands;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import Rivals.iSryMan.Kits.Main;
public class Kit implements CommandExecutor{
private HashMap<UUID,Long> ironcooldown = new HashMap<UUID,Long>();
private int ironcooldowntime = 300;
private HashMap<UUID,Long> DProtectcooldown = new HashMap<UUID,Long>();
private int DProtectcooldowntime = 5259487;
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(sender instanceof Player) {
Player p = (Player)sender;
if(args.length == 1) {
//Kit Iron
if(args[0].equals("Iron")) {
if(ironcooldown.containsKey(p.getUniqueId())) {
long ironsecondsleft = ( (ironcooldown.get(p.getUniqueId())/ 1000) + ironcooldowntime) - (System.currentTimeMillis() / 1000);
if(ironsecondsleft > 0) {
p.sendMessage(Main.Color(Main.prefix + "You must wait " + ironsecondsleft + " before you take that kit again!"));
}else if(ironsecondsleft == 0) {
final ItemStack ironhelmet = new ItemStack(Material.IRON_HELMET);
final ItemStack ironchestplate = new ItemStack(Material.IRON_CHESTPLATE);
final ItemStack ironleggings = new ItemStack(Material.IRON_LEGGINGS);
final ItemStack ironboots = new ItemStack(Material.IRON_BOOTS);
p.getInventory().addItem(ironhelmet);
p.getInventory().addItem(ironchestplate);
p.getInventory().addItem(ironleggings);
p.getInventory().addItem(ironboots);
p.sendMessage(Main.Color(Main.prefix + " You've got your kit, Enjoy!"));
}
}
//Kit Iron
//Kit DProtect
} else if (args[0].equals("DProtect")) {
if(DProtectcooldown.containsKey(p.getUniqueId())) {
long DProtectsecondsleft = ( (DProtectcooldown.get(p.getUniqueId()) / 1000) + DProtectcooldowntime) - (System.currentTimeMillis() / 1000);
if(DProtectsecondsleft > 0) {
p.sendMessage(Main.Color(Main.prefix + "You must wait " + DProtectsecondsleft + " before you take that kit again!"));
}else if(DProtectcooldowntime == 0) {
final ItemStack dphelmet = new ItemStack(Material.IRON_HELMET);
final ItemMeta dphelmetmeta = dphelmet.getItemMeta();
final ItemStack dpchestplate = new ItemStack(Material.IRON_CHESTPLATE);
final ItemMeta dpchestplatemetaa = dphelmet.getItemMeta();
final ItemStack dpleggings = new ItemStack(Material.IRON_LEGGINGS);
final ItemMeta dpleggingsmeta = dphelmet.getItemMeta();
final ItemStack dpboots = new ItemStack(Material.IRON_BOOTS);
final ItemMeta dpbootsmeta = dphelmet.getItemMeta();
ArrayList<String> dplore = new ArrayList<String>();
dplore.add(Main.Color("&bAuthentic Protection 4 Armor"));
//Set Meta
dphelmet.setItemMeta(dphelmetmeta);
dpchestplate.setItemMeta(dpchestplatemetaa);
dpleggings.setItemMeta(dpleggingsmeta);
dpboots.setItemMeta(dpbootsmeta);
//Set Meta
//Set Lore
dphelmetmeta.setLore(dplore);
dpchestplatemetaa.setLore(dplore);
dpleggingsmeta.setLore(dplore);
dpbootsmeta.setLore(dplore);
//Set Lore
//Adding Kit
p.getInventory().addItem(dphelmet);
p.getInventory().addItem(dpchestplate);
p.getInventory().addItem(dpleggings);
p.getInventory().addItem(dpboots);
//Adding Kit
p.sendMessage(Main.Color(Main.prefix + " You've got your kit, Enjoy!"));
}
}
//Kit DProtect
}
return true;
}
}
return false;
}
}
Have you made sure:
Your command is registered in onEnable() and plugin.yml?
You type specifically 'Iron' with a capital I? You should allow for different cases, using equalsIgnoreCase()
This is probably the issue. Your HashMap does not contain the UUID of the CommandExecutor at first, therefore it never gets passed the ironcooldown.containsKey(p.getUniqueId()). I would recommend checking if they are in it. If they are, check if the time is 0, otherwise add them after the code has been executed.
Let me know if this works.
Also, you should fix the indentation of your code - it confused me at first and it may confuse you in the future. This is not a big deal, however.
Although Slinthn answered your questions, I thought I'd add a bit more of an explanation.
You declare a private HashMap for both kits cooldown's: ironcooldown and DProtectcooldown.
You check within your onCommand if the player executing the command is in that HashMap in your condition if(ironcooldown.containsKey(p.getUniqueId())), however, that condition will never be true because the player's UUID is never added to the HashMap.
It looks to me like you want to do something like the following (half pseudo-code)
if(!(sender instanceof Player))
return true;
if(args.length == 0)
return true;
Player p = (Player) sender;
if(args[0].equalsIgnoreCase("iron")){
if(ironcooldown.containsKey(p.getUniqueId())){
//Do check if they are still on cooldown
//... if so, return here
}
ironcooldown.put(p.getUniqueId(), System.currentTimeMillis());
givePlayerKit(Kits.IRON, p); //made up function that takes Enum & Player
}
//etc
It seems that you haven't added the player to the HashMap so it will return false so you might want to make your HashMaps public and static and inside your PlayerJoinEvent (if you have one) add
Kit.ironcooldown.put(p.getUniqueId(), 0);
or if you don't have a PlayerJoinEvent and/or you don't want to do that, you can put before your args check
if (!ironcooldown.containsKey(p.getUniqueId()) {
ironcooldown.put(p.getUniqueId(), 0);
}
Do the same for Dprotectcooldown.
Hope this helped!

Why does Player name get printed twice by my code?

Main Class
package main;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.Test;
import lib.Die;
import lib.Name;
import lib.PairOfDice;
import lib.Player;
public class PlayerAppTest {
/* Please note - when we come to mark the solution to this unit test we will change the input
* data set for the players added to the list to ensure the solution works dynamically based
* upon any given data set and is not hardcoded in any way.
*/
#Test
public void testExecute() {
ArrayList<Player> players = new ArrayList<>();
players.add(new Player(new Name("Joe", "Bloggs"), new PairOfDice()));
players.add(new Player(new Name("Fred", "Jones"), new Die()));
players.add(new Player(new Name("Nila", "Singh"), new PairOfDice(new Die(5), new Die(5))));
String result = PlayerApp.execute(players, "Cassie Downturn");
String expectedResult = "cassie, DOWNTURN\nnila, SINGH\n";
assertEquals("The string returned should match the expected result (run 1)", expectedResult, result);
/* Test with a second set of input data */
ArrayList<Player> players2 = new ArrayList<>();
players2.add(new Player(new Name("David", "Blunt"), new PairOfDice()));
players2.add(new Player(new Name("Tim", "Jonas"), new Die(5)));
players2.add(new Player(new Name("Remi", "Patel"), new Die()));
String result2 = PlayerApp.execute(players2, "Cassie Downturn");
String expectedResult2 = "cassie, DOWNTURN\ntim, JONAS\nremi, PATEL\n";
assertEquals("The string returned should match the expected result (run 2)", expectedResult2, result2);
}
}
Hello, this is the JUnit test which I have to pass, below is the code that I have written in my main package;
JUnit Test Class
package main;
import java.util.ArrayList;
import lib.Player;
public class PlayerApp {
public static String execute(ArrayList<Player> players, String fullName) {
players.get(0).setFullPlayerName(fullName);
fullName = "";
for (int i = 0; i <players.size(); i ++) {
if (players.get(i).getName().getFirstName().toLowerCase().contains("a") || players.get(i).getName().getFamilyName().toUpperCase().contains("a")) {
fullName = players.get(i).getName().getFirstName().toLowerCase() + ", " + players.get(i).getName().getFamilyName().toUpperCase() + "\n";
}
System.out.println(fullName);
}
return fullName;
}
}
This is the code in my main package, I am trying to print out the names which contain a char "a" in the first name, the first name should be lowercase and the family name should be uppercase. It should print out
cassie, DOWNTURN
nila, SINGH which is the names with a new line between them, however, when i print it, it prints the following;
cassie, DOWNTURN
cassie, DOWNTURN
nila, SINGH
I am confused as to why cassie, DOWNTURN has been printed twice as i cannot find the error in my code, any help would be greatly appreciated, thank you.
You will print it even if the if doesn't match as it's outside the if-statement. Move it inside instead.
for (int i = 0; i <players.size(); i ++) {
if (players.get(i).getName().getFirstName().toLowerCase().contains("a") || players.get(i).getName().getFamilyName().toUpperCase().contains("a")) {
fullName = players.get(i).getName().getFirstName().toLowerCase() + ", " + players.get(i).getName().getFamilyName().toUpperCase() + "\n";
System.out.println(fullName);
}
}
Your print statement is not conditional and will always execute, move it inside the if. You're printing twice as your are not changing the value in fullName if the if condition does not evaluate as true. Further your family name comparison will always be false as you're comparing upper and lower case.
Your code can also be tided up and made easier to read:
for(Player player : players){
if(player.getName().getFirstName()).toLowerCase().contains("a")||player.getName().getFamilyName().toUpperCase.contains("A"))){
String fullName = players.get(i).getName().getFirstName().toLowerCase() + ", " + players.get(i).getName().getFamilyName().toUpperCase() + "\n";
System.out.println(fullname);
}
}

How could I use Stanford Core NLP to generate the dependency of a Chinese Sentence? It can only works greatly with English

How could I use Stanford Core NLP to generate the dependency of a Chinese Sentence? It can only work greatly with English
public class DemoChinese { public static void main(String[] args) {
Properties props = PropertiesUtils.asProperties("props", "StanfordCoreNLP-chinese.properties");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
Annotation document = new Annotation("我喜欢吃苹果");
pipeline.annotate(document);
List<CoreMap> sentence = document.get(SentencesAnnotation.class);
#SuppressWarnings("deprecation")
// Produce a dependency of this sentence.
SemanticGraph dp= sentence.get(0).get(SemanticGraphCoreAnnotations
.CollapsedCCProcessedDependenciesAnnotation.class);
String s = dp.typedDependencies().toString();
System.out.println(s);
}
}
Setting up the Properties as you did doesn’t work. This is maybe confusing, but the StanfordCoreNLP constructor needs a “real” properties list and it won’t process a props key expanding it out with its contents. (But doing things as you did appears in some examples – I initially assumed that it used to work and there was a regression, but it doesn’t seem like it worked in any of 3.6. 3.7, or 3.8, so maybe those examples never worked.) Also, in the example below, I get the dependencies in the non-deprecated way.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import edu.stanford.nlp.coref.CorefCoreAnnotations;
import edu.stanford.nlp.coref.data.CorefChain;
import edu.stanford.nlp.io.IOUtils;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.semgraph.SemanticGraph;
import edu.stanford.nlp.semgraph.SemanticGraphCoreAnnotations;
import edu.stanford.nlp.util.CoreMap;
/**
* #author Christopher Manning
*/
public class StanfordCoreNlpDemoChinese {
private StanfordCoreNlpDemoChinese() { } // static main
public static void main(String[] args) throws IOException {
// set up optional output files
PrintWriter out;
if (args.length > 1) {
out = new PrintWriter(args[1]);
} else {
out = new PrintWriter(System.out);
}
Properties props = new Properties();
props.load(IOUtils.readerFromString("StanfordCoreNLP-chinese.properties"));
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
Annotation document;
if (args.length > 0) {
document = new Annotation(IOUtils.slurpFileNoExceptions(args[0]));
} else {
document = new Annotation("我喜欢吃苹果");
}
pipeline.annotate(document);
List<CoreMap> sentences = document.get(CoreAnnotations.SentencesAnnotation.class);
int sentNo = 1;
for (CoreMap sentence : sentences) {
out.println("Sentence #" + sentNo + " tokens are:");
for (CoreMap token : sentence.get(CoreAnnotations.TokensAnnotation.class)) {
out.println(token.toShorterString("Text", "CharacterOffsetBegin", "CharacterOffsetEnd", "Index", "PartOfSpeech", "NamedEntityTag"));
}
out.println("Sentence #" + sentNo + " basic dependencies are:");
out.println(sentence.get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class).toString(SemanticGraph.OutputFormat.LIST));
sentNo++;
}
// Access coreference.
out.println("Coreference information");
Map<Integer, CorefChain> corefChains =
document.get(CorefCoreAnnotations.CorefChainAnnotation.class);
if (corefChains == null) { return; }
for (Map.Entry<Integer,CorefChain> entry: corefChains.entrySet()) {
out.println("Chain " + entry.getKey());
for (CorefChain.CorefMention m : entry.getValue().getMentionsInTextualOrder()) {
// We need to subtract one since the indices count from 1 but the Lists start from 0
List<CoreLabel> tokens = sentences.get(m.sentNum - 1).get(CoreAnnotations.TokensAnnotation.class);
// We subtract two for end: one for 0-based indexing, and one because we want last token of mention not one following.
out.println(" " + m + ":[" + tokens.get(m.startIndex - 1).beginPosition() + ", " +
tokens.get(m.endIndex - 2).endPosition() + ')');
}
}
out.println();
IOUtils.closeIgnoringExceptions(out);
}
}

How to get the phone number from a vcard

I am using cardme library to deal with vcards. Following is my code
package vcardtest;
import java.io.*;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.cardme.engine.VCardEngine;
import net.sourceforge.cardme.vcard.VCard;
import net.sourceforge.cardme.vcard.features.EmailFeature;
import net.sourceforge.cardme.vcard.features.NameFeature;
import net.sourceforge.cardme.vcard.features.NicknameFeature;
import net.sourceforge.cardme.vcard.features.TelephoneFeature;
import net.sourceforge.cardme.vcard.types.parameters.TelephoneParameterType;
public class VCardTest
{
public static void main(String[] args)
{
File vcardFile = new File("C:/Users/yohan/Contacts/Yohan Weerasinghe.vcf");
VCardEngine vcardEngine = new VCardEngine();
try
{
VCard vcard = vcardEngine.parse(vcardFile);
String name = vcard.getName().getGivenName();
EmailFeature email = vcard.getEmails().next();
String sEmail = email.getEmail();
NicknameFeature nickName = vcard.getNicknames();
Iterator<String> nicknames = nickName.getNicknames();
String sNickName = nicknames.next();
Iterator<TelephoneFeature> telephoneNumbers = vcard.getTelephoneNumbers();
TelephoneFeature next = telephoneNumbers.next();
String telephone = "";
while(vcard.getTelephoneNumbers().hasNext())
{
TelephoneFeature next1 = vcard.getTelephoneNumbers().next();
telephone = next1.getTelephone();
System.out.println(telephone);
}
Iterator<TelephoneParameterType> telephoneParameterTypes = next.getTelephoneParameterTypes();
TelephoneParameterType next1 = telephoneParameterTypes.next();
String type = next1.getType();
TelephoneParameterType next2 = telephoneParameterTypes.next();
String type2 = next2.getType();
System.out.println( name );
System.out.println(sEmail);
System.out.println(sNickName);
System.out.println(type);
System.out.println(type2);
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
However, there is no method called getNumber() or something. How can I get the mobile numbers and land numbers? Please help!
NOTE: I UPDATED THE CODE. In there, you can see I managed to get the phone number. But, this returns only the HOME phone and not anything else. Even the loop is not stopping. Please help!
I can see
TelephoneFeature.getTelephone()
I'd also suggest taking a look at
TelephoneFeature.getTelephoneParameterTypes()
to see the types
UPDATE
Be careful with the iterators
Each call to vcard.getTelephoneNumbers() is creating a new Iterator, which means you could end up in an infinite loop.
Iterator<TelephoneFeature> itNumbers = vcard.getTelephoneNumbers();
while (itNumbers.hasNext()) {
TelephoneFeature next1 = itNumbers.next();
String telephone = next1.getTelephone();
System.out.println(telephone);
System.out.println("types = " + next1.getExtendedTelephoneParameterSize());
Iterator<XTelephoneParameterType> itTypes = next1.getExtendedTelephoneParameterTypes();
while (itTypes.hasNext()) {
XTelephoneParameterType next = itTypes.next();
System.out.println(" - " + next.getType() + " / " + next.getDescription());
}
}
I stand corrected, the problem (isn't a bug) it's with the tester, not the API :P
If you add
Iterator<TelephoneParameterType> itNTypes = next1.getTelephoneParameterTypes();
while (itNTypes .hasNext()) {
TelephoneParameterType next = itNTypes .next();
System.out.println(" - " + next.getType() + " / " + next.getDescription());
}
to the previous loop, you should get what you're looking for

Categories