I am getting a error for incompatible string and int. How do I fix the error?
Here is what I am trying to get. getSongByTitle(title:String):int a method that takes the song title as input and returns as output the position of the song in the list. If not found, the method returns -1.
public int getSongByTitle(String title){
if (title == this.songList.length){
return this.songList[title];
}
else if (title != this.songList.length){
return -1;
}
}
You're probably better off with the songList being a list rather than array, this will mean you can easily add and remove songs from it and will give you the utility function indexOf which you can use to implement getSongByTitle.
private final List<String> songList = new ArrayList<String>();
public int getSongByTitle(String title) {
return songList.indexOf(title);
}
I guess you need something like this function:
public int getSongByTitle(String title) {
for(int i=0; i<this.songList.length; i++) {
if (title.equals(this.songList[i])) // or what ever you want to compare
return i;
}
// if you do not found any thing
return -1;
}
Related
I'm supposed to complete a class named "substitute" that can change elements of a LinkedList between them. I've been trying to figure this on my own but I'm kinda new to programming and I wasn't able to find the answer, I would be grateful if someone could help me. Thanks in advance.
I'm given this code which I cannot change, only write between the brackets:
import java.util.Iterator;
import java.util.LinkedList;
public class Device implements Iterable<String>{
private static int numDevices=0; //device counter... static atribute
private String name;
private int id;
protected LinkedList<String> words;
public boolean substitute(String word1, String word2) {
//You can't use ListIterator<>
//You must use indexOf()...
//incomplete code that I'm not allowed to change ahead:
int position = this.words.indexOf(word1.toLowerCase());
return true;
}
I'm also supposed to pass this JUnit5 test:
assertTrue(d1.substitute("amigo", "perla")); //returns true because the word amigo exists --> returns true
assertFalse(d1.substitute("amigo", "perla")); //the word amigo does not exist --> returns false
assertTrue(d1.substitute("estamos", "estas"));
assertTrue(d1.substitute("que", null)); //remove the word que
assertTrue(d1.substitute("tal", null)); //remove the word tal
The LinkedList Class in Java has methods that can help you complete this problem. With the index found in the position, you can call the remove() or set() function to help complete your code.
public boolean substitute(String word1, String word2) {
int position = this.words.indexOf(word1.toLowerCase());
if(position == -1) {
return false; // index of -1 means the word wasn't found in the list, return false
}
if(word2 == null) { // remove item if word2 is null as indicated by tests
words.remove(position);
} else {
words.set(position, word2); // set word2 at the position word1 was found at
}
return true;
}
package generics;
import java.util.ArrayList;
import java.util.List;
public class Generics {
private static List <Box> newlist = new ArrayList<>();
public static void main(String[] args) {
newlist.add(new Box("charlie",30));
newlist.add(new Box("max",29));
newlist.add(new Box("john",22));
// Testing method find -- Start
find ("max",29);
//Testing method find2 -- Start
Box <String,Integer> search = new Box("max",29);
find2(search);
}
public static void find (String parameter, Integer parameter1){
for (Box e : newlist){
if(e.getName() != null && e.getMoney() !=null
&& e.getName().equals(parameter)
&& e.getMoney().equals(parameter1)){
System.out.println("found on position " + newlist.indexOf(e));
break;
}
}
}
public static void find2 (Box e){
for (Box a : newlist){
if (a.equals(e)){
System.out.println("Found");
}else {
System.out.println("Not found");
}
}
}
}
public class Box<T , D>{
private T name;
private D money;
public Box(T name, D money) {
this.name = name;
this.money = money;
}
public T getName() {
return name;
}
public D getMoney() {
return money;
}
#Override
public String toString() {
return name + " " + money;
}
}
Can someone show me how to search for an object in ArrayList.
Method find() it works perfect but in my opinion is wrong and
the reason why I am thinking like that, because I am passing as parameter a string and an integer but should be an box object or maybe I wrong?
In my second method find2() I am trying to pass as parameter an object of Box and when I am trying to search for it I got a false result =(
I am noobie I am trying to understand and to learn.
Stop using raw types!
Box is generic, so if you are not targeting older Java versions, always add generic parameters!.
The declaration of find2 should be like this:
public static void find2 (Box<String, Integer> e)
And you should check whether two boxes are equal in exactly the way you did in find. equals will not work because you did not define an equals method in Box. So:
for (Box<String, Integer> a : newlist){
if (a.getName().equals(e.getName()) &&
a.getMoney().equals(e.getMoney())){
System.out.println("Found");
}else {
System.out.println("Not found");
}
}
You should override Object.equals() on the Box class.
Try to handle null correctly too. Because 2 Box with null names and/or null money are in fact equal.
(you DON'T need to override Object.hashCode() for this, but it's a good practice to do so, just in case it is used in a hashmap or hashset or such).
The easiest way to search and find something in an arraylist is to use the .equals method combined with a for loop to iterate through your lists.
for(int i = 0; i < newList; ++i)
{
if(newlist.equals(Stringname))
{
//it matches so do something in here
}
}
what it is doing here is moving through the list 1 by 1 until it finds something that matches what you entered -> stringName
I periodically check if a string which I get from a web service changed. This works just fine but if an old string is deleted from my method triggers, too.
For Example:
//I get this at the beginning
"One,Two,Three"
//And at the next check I get this
"Two,Three"
So the String changed and my method returned true like it is supposed to do.
But I only want to return true if e.g. "Four" is added to the string.
Can anyone give me a solution for this problem?
Thank you a lot,
Freezed
if (!oldstring.contains(newstring)))
return true;
Perhaps you could use split like so
public class MyClass {
public static void main(String args[]) {
String oldString = "This,Is,A,Test";
String[] oldItems = oldString.split(",");
String newString = "This,Is,A,New";
String[] newItems = newString.split(",");
// For each new item, check all old items
for (String newItem: newItems)
{
Boolean foundItem = false;
for (String oldItem: oldItems)
{
// Item was already in the old items
if (newItem.equals(oldItem))
{
foundItem = true;
break;
}
}
// New item is not in the old list of items
if (!foundItem)
{
System.out.println("New item added: " + newItem);
}
}
}
}
Something like
newString.contains(oldString) && !newString.equals(oldString)
Why not just trigger when the length of the string increases? The question doesn't state that what is being added matters--only whether something is being added at all.
boolean result = false;
if(newString.length() > oldString.length()) {
result = true;
break;
}
return result;
EDIT: Based on further clarification, I understand that the length of the string is not the best indicator, since something can be removed and added at the same time, in which case OP wants true returned--even if length is shorter. Here's a solution that splits the strings into tokens, and then checks whether the last token of the old string occurs before the last token of the new string, because that means something was added after it:
boolean result = false;
String delim = ",";
String oldStringTokens[] = oldString.split(delim);
String newStringTokens[] = newString.split(delim);
for(int i = 0; i < newStringTokens.length; i++) {
if(oldStringTokens[oldStringTokens.length-1].equals(newStringTokens[i])) {
if(i < newStringTokens.length - 1) {
result = true;
}
}
}
return result;
I used following method to add my data to ArrayList.
ArrayList<Word> wordList = new ArrayList<Word>();
Word word = new Word();
word.set_id(id);
word.setWord(word);
word.setDefinition(definition);
wordList.add(word);
After the add some data, I want find the position of the any id which I want find in ArrayList.
Already I have tried following method to get position by id. But it isn't work.
int position = wordList.indexOf(id);
and
int position = wordList.lastIndexOf(id);
Both codes always generated "position = -1" as a result. How can I do that?
Edited
This is the code of the Word.java class. How can I implement equal method?
public class Word {
private String _id, word, definition, favourite, usage;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public String getFavourite() {
return favourite;
}
public void setFavourite(String favourite) {
this.favourite = favourite;
}
public String getUsage() {
return usage;
}
public void setUsage(String usage) {
this.usage = usage;
}
}
indexOf is trying to compare Word objects. Your list doesn't contain ids as the elements, so you get -1.
You need to use a loop and search the list.
int id = 3;
int position = -1;
for (int i = 0; i < wordlist.size(); i++) {
if (wordlist.get(i).getId() == id) {
position = i;
// break; // uncomment to get the first instance
}
}
Note: this will search the whole list to find the last index of that id. So if there are duplicates and you only want the first one (or stop the loop as soon as you find what you want) add a break in the if statement.
Implement equals method in the "Word" object. Inside equals method you can apply equals only to id field.
Create a new Word object with that id and pass that object in indexOf. Don't pass the id in the indexOf. Pass the new of existing Word object with the required id.
Then indexOf will return the valid index of this word object.
For searching the object in a list. you need to override equals method in your Word class. otherwise you will get -1. because indexOf internally used equals method to search the element in list.
The class inside your list should implement hascode() and equals() in order to have indexOf() that works.
I couldn't remove object.How can I remove a object from an arraylist?
my code
List<kisi> x=new ArrayList<kisi>();
x.add(new kisi("1","betül"));
x.add(new kisi("2","hatice"));
x.add(new kisi("3","selma"));
kisi k=new kisi("2","hatice");
for (int i = 0; i < x.size(); i++) {
if (x.get(i).id==k.id) {
Object obj = x.remove(i);
break;
}
}
my constructor
public class kisi {
public static String id="0";
public static String ad="0";
public kisi(String id,String ad) {
// TODO Auto-generated constructor stub
this.id=id;
this.ad=ad;
}
Solution
Remove the statics from your member variables in your kisi class.
But also note
new kisi("1","betül")
So your id is a String.
When you go through the list comparing ids you do so with ==.
== in java is a same comparison, not an equal comparison. This is unlike the behavior for strings in C# say.
So what you should do is this:
for (int i = 0; i < x.size(); i++) {
if (x.get(i).id.equals(k.id)) { //change here
Object obj = x.remove(i);
break;
}
}
In this simple example this is not causing the problem because the two "2" strings are the same. Which leads me to conclude there's something funny going on your kisi constructor. This is the one I used and the code worked as was:
public class kisi {
public String id;
public kisi(String id, String string2) {
this.id = id;
}
}
A constructor like this will break the code without the .equals call:
public kisi(String id, String string2) {
this.id = id + string2;
}
To remove an Element safely from a list while traversing it you need to do it with an iterator. Otherwise you might get strange results!
Calling remove in foreach loop in Java
In java the only method for removing an item from a list while traversing it is via Iterator.