the variable TEST is equal to this
lazar108#hotmail.com_Hd_s lazar108#hotmail.com_Update_on the lazar108#hotmail.com_Ksks_ajsj
i want to pull each "product" out so i have an ArrayList equal to this
lazar108#hotmail.com_Hd_s
lazar108#hotmail.com_Update_on
lazar108#hotmail.com_Ksks_ajsj
Right now the only thing in my array list is lazar108#hotmail.com_Hd_s
How can i pull each "product" from the one variable (TEST) in a loop and add it to the ArrayList?
My code so far:
String TEST = result;
ArrayList<String> Products = new ArrayList<>();
boolean flag = true;
while(flag == true){
Products.add(TEST.substring(0, TEST.indexOf(' ')));
TEST = TEST.substring(TEST.indexOf(' ') + 1);
if(TEST.equals("")){
flag = false;
}else{
TEST = TEST.substring(1);
}
}
Your one step away from doing it. After the first iteration of your while loop, you do retrieve lazar108#hotmail.com_Hd_s, but after that the loop runs infinitely because the other parts of the string are not being accessed. The solution is to cut out the part you retrieved from the string each time you add it to Products. I should also note that this will only work if TEST ends with a space " ". Here is a way to approach this.
String TEST = result;
ArrayList<String> Products = new ArrayList<>();
boolean flag = true;
while(flag == true){
Products.add(TEST.substring(0,TEST.indexOf(' ')));
TEST = TEST.substring(TEST.indexOf(' '));//cutting the last email added from the string
if(TEST.equals(" ")){
flag = false;
}
else{
TEST = TEST.substring(1); //remove that space so that it doesn't get
//counted again in the next iteration
}
}
Seeing your input string doesn't simply have email separated by white space, I suggest you use Pattern and Matcher. First you need to define the email's pattern (you can google it), then use the example in this : http://www.tutorialspoint.com/java/java_regular_expressions.htm
An alternative one line solution using String.split() function:
List<String> products = Arrays.asList(TEST.split(" "));
Related
I'm using a trie structure called a dictionary tree which I want to print all words from. When I insert a word when I reach the last letter in the word I store the completed word in Dictionary Tree.
private Map<Character, DictionaryTree> children = new LinkedHashMap<>();
private String completeWord;
void insertionHelper(String currentPortion, String fullWord){
if(currentPortion.length() == 1){
if(children.containsKey(currentPortion.charAt(0))){
// do nothing
}else{
this.children.put(currentPortion.charAt(0), new DictionaryTree());
}
this.completeWord = fullWord;
}else{
if(children.containsKey(currentPortion.charAt(0))){
children.get(currentPortion.charAt(0)).insertionHelper(currentPortion.substring(1), fullWord);
}else{
DictionaryTree a = new DictionaryTree();
a.insertionHelper(currentPortion.substring(1), fullWord);
children.put(currentPortion.charAt(0), a);
}
}
}
After this when Looking for all words I traverse every node and try to add the words to a static array List, however, for some reason many of the words are duplicated and others are missing.
String allWordHelper(){
String holder = " ";
for (Map.Entry<Character, DictionaryTree> child : children.entrySet()) {
if(completeWord != null){
//holder += completeWord + child.getValue().allWordHelper();
Word_Holder.allWords.add(completeWord);
}else{
holder += child.getValue().allWordHelper();
}
}
return holder;
}
I can't figure out why.
I have no idea what a DictionaryTree is and what your indata looks like but if you do
children.put(currentPortion.charAt(0), a);
doesn't that mean that whenever you get a words that starts with the same character as a previous word then the old word might be replaced by the new one?
It's quite impossible to fully understand your code with an unknown data type and all the recursive calls.
I am creating a program that lets you store 10 items in an array. What I haven't been able to get the program to do is give an error if one of the entered items already exists in the array.
So, for example, if the array looks like [banana, potato, 3, 4, yes, ...] and I enter banana again, it should say "Item has already been stored" and ask me to re-enter the value. The code I currently have is:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int stringNumber = 0;
String[] stringArray = new String[10];
for (int i = 0; i <= stringArray.length; i++) {
out.println("\nEnter a string");
String input = keyboard.next();
stringArray[stringNumber] = input;
out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored.");
PrintArray(stringArray);
stringNumber++;
You can use nested loops to go through the array to see if the new input exists. It would be better to do this in a function. Also when doing this you need to make sure that you are not at the first element or you will get a null pointer exception.
for (int i = 0; i <= stringArray.length; i++) {
boolean isInArray = false;
System.out.println("\nEnter a string");
String input = keyboard.next();
if (i > 0) {
for (int j = 0; j < stringArray.length; j++) {
if (stringArray[j].equalsIgnoreCase(input)) {
isInArray = true;
break;
}
}
}
if (!isInArray) {
stringArray[stringNumber] = input;
} else {
System.out.println("\"" + stringArray[stringNumber-1] + "\""
+ " has been stored.");
}
PrintArray(stringArray);
stringNumber++;
}
It's always better to use a HashSet when you don't want to store duplicates. Then use HashSet#contains() method to check if element is already there. If ordering is important, then use LinkedHashSet.
If you really want to use an array, you can write a utility method contains() for an array. Pass the array, and the value to search for.
public static boolean contains(String[] array, String value) {
// Iterate over the array using for loop
// For each string, check if it equals to value.
// Return true, if it is equal, else continue iteration
// After the iteration ends, directly return false.
}
For iterating over the array, check enhanced for statement.
For comparing String, use String#equals(Object) method.
When you got the String input, you can create a method that will :
Go through the entire array and check if the string is in it (you can use equals() to check content of Strings)
Returns a boolean value wheter the string is in the array or not
Then just add a while structure to re-ask for an input
Basically it can look like this :
String input = "";
do {
input = keyboard.next();
}while(!checkString(input))
The checkString method will just go through all the array(using a for loop as you did to add elements) and returns the appropriate boolean value.
Without introducing some order in your array and without using an addition structure for instance HashSet, you will have to look through the whole array and compare the new item to each of the items already present in the array.
For me the best solution is to have a helper HashSet to check the item for presence.
Also have a look at this question.
To avoid you should use an Set instead of an array and loop until size = 10.
If you need to keep an array, you can use the .contains() method to check if the item is already present in the array.
while (no input or duplicated){
ask for a new string
if (not duplicated) {
store the string in the array
break;
}
}
You should check the input value in array before inserting into it. You can write a method like exists which accepts String[] & String as input parameter, and find the string into the String array, if it finds the result then return true else false.
public boolean exists(String[] strs, String search){
for(String str : strs){
if(str.equals(search))
return true;
}
return false;
}
performance would be O(n) as it searchs linearly.
This loop breaks if uncomment 2 commented string, cannot figure out why it happens, help plz:
private static String findAll(String cell, ArrayList<String> hrange, ArrayList<String> vrange, List<String> cellrange, Integer cycle){
cellrange.add(cell);
String color = XldocReader.xlCells.get(cell);
String[] chkeys = cell.split("\\$");
String chLetter = chkeys[1];
Integer chNumber = Integer.parseInt(chkeys[2]);
boolean rcnext = false;
boolean rcprev = false;
Iterator<String> ite = hrange.iterator();
while ( ite.hasNext() ) {
String candidate = ite.next();
String value = XldocReader.xlCells.get(candidate);
String[] ckeys = candidate.split("\\$");
String cLetter = ckeys[1];
int n = getKeyByValue(chLetter);
String next = cell.replaceAll(chLetter+"", columns.get(n+1) +"");
String cnext = XldocReader.xlCells.get(next);
String prev = cell.replaceAll(chLetter+"", columns.get(n-1) +"");
String cprev = XldocReader.xlCells.get(prev);
//rcnext = cnext.equals(color);
//rcprev = cprev.equals(color);
...
}
return cellrange.toString();
}
it should find equals strings and run recursively check again but on first check it's breaks and nothing check more...
I would make the loop
for(String candidate : hrange) {
}
And I would step through the code in a debugger to see exactly what it is doing as I suspect you program isn't doing what you think it is.
What do you mean by breaks? What is the Exception and on which line does it occur? Does it match what you see in the debugger?
I suspect the problem is in the code you have labelled as ...
Can you give us more info? What the error is? How it breaks? etc. Also, print out the results of color and cnext, cprev right before it breaks.
My guess is those are not legit strings. And you are trying to run an equals method on something that is not a legit string.
What I'm trying to do here is to always get a random value from my String arraylist and to do this I'm using another arraylist containing the same amount of booleans as the strings.
When I need a random string I do this:
randomstring = r.nextInt(100);
String mystring = c.getAnswear(randomstring);
if(c.getAnswear(randomstring) == null){
randomstring = r.nextInt(100);
mystring = c.getAnswear(randomstring);
System.out.println("Random again!!!!!!!!!!!!!!!");
}
And this is how it looks inside c.getAnswear
List<String> strings = new ArrayList<String>();
strings.add("blablabla");
//And another 100 of theese
//Then we have theese boolean array
ArrayList<Boolean> trueornot = new ArrayList<Boolean>();
trueornot.add(false);
//Another 100 of them
//Then we have this
String Answear = null;
if(trueornot.get(indexNum).equals(true)){
Answear = null;
System.out.println(Answear);
System.out.println("Already used string random again!");
}
else if(trueornot.get(indexNum).equals(false)){
trueornot.add(indexNum, true);
Answear = strings.get(indexNum);
System.out.println(Answear);
System.out.println("Something in the array was set to true");
}
return Answear;
But when I try to do this can randomize my string how much I want and it prints to console something was set to true but I see many times the same string gets used again and the System.out.println("Already used string random again!"); never gets printed in the console
Same with when I call this getAnswear I have the if statement (c.getAnswear(randomstring) == null) the line inside there System.out.println("random again!!!!!!!"); never gets into the console.
How would I make it work? Seems like the answer string inside getAnswear is never null and that's strange because I'm setting the booleans to true.
trueornot.add(indexNum, true)
this adds the value to the list and shifts the previous value at that index down the list.
you should use trueornot.set(...) which replaces the value...
update:
And this is how it looks inside c.getAnswear
List<String> strings = new ArrayList<String>();
strings.add("blablabla");
//And another 100 of theese
//Then we have theese boolean array
ArrayList<Boolean> trueornot = new ArrayList<Boolean>();
trueornot.add(false);
//Another 100 of them
//Then we have this
if this actually happens every time getAnswer is called then you're recreating the strings and the boolean list everytime, all previous changes are lost.
strings and trueornot should be class fields and not local variables.
may it be, you want to set your value true, instead of insert it?
you do this:
trueornot.add(indexNum, true);
but to set a value you have to do this:
trueornot.set(indexNum, true);
When I use System.out.println to show the size of a vector after calling the following method then it shows 1 although it should show 2 because the String parameter is "7455573;photo41.png;photo42.png" .
private void getIdClientAndPhotonames(String csvClientPhotos)
{
Vector vListPhotosOfClient = new Vector();
String chainePhotos = "";
String photoName = "";
String photoDirectory = new String(csvClientPhotos.substring(0, csvClientPhotos.indexOf(';')));
chainePhotos = csvClientPhotos.substring(csvClientPhotos.indexOf(';')+1);
chainePhotos = chainePhotos.substring(0, chainePhotos.lastIndexOf(';'));
if (chainePhotos.indexOf(';') == -1)
{
vListPhotosOfClient.addElement(new String(chainePhotos));
}
else // aaa;bbb;...
{
for (int i = 0 ; i < chainePhotos.length() ; i++)
{
if (chainePhotos.charAt(i) == ';')
{
vListPhotosOfClient.addElement(new String(photoName));
photoName = "";
continue;
}
photoName = photoName.concat(String.valueOf(chainePhotos.charAt(i)));
}
}
}
So the vector should contain the two String photo41.png and photo42.png , but when I print the vector content I get only photo41.png.
So what is wrong in my code ?
The answer is not valid for this question anymore, because it has been retagged to java-me. Still true if it was Java (like in the beginning): use String#split if you need to handle csv files.
It's be far easier to split the string:
String[] parts = csvClientPhotos.split(";");
This will give a string array:
{"7455573","photo41.png","photo42.png"}
Then you'd simply copy parts[1] and parts[2] to your vector.
You have two immediate problems.
The first is with your initial manipulation of the string. The two lines:
chainePhotos = csvClientPhotos.substring(csvClientPhotos.indexOf(';')+1);
chainePhotos = chainePhotos.substring(0, chainePhotos.lastIndexOf(';'));
when applied to 7455573;photo41.png;photo42.png will end up giving you photo41.png.
That's because the first line removes everything up to the first ; (7455573;) and the second strips off everything from the final ; onwards (;photo42.png). If your intent is to just get rid of the 7455573; bit, you don't need the second line.
Note that fixing this issue alone will not solve all your ills, you still need one more change.
Even though your input string (to the loop) is the correct photo41.png;photo42.png, you still only add an item to the vector each time you encounter a delimiting ;. There is no such delimiter at the end of that string, meaning that the final item won't be added.
You can fix this by putting the following immediately after the for loop:
if (! photoName.equals(""))
vListPhotosOfClient.addElement(new String(photoName));
which will catch the case of the final name not being terminated with the ;.
These two lines are the problem:
chainePhotos = csvClientPhotos.substring(csvClientPhotos.indexOf(';') + 1);
chainePhotos = chainePhotos.substring(0, chainePhotos.lastIndexOf(';'));
After the first one the chainePhotos contains "photo41.png;photo42.png", but the second one makes it photo41.png - which trigers the if an ends the method with only one element in the vector.
EDITED: what a mess.
I ran it with correct input (as provided by the OP) and made a comment above.
I then fixed it as suggested above, while accidently changing the input to 7455573;photo41.png;photo42.png; which worked, but is probably incorrect and doesn't match the explanation above input-wise.
I wish someone would un-answer this.
You can split the string manually. If the string having the ; symbol means why you can do like this? just do like this,
private void getIdClientAndPhotonames(String csvClientPhotos)
{
Vector vListPhotosOfClient = split(csvClientPhotos);
}
private vector split(String original) {
Vector nodes = new Vector();
String separator = ";";
// Parse nodes into vector
int index = original.indexOf(separator);
while(index>=0) {
nodes.addElement( original.substring(0, index) );
original = original.substring(index+separator.length());
index = original.indexOf(separator);
}
// Get the last node
nodes.addElement( original );
return nodes;
}