Dynamically store objects in an unallocated object in java - java

I am stuck in a problem where i have to allocate string objects in an array of strings But the problem is i don't know how many string objects i will be putting in this array.
CODE
static String[] decipheredMessage;
static int pointer=0;
// in another function i have this code
if(sentenceFormationFlag==true) {
// System.out.println(" " + word); // prints the words after sentence formation
// add the words to an array of strings
decipheredMessage[pointer] = new String();
decipheredMessage[pointer++] = word;
return true;
What i have done here is i have declared an array of strings and since i don't know how many strings my array is going to contain i dynamically create string objects and assign it to the array.
ERROR
$ java SentenceFormation
arms
Exception in thread "main" java.lang.NullPointerException
at SentenceFormation.makeSentence(SentenceFormation.java:48)
at SentenceFormation.makeSentence(SentenceFormation.java:44)
at SentenceFormation.makeSentence(SentenceFormation.java:44)
at SentenceFormation.main(SentenceFormation.java:16)
I don't know why i am getting this problem can anybody help me with this.
Thanks in advance.

Dynamic arrays do not work in Java. You need to use one of the fine examples of the collections framework. Import java.util.ArrayList.
static ArrayList<String> decipheredMessage=new ArrayList<>();;
static int pointer=0;
// in another function i have this code
if(sentenceFormationFlag==true) {
// System.out.println(" " + word); // prints the words after sentence formation
// add the words to an array of strings
decipheredMessage.add(new String());
decipheredMessage.add(word);
return true;

You can use a List implementation like ArrayList if you don't know how many elements your array will have.
static List<String> decipheredMessage = new ArrayList<>();
...
decipheredMessage.add("my new string");
Check out the List documentation (linked above) to see what APIs are available.
If you are using Java 5 or 6, you'll need to specify the type in the angled brackets above, i.e. new ArrayList<String>().

Try something like this, and read about List
List<String> decipheredMessage = new ArrayList<String>();
static int pointer=0;
// in another function i have this code
if(sentenceFormationFlag==true) {
// System.out.println(" " + word); // prints the words after sentence formation
// add the words to an array of strings
decipheredMessage. add("string1");
decipheredMessage.add("string2");
return true;

Related

How to find the number of unique words in array list

So I am trying to create an for loop to find unique elements in a ArrayList.
I already have a ArrayList stored with user input of 20 places (repeats are allowed) but I am stuck on how to count the number of different places inputted in the list excluding duplicates. (i would like to avoid using hash)
Input:
[park, park, sea, beach, town]
Output:
[Number of unique places = 4]
Heres a rough example of the code I'm trying to make:
public static void main(String[] args) {
ArrayList<City> place = new ArrayList();
Scanner sc = new Scanner(System.in);
for(...) { // this is just to receive 20 inputs from users using the scanner
...
}
# This is where i am lost on creating a for loop...
}
you can use a Set for that.
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Store the list data to the Set.Set will not have duplicates in it, so the size of set will be the elements without duplicates.
use this method to get the set size.
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#size()
Sample Code.
List<String> citiesWithDuplicates =
Arrays.asList(new String[] {"park", "park", "sea", "beach", "town"});
Set<String> cities = new HashSet<>(citiesWithDuplicates);
System.out.println("Number of unique places = " + cities.size());
If you are able to use Java 8, you can use the distinct method of Java streams:
int numOfUniquePlaces = list.stream().distinct().count();
Otherwise, using a set is the easiest solution. Since you don't want to use "hash", use a TreeSet (although HashSet is in most cases the better solution). If that is not an option either, you'll have to manually check for each element whether it's a duplicate or not.
One way that comes to mind (without using Set or hashvalues) is to make a second list.
ArrayList<City> places = new ArrayList<>();
//Fill array
ArrayList<String> uniquePlaces = new ArrayList<>();
for (City city : places){
if (!uniquePlaces.contains(city.getPlace())){
uniquePlaces.add(city.getPlace());
}
}
//number of unique places:
int uniqueCount = uniquePlaces.size();
Note that this is not super efficient =D
If you do not want to use implementations of Set or Map interfaces (that would solve you problem with one line of code) and you want to stuck with ArrayList, I suggest use something like Collections.sort() method. It will sort you elements. Then iterate through the sorted array and compare and count duplicates. This trick can make solving your iteration problem easier.
Anyway, I strongly recommend using one of the implementations of Set interface.
Use following answer. This will add last duplicate element in distinct list if there are multiple duplicate elements.
List<String> citiesWithDuplicates = Arrays.asList(new String[] {
"park", "park", "sea", "beach", "town", "park", "beach" });
List<String> distinctCities = new ArrayList<String>();
int currentIndex = 0;
for (String city : citiesWithDuplicates) {
int index = citiesWithDuplicates.lastIndexOf(city);
if (index == currentIndex) {
distinctCities.add(city);
}
currentIndex++;
}
System.out.println("[ Number of unique places = "
+ distinctCities.size() + "]");
Well if you do not want to use any HashSets or similar options, a quick and dirty nested for-loop like this for example does the trick (it is just slow as hell if you have a lot of items (20 would be just fine)):
int differentCount=0;
for(City city1 : place){
boolean same=false;
for(City city2 : place){
if(city1.equals(city2)){
same=true;
break;
}
}
if(!same)
differentCount++;
}
System.out.printf("Number of unique places = %d\n",differentCount);

How to add to an array in java, and then print out using for loop? [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
So in the beginning, I just had this code to add to my array:
public void getMyArray()
{
myArray[0] = ("String1");
myArray[1] = ("String2");
}
But I kept getting a null pointer exception whenever I called it, and I wasn't sure why. So I changed my code to this:
public void getMyArray()
{
String [] myArray = {"String1", "String2"};
System.out.println(myArray);
}
And now I get what seems to be the address when printing:
[Ljava.lang.String;#1ca6218
You can use Arrays.toString() like this:
System.out.println(Arrays.toString(myArray));
Replacing it in your code:
public void getMyArray()
{
String [] myArray = {"String1", "String2"};
System.out.println(Arrays.toString(myArray));
}
The output will be:
[String1, String2]
The toString() method for an array will not print out all objects in an array in java, unless you want to override it and make your own implementation. What is printing is a description of the array object.
To print all elements in the array you would do something like:
for(String myArray1 : myArray) {
System.out.println(myArray1);
}
Also, the size of an array in java is fixed at instantiation. Whatever amount of memory you allocate for the array is there to stay. If you want to change the size, look into ArrayLists or LinkedLists and other structures. Hope this helps.
i imagine that you are not initializing youre array anywhere, using something like
myArray = new String[2];
But, besides that, the second option you have there is printing that because its actually printing the objects string encoding for a String array. instead, you will have to loop through each element and print it inidividually
for(int i = 0; i < myArray.length; i++)
{
System.out.println(myArray[i]);
}
The reason you get [Ljava.lang.String;#1ca6218 on output is because an object's default string representation is its bytecode representation in the JVM.
Since there is no way in the Java language to override array's toString(), you can create a utility method to make a more appropriate string.
Here is an example for you:
public static String arrayToString(String[] array) {
StringBuilder builder = new StringBuilder();
for (String s : array) builder.append(s).append(" ");
String result = builder.toString();
return result.substring(0, result.length() - 1);
}
You can also use Java's built-in array to string via the Arrays utility class:
Arrays.toString(myArray)
The reason you get a null pointer or index out of bounds is because your array variable reference is either null or not to an appropriately sized array.
In your problem, you will need an array of 2 elements, thus new String[2]
You can then use normal assignment and it should work, along with the above method to print out the string.
String[] myArray = new String[2];
myArray[0] = "Hello";
myArray[1] = "there.";
System.out.println(Arrays.toString(myArray));
Use java.util.Arrays#toString
System.out.println(Arrays.toString(myArray));

Android randomize strings without repetition

I'm doing a simple random quiz app in Android. So basically I have string array of words. I need to display the string without repetition. This is what I've tried so far:
String[] words = { "Welcome", "Different", "Teenager", "Transfer", "Italian",
"Timber", "Toxic", "Illiterate", "Irate", "Moderate", "Transportation", "Attention" };
ArrayList<String> wordlist = new ArrayList<String>();
for (String i : words)
wordlist.add(i);
Collections.shuffle(wordlist);
randomStr = words[new Random().nextInt(words.length)];
tvWord.setText("");
tvWord.setText(randomStr);
But I still get the random word repeating. What am I doing wrong in here? Any ideas? I would gladly appreciate your help. Thanks.
Update:
First on a button click the word should then display. And many times I click the button I keep getting the same word again.
switch(v.getId()){
case R.id.btPlay:
randomWordList();
break;
}
Where randomWordList(); is the method I posted above.
You don't keep track of what was already used. I also don't understand why you define wordlist and then don't use it. Just a small modification of your code will do the trick.
Edit: You also need to initialize values in different scope than where you use it. For example like this:
public class MyClass{
LinkedList<String> wordlist;
public MyClass(){
String[] words = { "Welcome", "Different", "Teenager", "Transfer", "Italian",
"Timber", "Toxic", "Illiterate", "Irate", "Moderate", "Transportation", "Attention" };
wordlist = new LinkedList<String>();
for (String i : words)
wordlist.add(i);
Collections.shuffle(wordlist);
}
public void useNextWord(){
tvWord.setText("");
tvWord.setText(wordlist.pollLast());
}
Create a new list of Strings and shuffle it. Then simply iterate over the shuffled list from the beginning.
ArrayList<String> copyOfWords= new ArrayList<String>(words);
Collections.shuffle(copyOfWords);
This is taken from here.
Time complexity is O(n).
To iterate over the List you can either get the first element and remove it (with the same method) or keep track which was the last used element.
First solution:
String randomWord = copyOfWords.remove(0);
tvWord.setText(randomWord);
P.S. do not use this line in your code randomStr = words[new Random().nextInt(words.length)];
You will need to either keep track of the Strings you have already used in another array or list and check the value has not already been used or alternatively remove any used Strings from the pool. You can do that with String next = List.remove(index).
You first shuffle your list with Collections.shuffle(wordlist); and then access the list with a random index. There's no need to use a random index if the list is already shuffled. Just get one item after another. You could use wordlist.remove(0) until your list is empty.
Display the next string as follows:
if (!wordlist.isEmpty()) {
randomStr = wordlist.remove(0);
tvWord.setText(randomStr);
}

I have a bunch of words (strings?) in an ArrayList and I'd like to know if I can find the size of each element?

So like the title says: I have a bunch of words in an ArrayList and I want to know how I can get the size of each element in the ArrayList. For example:
ArrayList input = new Arraylist();
input = {"Hello", "Goodbye", "Segall", "Ty"};
Id like to know if there is a way to find out the length of the first element which, in this case, would be "Hello". I had something in mind like:
input(0).size();
That obviously doesn't work.
I also tried setting up variable for it like this:
String variable = input.get(0);
variable.length() or variable.size();
But turns out-- input is an object and variable is expecting a string type.
I am a beginner to this so if this stupidly easy question I apologize!
Either typecast your object coming from the list like this(String)input.get(0);
or make your array list declaration like this
ArrayList<String> input = new ArrayList<String>(); // Preferred way.
So that you don't need a cast.
And finally you can call variable.length() to get the length.
For one thing, you don't specify that it is an array list of String. When declaring the array list, you want to use
ArrayList<String> input = new ArrayList<String>();
Then for each element you want to add, use
input.add("myString");
Check this-
final List<String> input = new ArrayList<String>() {
{
add("Hello");
add("Goodbye");
add("Segall");
add("Ty");
}
};
for(String word : input) {
System.out.println(word + " --> " + word.length());
}

How do I make an ArrayList of ArrayLists from an ArrayList by using a function that makes ArrayLists in an ArrayList from Strings of an ArrayList [duplicate]

This question already has answers here:
Looping in ArrayLists with a Method
(3 answers)
Closed 9 years ago.
I have a java program that
reads a text file,
puts all it's words in an ArrayList
puts all the words into an ArrayList, lowercase with punctuation removed
I now want to make two more things.
A function that creates all the anagrams of the strings of a String ArrayList,
an ArrayList of ArrayLists that will store each of the anagrams and the original string into each ArrayList in the ArrayList.
So I want to develop a function that will take a string that I am inserting from one ArrayList into a new ArrayList and make all it's anagrams and put them in an ArrayList and then put that ArrayList in the ArrayList that is reading the old ArrayList.
Something that will look like this:
List<String> arLists = new ArrayList<String>(); //makes new array list
for(String arList : words) //takes values from old array list
ArrayList<String> anaLists = new ArrayList<String>(); //makes a new array list
arLists.add(anag(anaLists,arList,"")); //uses a function that makes an
I want to make a function kinda like this, but what I have made here... doesn't really work.
public void anag(ArrayList<String> anaLists, String s1, String s2){
if(s1.length() == 0){
return anaLists;
}
for(int i = 0 ; i < s1.length() ; i++){ //only runs for string length
String anaList = anag(s1.substring(0, i) + s1.substring(i+1, s1.length()), s1.charAt(i) + s2);
anaLists.add(anaList);
}
}
Some guidance on this would be superb.
To make all anagrams from a string, follow the following steps:
Step 1: Use String's replace to remove whitespace, and make sure all punctuation and capitalization has been removed.
Step 2: Write this function f(string s, string anagram, ArrayList<String> array) and call it with s = yourstring, anagram = "", array = new ArrayList<String>():
If s is empty, add anagram to array and return
For each letter l in s:
newanagram = anagram + l
news = s with l taken out of it (e.g. make a substring of everything before l in s and everything after l in s, and concatenate them together)
call f(news, anagram, array)
This will explore a 'tree' of recursive self calls, and at each 'leaf' of the 'tree' each possible permutation of all the letters will be added to the array. When it finishes, n*n-1*n-2*n-3... aka n factorial entries will be in the array, which is how you know you're on the right track :)
And if you need an anagram of every string in an arraylist, just call it in a for loop.
After some struggle, I have tried to understand your question and here's my answer. Correct me if I am wrong. First of all, you can do all that pre-processing stuff like changing case, removing grammar using one array list. Now to the actual function:
public void getAnag(String baseStr, ArrayList<String> finalAnagList)
{
ArrayList<String> anagList = new ArrayList<String>();
anagList = getAnagrams(baseStr); // getAnagrams is a support function to get the anagrams
anagList.add(baseStr); // I suppose you want to add the base string also to the anagrams list
finalAnagList.add(anagList);
}
And your calling function in program would be:
public void testAnagrams()
{
ArrayList<String> words = getWordsFromFile("/home/list.txt"); // gets the words from the file
ArrayList<String> anagramsList = new ArrayList<String>();
foreach(String word : words)
{
getAnag(word, anagramsList);
}
}

Categories