I need to get all the index numbers were in i will get a match of the keyword 'Articles' & also i want the counter 'indexoccurencecounter' to increment only if i get a match.
List<String> valueslist = new ArrayList<String>();
valueslist.add("Articles");
valueslist.add("Vals");
valueslist.add("Articles");
valueslist.add("Toast");
String key="Articles";
System.out.println("List contents having values are: "+valueslist);
int ind=0;
int indexoccurencecounter=0;
for (int i=0;i<valueslist.size();i++){
ind=valueslist.indexOf(key);
if (ind>=0){
indexoccurencecounter++;
}
}
System.out.println("Index's of the key "+key+" is: "+ind);
System.out.println("The key specified appears "+indexoccurencecounter+" times in the result links");
My above code is giving me incorrect output, i am expecting the output to be like below:
List contents having values are: [Articles, Vals, Articles, Toast]
Index's of the key Articles is: 0,2
The key specified appears 2 times in the result links
Because multiple indexes will match, int ind cannot keep track of them all. It could only keep track of one. I suggest you create a List<Integer> of indices. A useful side-effect of doing that is that you no longer have to count the occurrences—you can simply use the size() method of the list.
List<String> values = new ArrayList<>();
values.add("Articles");
values.add("Vals");
values.add("Articles");
values.add("Toast");
String searchTerm = "Articles";
List<Integer> matchingIndices = new ArrayList<>();
for (int i = 0; i < values.size(); i++) {
String candidate = values.get(i);
if (candidate.indexOf(searchTerm) >= 0) {
matchingIndices.add(i);
}
}
int numberOfMatches = matchingIndices.size();
System.out.println("Values: " + values);
System.out.println("Indexes of the key '" + searchTerm + "': " + matchingIndices);
System.out.println("The key appears " + numberOfMatches + " times.");
Produces:
Values: [Articles, Vals, Articles, Toast]
Indexes of the key 'Articles': [0, 2]
The key appears 2 times.
Related
I have an array with several elements String[] names = {"Jeremy", "Aude", "David"};
I would like to use the method .substring() to extract the index 1 and 2 namely the elements Aude and David then I want to concatenate the element Jeremy also.
Here is the result that I want to get : Aude, David, Jeremy
Do you have an idea to manipualte the elements ?
Here is my code
ArrayList<String> myList = new ArrayList<>();
String[] names = {"Jeremy", "Aude", "David"};
String x = "";
for(int i = 0; i<names.length; i++){
myList.add(names[i]);
System.out.print(myList.get(i) + " ");
}
x = names.substring(1,2);
You could do it pretty much as described, first create a new array of the same length as names (since you want to keep all of the names, just rotate them). Next, copy every name with an offset of one from names to that second array. Finally, copy the first name to the last element in the second array (and print it). Like,
String[] names = { "Jeremy", "Aude", "David" };
String[] names2 = new String[names.length];
System.arraycopy(names, 1, names2, 0, names.length - 1);
names2[names2.length - 1] = names[0];
System.out.println(Arrays.toString(names2));
Outputs (as requested)
[Aude, David, Jeremy]
extract the index 1 and 2
names[1] and names[2]
element Jeremy also
names[0]
concatenate ... result that I want to get: Aude, David, Jeremy
String result = names[1] + ", " + names[2] + ", " + names[0];
would like to use the method .substring()
You can't, since that method is not for array manipulation.
Code
String[] names = {"Jeremy", "Aude", "David"};
String result = names[1] + ", " + names[2] + ", " + names[0];
System.out.println(result);
Output
Aude, David, Jeremy
I would not use .substring() to access the elements in an array. you can use their location in memory by getting them by their index.
ArrayList<String> myList = new ArrayList<>();
String[] names = {"Jeremy", "Aude", "David"};
String x = "";
for(int i = 0; i<names.length; i++){
myList.add(names[i]);
System.out.print(myList.get(i) + " ");
}
x = names[1] + ", " names[2] + ", " names[0];
.substring() is used to get elements in an String such as
`String x = "jeremy;
x = x.substring(0, 2);`
x will now equal to "jer"
I would also advise to use StringBuilder as it is mutable
The variable 'String [] names' is not an object of String but rather an object of the generic container class array, containing the object type String. This means that the method that you are trying to access is not usable due to being an array. You will have to make a new function that takes in the 2 parameters and returns a String.
public String subString(int index1,int index2)
{
if(names.length < index1 || names.length < index2)
{
return names[index1] + ", " + names[index2];
}
return "Index's not in array range";
}
Good Morning
I write a function that calculates for me the frequency of a term:
public static int tfCalculator(String[] totalterms, String termToCheck) {
int count = 0; //to count the overall occurrence of the term termToCheck
for (String s : totalterms) {
if (s.equalsIgnoreCase(termToCheck)) {
count++;
}
}
return count;
}
and after that I use it on the code below to calculate every word from a String[] words
for(String word:words){
int freq = tfCalculator(words, word);
System.out.println(word + "|" + freq);
mm+=word + "|" + freq+"\n";
}
well the problem that I have is that the words repeat here is for example the result:
cytoskeletal|2
network|1
enable|1
equal|1
spindle|1
cytoskeletal|2
...
...
so can someone help me to remove the repeated word and get as result like that:
cytoskeletal|2
network|1
enable|1
equal|1
spindle|1
...
...
Thank you very much!
Java 8 solution
words = Arrays.stream(words).distinct().toArray(String[]::new);
the distinct method removes duplicates. words is replaced with a new array without duplicates
I think here you want to print the frequency of each string in the array totalterms . I think using Map is a easier solution as in the single traversal of the array it will store the frequency of all the strings Check the following implementation.
public static void printFrequency(String[] totalterms)
{
Map frequencyMap = new HashMap<String, Integer>();
for (String string : totalterms) {
if(frequencyMap.containsKey(string))
{
Integer count = (Integer)frequencyMap.get(string);
frequencyMap.put(string, count+1);
}
else
{
frequencyMap.put(string, 1);
}
}
Set <Entry<String, Integer>> elements= frequencyMap.entrySet();
for (Entry<String, Integer> entry : elements) {
System.out.println(entry.getKey()+"|"+entry.getValue());
}
}
You can just use a HashSet and that should take care of the duplicates issue:
words = new HashSet<String>(Arrays.asList(words)).toArray(new String[0]);
This will take your array, convert it to a List, feed that to the constructor of HashSet<String>, and then convert it back to an array for you.
Sort the array, then you can just count equal adjacent elements:
Arrays.sort(totalterms);
int i = 0;
while (i < totalterms.length) {
int start = i;
while (i < totalterms.length && totalterms[i].equals(totalterms[start])) {
++i;
}
System.out.println(totalterms[start] + "|" + (i - start));
}
in two line :
String s = "cytoskeletal|2 - network|1 - enable|1 - equal|1 - spindle|1 - cytoskeletal|2";
System.out.println(new LinkedHashSet(Arrays.asList(s.split("-"))).toString().replaceAll("(^\[|\]$)", "").replace(", ", "- "));
Your code is fine, you just need keep track of which words were encountered already. For that you can keep a running set:
Set<String> prevWords = new HashSet<>();
for(String word:words){
// proceed if word is new to the set, otherwise skip
if (prevWords.add(word)) {
int freq = tfCalculator(words, word);
System.out.println(word + "|" + freq);
mm+=word + "|" + freq+"\n";
}
}
I am adding data into HashMap where node is an object with variables index and successor.
private static HashMap <Integer, node> peerList = new HashMap<Integer, node>();
public void generateFingerTable (int node_position) {
chordSize = chord.initChordSize;
chord chord = new chord();
//create new node and add to map
node newPeer = new node();
peerList.put(node_position, newPeer);
for (int i=0; i<chordSize; i++) {
int temp = i+1;
newPeer.index = new int [chordSize];
newPeer.successor = new int [chordSize];
int temp1 = node_position + (int)Math.pow(2, temp-1) % chord.getChordSize();
peerList.get(node_position).index[i] = temp;
peerList.get(node_position).successor[i] = temp1;
System.out.println ("Index: " + newPeer.index[i] + "\n" + "Successor: " +
newPeer.successor[i]);
}
}
public void printFingerTable() {
for (Map.Entry<Integer, node> m : peerList.entrySet()) {
System.out.println ("Peer " + m.getKey() + " with Index: " + m.getValue().getIndex() + " Successor: " +
m.getValue().getSuccessor());
}
When I print the Hash details, the result shows Index: [0,0,0,0,5] , Successor:[0,0,0,0,16] which means the previously added elements gets replaced and only the last element is saved in Hashmap.
The intended result should be Index [1,2,3,4,5], Successor: [1,2,4,8,16].
How can I amend this so the data don't get replaced?
You initialize the index and successor arrays in each iteration of the loop, so only the value of the last index remains in the end, and the others are 0.
You should initialize the arrays before the loop.
Change the code to :
public void generateFingerTable (int node_position) {
chordSize = chord.initChordSize;
chord chord = new chord();
//create new node and add to map
node newPeer = new node();
peerList.put(node_position, newPeer);
newPeer.index = new int [chordSize];
newPeer.successor = new int [chordSize];
for (int i=0; i<chordSize; i++) {
int temp = i+1;
int temp1 = node_position + (int)Math.pow(2, temp-1) % chord.getChordSize();
peerList.get(node_position).index[i] = temp;
peerList.get(node_position).successor[i] = temp1;
System.out.println ("Index: " + newPeer.index[i] + "\n" + "Successor: " +
newPeer.successor[i]);
}
}
I think you should use a different data-type or structure than HashMap as HashMaps do not guarantee order. I am pointing this out as your code peerList.put(node_position, newPeer); seems to imply you are setting the position of your object in your HashMap but that is not the case. I only say this because you are just using the variable called node_postion to key or hash where your data object will live in your HashMap. See this link for more details.
Difference between HashMap, LinkedHashMap and TreeMap
I am trying to make an Array that starts at an initial size, can have entries added to it. (I have to use an Array). To print the Array I have to following code :
public String printDirectory() {
int x = 0;
String print = String.format("%-15s" + "%-15s" + "%4s" + "\n", "Surname" , "Initials" , "Number");
// Sorts the array into alphabetical order
// Arrays.sort(Array);
while ( x < count ){
Scanner sc = new Scanner(Array[x]).useDelimiter("\\t");
secondName[x] = sc.next();
initials[x] = sc.next();
extension[x] = sc.next();
x++;
}
x = 0;
while ( x < count){
print += String.format("%-15s" + "%-15s" + "%4S" + "\n", secondName[x] , initials[x] , extension[x]);
x++;
}
return print + "" + Array.length;
}
Please ignore the extra Array.length, on the return statement.
Anyways this is working fine, firstly the Array reads a file which is formated like NameInitialsnumber on each line.
So I tried making a newEntry method and it causes problems when I want to print the Array. When I add a new entry, if the Array is too small, it will make the array bigger and add the entry. I made methods to make sure this worked and it does work. The following code for this method is:
public void newEntry(String surname, String in, String ext) {
if (count == Array.length) {
String entry = surname + "\t" + in + "\t" + ext;
int x = Array.length + 1;
String[] tempArray = new String[x];
System.arraycopy(Array, 0, tempArray, 0, Array.length);
Array = tempArray;
Array[count] = entry;
Arrays.sort(Array);
} else {
String entry = surname + "\t" + in + "\t" + ext;
Array[count] = entry;
Arrays.sort(Array);
}
count++;
}
The problem is when I then call the printDirectory method it has problems with sc.next(). The error message is as follows:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at ArrayDirectory.printDirectory(ArrayDirectory.java:106)
at ArrayDirectory.main(ArrayDirectory.java:165)
Im really new to coding and im not sure what is wrong. I know its something wrong with the new entry but im not sure what. Really grateful for any help. Thanks.
It seems that your other arrays secondName, initials, and extension are not large enough.
You need to make them bigger as well. Or even better, when you think a bit about it you will recognize that you do not need them at all.
i'm having trouble with a code. I have read words from a text file into a String array, removed the periods and commas. Now i need to check the number of occurrences of each word. I managed to do that as well. However, my output contains all the words in the file, and the occurrences.
Like this:
the 2
birds 2
are 1
going 2
north 2
north 2
Here is my code:
public static String counter(String[] wordList)
{
//String[] noRepeatString = null ;
//int[] countArr = null ;
for (int i = 0; i < wordList.length; i++)
{
int count = 1;
for(int j = 0; j < wordList.length; j++)
{
if(i != j) //to avoid comparing itself
{
if (wordList[i].compareTo(wordList[j]) == 0)
{
count++;
//noRepeatString[i] = wordList[i];
//countArr[i] = count;
}
}
}
System.out.println (wordList[i] + " " + count);
}
return null;
I need to figure out 1) to get the count value into an array.. 2) to delete the repetitions.
As seen in the commenting, i tried to use a countArr[] and a noRepeatString[], in hopes of doing that.. but i had a NullPointerException.
Any thought on this matter will be much appreciated :)
I would first convert the array into a list because they are easier to operate on than arrays.
List<String> list = Arrays.asList(wordsList);
Then you should create a copy of that list (you'll se in a second why):
ArrayList<String> listTwo = new ArrayList<String>(list);
Now you remove all the duplicates in the second list:
HashSet hs = new HashSet();
hs.addAll(listTwo);
listTwo.clear();
listTwo.addAll(hs);
Then you loop through the second list and get the frequency of that word in the first list. But first you should create another arrayList to store the results:
ArrayList<String> results = new ArrayList<String>;
for(String word : listTwo){
int count = Collections.frequency(list, word);
String result = word +": " count;
results.add(result);
}
Finally you can output the results list:
for(String freq : results){
System.out.println(freq);}
I have not tested this code (can't do that right now). Please ask if there is a problem or it doesnÄt work. See these questions for reference:
How do I remove repeated elements from ArrayList?
One-liner to count number of occurrences of String in a String[] in Java?
How do I clone a generic List in Java?
some syntax issues in your code but works fine
ArrayList<String> results = new ArrayList<String>();
for(String word : listTwo){
int count = Collections.frequency(list, word);
String result = word +": "+ count;
results.add(result);
}