Hey im trying convert all my ForEachs into ForLoops as i am now using a Linked List.
I am having trouble with this one for some reason! Anyone able to covert the forEach into a forLoop
public String listCounty(String county) {
boolean matchFound = false;
int i = 0;
String displayPropertys = "All Propertys";
for (Property item : house) {
if (item.getGeneralLocation().equals(county)) {
displayPropertys += "\n" + i++ + item;
i++;
matchFound = true;
} else i++;
}
if (!matchFound)
return "No propertys for this County";
else
return displayPropertys;
}
}
Assuming house is a LinkedList<Property> you could use LinkedList.get(int) but it would be more efficient to use a traditional iterator (because accessing arbitrary indices of a LinkedList is potentially expensive). You could also use a StringJoiner. Something like,
public String listCounty(String county) {
boolean matchFound = false;
Iterator<Property> iter = house.iterator();
StringJoiner sj = new StringJoiner(System.lineSeparator());
sj.add("All Propertys");
for (int i = 0; iter.hasNext(); i++) {
Property item = iter.next();
if (item.getGeneralLocation().equals(county)) {
sj.add(String.format("%d%s", i + 1, item));
matchFound = true;
}
}
return !matchFound ? "No propertys for this County" : sj.toString();
}
You should be able to do it using the following.
for(int index = 0; index < house.size(); index++)
{
Property item = house.get(index);
// Your code goes here
}
There's also no need for the i variable now that we have the index from the for loop.
public String listCounty(String county) {
boolean matchFound = false;
String displayPropertys = "All Propertys";
for (int index = 0; index < house.length; index++) {
Property item = house.get(index)
if (item.getGeneralLocation().equals(county)) {
displayPropertys += "\n" + (index + 1) + item;
matchFound = true;
}
}
if (!matchFound)
return "No propertys for this County";
else
return displayPropertys;
}
You can also use an iterator like Elliot suggests. This will give you better performance but is a bit more difficult to read.
Iterator<Property> iterator = house.iterator();
for (int index = 0; iterator.hasNext(); index++) {
Property item = iterator.next();
// Your code goes here
}
As per your question, I am assuming house is a LinkedList
for (int k = 0; k < house.size(); k++) {
if (house.get(k).getGeneralLocation().equals(county)) {
displayPropertys += "\n" + i++ + house.get(k);
matchFound = true;
} else i++;
}
Related
I have next method
public Event findEvent(Date date){
for (int i = 0; i < events.length ; i++) {
if(events[i].getDate() == date){
return events[i];
}
}
return null;
}
It returns me link from object in array.
Then I want to delete this element, but don't know how to correct code it.
public void deleteEvent(Date date){
findEvent(date) = null; //???????????
Event[] list = new Event[events.length - 1];
int j = 0;
for (int i = 0; i < events.length ; i++) {
if(events[i] != null){
list[j] = events[i];
j++;
}
}
}
Use the found event to compare against, if no event was found for the date then just return with nothing changed.
public void deleteEvent(Date date){
Event foundEvent = findEvent(date);
if (foundEvent == null) {
return;
}
Event[] list = new Event[events.length - 1];
int j = 0;
for (int i = 0; i < events.length ; i++) {
if(!events[i].getDate().equals(foundEvent.getDate())) {
list[j] = events[I];
j++;
}
}
events = list;
}
You can't assign a value to a method return value.
While, yes, you logically want to "set the found date to null", you will need to actually do that within the loop
And instead of setting it to null, you could skip over its index and not copy it into the new list
public void deleteEvent(Date date){
Event[] list = new Event[events.length - 1];
int j = 0;
for (int i = 0; i < events.length ; i++) {
if(events[i] != null){
if (events[i].getDate().equals(date)) continue; // skip the event to delete
list[j] = events[i];
j++;
}
}
events = list; // reassign the new events
}
Note: this doesn't work if multiple events are on the same date
Alternatively, make the find method return an index
public int findEvent(Date date){
for (int i = 0; i < events.length ; i++) {
if(events[i].getDate().equals(date)){
return i;
}
}
return -1;
}
From which you can delete
int indexToRemove = findEvent(date);
if (indexToRemove > 0) {
events[indexToRemove] = null;
// copy these events to new list to remove nulls
}
If you're not required to use arrays, you should be using an Arraylist and making your Event objects as Comparable types
I don't think this question is very complicated to an experienced programmer, but I'm pretty new to it so I'm struggling.
I have a list of delimiters declared before a java class as such:
public static final String DELIMITERS = ",<.>/?;:'\"[{]}\\|=+-_)(*&^%$##!`~ \t\n";
I'd like to create a method that takes two parameters (a starting index and a string). The goal is to read through the string and return the next index that corresponds to a character NOT in the list of delimiters given above. If the starting index is a negative number or greater than the length of the text, the method should simply return -1. Otherwise it just returns the index of the next character NOT in the delimiter list.
This is what I have so far:
public static boolean isDelimiter(char c) {
String letter = "" + c;
if(DELIMITERS.contains(letter)){
return true;
}
else{
return false;
}
}
public static int posNextWord(int startPosition, String text) {
boolean isWord = false;
int nextWordPosition = 0;
if(startPosition < 0 || startPosition > (text.length()-1)){
return -1;
}
else{
while(isWord = false) {
for (int i = startPosition; i < text.length(); i++) {
if(!isDelimiter(text.charAt(i))){
nextWordPosition = nextWordPosition + i + startPosition;
isWord = true;
}
else{
isWord = false;
}
}
}
return nextWordPosition;
}
}
}
When I run this program with a sample text and index, however, the method just returns the number 0. Any help at all would be much appreciated. Also, the method isDelimiter is required for use in the posNextWord() method.
This entire block of code is the problem:
while(isWord = false) {
for (int i = startPosition; i < text.length(); i++) {
if(!isDelimiter(text.charAt(i))){
nextWordPosition = nextWordPosition + i + startPosition;
isWord = true;
}
else{
isWord = false;
}
}
}
return nextWordPosition;
First of all, you only need one loop to check each character of your loop. You don't need a while and a for. Second, if you want to find the first non-matching char, you can just return when you find it.
Like this:
for (int i = startPosition; i < text.length(); i++) {
if(!isDelimiter(text.charAt(i))){
return i + startPosition;
}
}
return -1;
See documented comments. Don't hesitate to ask if it is not clear :
public static boolean isDelimiter(char c) {
String letter = "" + c;
if(DELIMITERS.contains(letter)){
return true;
}
//else{ this else is not needed
System.out.println(letter +" is not a delimiter");
return false;
//}
}
public static int posNextWord(int startPosition, String text) {
//boolean isWord = false; not used
int nextWordPosition = 0;
if((startPosition < 0) || (startPosition > (text.length()-1))){
return -1;
}
//else{ this is not needed
//while(isWord = false) {
for (int i = startPosition; i < text.length(); i++) {
if(!isDelimiter(text.charAt(i))){
nextWordPosition = nextWordPosition + i + startPosition;
//isWord = true;
return nextWordPosition; //as Scary Wombat commented
}
//else{
// isWord = false;
//}
}
//isWord = false;
//}
return nextWordPosition;
// }
}
BTW: I don't think it is a good idea to return 0 as "not found" result. 0 may be returned also as valid "found" position.
I know this problem is probably best served with DP, but I was wondering if it was possible to do it with recursion as a brute force way.
Given a set of words, say {"sales", "person", "salesperson"}, determine which words are compound (that is, it is the combination of 2 or more words in the list). So in this case, salesperson = sales + person, and is compound.
I based my answer heavily off of this problem: http://www.geeksforgeeks.org/dynamic-programming-set-32-word-break-problem/
public static void main(String args[]) throws Exception {
String[] test = { "salesperson", "sales", "person" };
String[] output = simpleWords(test);
for (int i = 0; i < output.length; i++)
System.out.println(output[i]);
}
static String[] simpleWords(String[] words) {
if (words == null || words.length == 0)
return null;
ArrayList<String> simpleWords = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
String word = words[i];
Boolean isCompoundWord = breakWords(words, word);
if (!isCompoundWord)
simpleWords.add(word);
}
String[] retVal = new String[simpleWords.size()];
for (int i = 0; i < simpleWords.size(); i++)
retVal[i] = simpleWords.get(i);
return retVal;
}
static boolean breakWords(String[] words, String word) {
int size = word.length();
if (size == 0 ) return true;
for (int j = 1; j <= size; j++) {
if (compareWords(words, word.substring(0, j)) && breakWords(words, word.substring(j, word.length()))) {
return true;
}
}
return false;
}
static boolean compareWords(String[] words, String word) {
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word))
return true;
}
return false;
}
The problem here is now that while it successfully identifies salesperson as a compound word, it will also identify sales and person as a compound word. Can this code be revised so that this recursive solution works? I'm having trouble coming up with how I can easily do this.
Here is a solution with recursivity
public static String[] simpleWords(String[] data) {
List<String> list = new ArrayList<>();
for (String word : data) {
if (!isCompound(data, word)) {
list.add(word);
}
}
return list.toArray(new String[list.size()]);
}
public static boolean isCompound(String[] data, String word) {
return isCompound(data, word, 0);
}
public static boolean isCompound(String[] data, String word, int iteration) {
if (data == null || word == null || word.trim().isEmpty()) {
return false;
}
for (String str : data) {
if (str.equals(word) && iteration > 0) {
return true;
}
if (word.startsWith(str)) {
String subword = word.substring(str.length());
if (isCompound(data, subword, iteration + 1)) {
return true;
}
}
}
return false;
}
Just call it like this:
String[] data = {"sales", "person", "salesperson"};
System.out.println(Arrays.asList(simpleWords(data)));
I having a hard time getting the right output because i dont know how boolean exactly works inside a method. I have an arraylist and I'm check for any duplicates in the arraylist Here's my code
public void rentOneInstrument(List<Instrument> instrumentList){
String a="";
String b="";
boolean found = false;
for (int j = 0; j < instrumentList.size(); j++) {
a ="";
a = instrumentList.get(j).getName();
for (int i = j+1; i < instrumentList.size(); i++) {
b = instrumentList.get(i).getName();
System.out.println("a" + a + " b" + b);
if(a.equals(b)){
found = true;
}else {
found = false;
}
}
}
if (found) {
System.out.println("duplicate");
}else{
System.out.println("no duplicate");
}
}
Here is my output
a Cymbals b Drums,..
a Cymbals b Cello,..
a Cymbals b Cymbals,..
a Drums b Cello,..
a Drums b Cymbals,..
a Cello b Cymbals
no duplicate // prints no duplicate when there is clearly a duplicate in the output. How can i correct this?
Edit.. Btw I just a want a single out put that prints whether it found a duplicate or not inside the loop
if(a.equals(b)){
found = true
}else {
found = false;
}
This is your problem. This way only the last iteration of your loop will be stored in found. Since you are initializing it as false you don't need to set it to that again here.
for (int i = j+1; i < instrumentList.size(); i++) {
b = instrumentList.get(i).getName();
System.out.println("temp1 " + a + " temp2 " + b);
if(a.equals(b)){
found = true;
}
}
Alternatively, you can use a break statement when you have found a match to get out of the loop like so:
if(a.equals(b)){
found = true;
break;
}else {
found = false;
}
This way, found will be true and no other iterations will be performed, continuing after the end of the loop instead.
Let found be false by default. and just set it true if any duplicate is found.
if(a.equals(b)){
found = true;
}else {
// found = false;
// don't do this otherwise it will override previous `found` value
}
Consider the following input :
a,b,c,a,d
Now whit your code it would be false as d is not repeated. It would over right the value for a that is repeated. Also once a element is fond that it is replanted you don't need to go through the entire loop of all elements hence there is a break.
public void rentOneInstrument(List<Instrument> instrumentList){
String a="";
String b="";
boolean found = false;
for (int j = 0; j < instrumentList.size(); j++) {
a ="";
a = instrumentList.get(j).getName();
if(found) { break; } // Changed line here
for (int i = j+1; i < instrumentList.size(); i++) {
b = instrumentList.get(i).getName();
System.out.println("temp1 " + a + " temp2 " + b);
if(a.equals(b)){
found = true;
break; // Changed line here
}
}
}
if (found) {
System.out.println("duplicate");
}else{
System.out.println("no duplicate");
}
}
Another way of doing it without a break would be
public void rentOneInstrument(List<Instrument> instrumentList){
String a="";
String b="";
boolean found = false;
for (int j = 0; j < instrumentList.size() && !found; j++) {
a ="";
a = instrumentList.get(j).getName();
for (int i = j+1; i < instrumentList.size() && !found; i++) { // Changed for condition to look at the found variable too.
b = instrumentList.get(i).getName();
System.out.println("temp1 " + a + " temp2 " + b);
if(a.equals(b)){
found = true;
}
}
}
if (found) {
System.out.println("duplicate");
}else{
System.out.println("no duplicate");
}
}
A much better way of doing this would be using sets that doesn't contain duplicates.
public void rentOneInstrument(List<Instrument> instrumentList){
Set< Instrument > instrumentSet = new HashSet< Instrument >(instrumentList);
if(instrumentList.size()== instrumentSet.size()) {
System.out.println("no duplicate");
} else {
System.out.println("duplicate");
}
}
public void rentOneInstrument(List<Instrument> instrumentList){
boolean found=false;
List<String> listString=new ArrayList<String>();
for (Instrument inst: instrumentList){
if(listString.contains(inst.getName())){
found=true;
}
else{
listString.add(inst.getName());
}
}
if (found) {
System.out.println("duplicate");
}else{
System.out.println("no duplicate");
}
}
(Full disclosure: this is for some homework I can't seem to figure out.)
The task: Identify duplicates in a list and add them to another ArrayList to be printed out.
Specifications: I am NOT allowed to use any collection other than an ArrayList, so I can't use something like a Set. It seems like every answer on StackOverflow recommends use of a Set, which is why I decided to ask this question.
What I've attempted so far:
public static void deleteDuplicates(List<String> list)
{
int pointer = 1;
List<String> duplicates = new ArrayList<String>();
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i).equals(list.get(pointer))) {
duplicates.add(list.get(i));
if (pointer == 1) {
duplicates.add(list.get(pointer));
} else if ((pointer + 1) == list.size() - 1) {
duplicates.add(list.get(pointer));
}
pointer++;
} else {
display(duplicates);
duplicates = new ArrayList<String>();
pointer++;
}
}
}
The test data:
List<String> duplicated = new ArrayList<String>();
duplicated.add("3");
duplicated.add("3");
duplicated.add("30");
duplicated.add("46");
duplicated.add("46");
What's not working: When the size of the list is an odd number, the duplicates report correctly. When the size of the list is an even number, only the first two duplicates are reported.
The problem with your approach was the loop exits before it do the if-else check for last element. On the last iteration the if condition satisfies and it adds to duplicates but it wont enter the for loop again to goto the else part. So it does'nt get dispalyed. Try
public static void deleteDuplicates(List<String> list)
{
int pointer = 1;
List<String> duplicates = new ArrayList<String>();
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i).equals(list.get(pointer))) {
duplicates.add(list.get(i));
if (pointer == 1) {
duplicates.add(list.get(pointer));
} else if ((pointer + 1) == list.size() - 1) {
duplicates.add(list.get(pointer));
}
pointer++;
} else if(duplicates.size() > 0) {
display(duplicates);
duplicates.clear();
pointer++;
}
}
if(duplicates.size() > 0){
display(duplicates);
}
}
Although Syam S answer is right but this will work for unsorted array too:
public static void deleteDuplicates(List<String> list)
{
List<String> duplicates = new ArrayList<String>();
for (int j = 0; j < list.size() - 2; j++) {
int pointer = j;
for (int i = j+1; i < list.size() - 1; i++) {
if (list.get(i).equals(list.get(j))) {
duplicates.add(list.get(i));
duplicates.add(list.get(j));
}
if(duplicates.size() > 0){
System.out.println(duplicates);
duplicates.clear();
}
}
}
}
you can see the working version in Ideone
Try this:
Extending the ArrayList
1)
boolean result = false;
if(!contains(object))
result= super.add(object);
return result;
OR
2)
ArrayList<String> myList = new ArrayList<String>()
{
#Override
public boolean add(String object)
{
boolean present = false;
boolean result = false;
for(int i=0;i<size();i++)
{
if(object.equals(get(i)))
{
present = true;
break;
}
}
if(!present)
result= super.add(object);
return result;
}
};
myList.add("1");
myList.add("2");
myList.add("3");
myList.add("1");
myList.add("2");
myList.add("3");
myList.add("1");
myList.add("1");
System.out.println(myList);