Alternative to substring - java

I have a strange problem when adding a value to a String array which is later involved in an array sort using a hash map. I have a filename XFR900a, and the XFR900 part is added to the array using the following code;
private ArrayList<String> Types = new ArrayList<String>();
...
Types.add(name.substring(0,(name.length() - 1));
System.out.println(name.substring(0,(name.length() - 1));
I even print the line which gives "XFR900", however the array sort later on behaves differently when I use the following code instead;
Types.add("XFR900");
System.out.println(name.substring(0,(name.length() - 1));
which is simply the substring part done manually, very confusing.
Are there any good alternatives to substring, as there must be some odd non ascii character in there?
Phil
UPDATE
Thanks for your comments everyone. Here is some of the code that later compares the string;
for (int i=0;i< matchedArray.size();i++){
//run through the arrays
if (last == matchedArray.get(i)) {
//add arrays to a data array
ArrayList data = new ArrayList();
data.add(matchedArray1.get(i));
data.add(matchedArray2.get(i));
data.add(matchedArray3.get(i));
data.add(matchedArray4.get(i));
data.add(matchedArray5.get(i));
//put into hash map
map.put(matchedArray.get(i), data);
}
else {
//TODO
System.out.println("DO NOT MATCH :" + last + "-" + matchedArray.get(i));
As you can see I have added a test System.out.println("DO NOT MATCH" ... and below is some the output;
DO NOT MATCH :FR99-XFR900
DO NOT MATCH :XFR900-XFR900
I only run the substring on the XFR900a filename. The problem is that for the test line to be printed last != matchedArray.get(i) however they are then the same when printed out to the display.
Phil

You should never use the == operator to compare the content of strings. == checks if it is the same object. Write last.equals(matchedArray.get(i)) instead. The equals() method checks if to object are equal, not if they are the same. In case of String it checks if the two strings consists of the same characters. This might eliminate your strange behaviour.
PS: The behaviour of == on string is a little unpredictable because the java virtual machine does some optimization. If two strings are equal it is possible that the jvm uses the same object for both. This is possible because String objects are immutable anyway. This would explain the difference in behaviour if you write down the substring manually. In the one case the jvm optimizes, in the other it doesn't.

Use .equals() rather than == because they are strings!
if (last.equals(matchedArray.get(i))) {}

Never use == operator if you wanted to check the value since operator will check the Object reference equality, use equals operator which check on the value not the reference i.e. for (int i=0;i< matchedArray.size();i++){
//run through the arrays
if (last.equals(matchedArray.get(i))) { // Line edited
//add arrays to a data array
ArrayList data = new ArrayList();
data.add(matchedArray1.get(i));
data.add(matchedArray2.get(i));
data.add(matchedArray3.get(i));
data.add(matchedArray4.get(i));
data.add(matchedArray5.get(i));
//put into hash map
map.put(matchedArray.get(i), data);
}
else {
//TODO
System.out.println("DO NOT MATCH :" + last + "-" + matchedArray.get(i));

Related

Java - How to display all substrings in String without using an array

I have a string which is :
1|name|lastname|email|tel \n
2|name|lastname|email|tel \n
I know that I have to use a loop to display all lines but the problem is that in my assignment
I can't use arrays or other classes than String and System.
Also I would like to sort names by ascending order without using sort method or arrays.
Do I have to use compareTo method to compare two names ?
If that's the case, how do I use compareTo method to sort names.
For example, if compareTo returns 1, that means that the name is greater than the other one. In that case how do I manage the return to sort name properly in the string ?
To display all substrings of the string as in the example, you can just go through all characters one by one and store them in a string. Whenever you hit a delimiter (e.g. | or \n), print the last string.
Here's a thread on iterating through characters of a string in Java:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
If you also need to sort the names in ascending order without an array, you will need to scan the input many times - sorting N strings takes at least N*log(N) steps. If this is a data structure question, PriorityQueue should do the trick for you - insert all substrings and then pop them out in a sorted fashion :)
building on the previous answer by StoneyKeys, since i do not have the privilege to comment, you can use a simple if statement that when the char is a delimiter, System.out.println() your previous scanned string. Then you can reset the string to an empty string in preparation for scanning the next string.
In java, there are special .equals() operators for strings and chars so when you won't be using == to check strings or char. Do look into that. To reset the value of string just assign it a new value. This is because the original variable points at a certain string ie "YHStan", by making it point at "", we are effectively "resetting" the string. ie scannedstr = "";
Please read the code and understand what each line of code does. The sample code and comments is only for your understanding, not a complete solution.
String str ="";
String value = "YH\nStan";
for (int i=0; i <value.length(); i++) {
char c = value.charAt(i);
String strc = Character.toString(c);
//check if its a delimiter, using a string or char .equals(), if it is print it out and reset the string
if (strc.equals("\n")) {
System.out.println(str);
str ="";
continue; // go to next iteration (you can instead use a else if to replace this)
}
//if its not delimiter append to str
str = str +strc;
//this is to show you how the str is changing as we go through the loop.
System.out.println(str);
}
System.out.println(str); //print out final string result
This gives a result of:
Y
YH
YH
S
St
Sta
Stan
Stan

Splitting a string by delimiter without any variables?

Can you split a string in Java without storing what has been split into variables? (Assignment requirement :()
I have tried things which worked on other programming languages however nothing I try seems to work:
(Attempting to see if the second item in a space delimited string (x) is +)
if ((x.split.(" ")).(1) = "+") {
// Do something
}
if ((x.split.(1).(" ")) = "+") {
// Do something
}
Well, what is returned is of type String[]. So if you know that there will be two items, you can reference it as an array..
if(x.split(" ")[1].equals("+"))
Extra Reading
You should look at String Comparison.
String.split returns an array, so this is how it could be done. Note the use of '.equals()'. In Java the == operator checks if the pointer value is the same.
if (x.split.(" ")[1].equals("+")) {
// Do something
}
(And of course this could throw an out of bounds exception if the split wouldn't make an array of size >= 2)

Java Implementing Comparable

I am trying to overwrite the compareTo in Java such that it works as follows. There will be two string arrays containing k strings each. The compareTo method will go through the words in order, comparing the kth element of each array. The arrays will then be sorted thusly. The code I have currently is as follows, but it does not work properly.
I need a return statement outside the for-loop. I'm not sure what this return statement should return, since one of the for-loop return statements will always be reached.
Also, am I using continue correctly here?
public int compareTo(WordNgram wg) {
for (int k = 0; k < (this.myWords).length; k++) {
String temp1 = (this.myWords)[k];
String temp2 = (wg.myWords)[k];
int last = temp1.compareTo(temp2);
if (last == 0) {
continue;
} else {
return last;
}
}
}
You want to compare the two string at the same location:
int last = temp1.compare(temp2);
Java compiler mandates all the end points must have a return statement. In your case you must return 0 at end so when both arrays contain completely equal strings the caller will know they are equal.
You should start listening to your compiler, because after looking at your code for 1 minute, I spotted two undefined states: this.myWords.length is 0 and the two words are equal.
Also, I personally find it very difficult to handle multiple method exit points with all possibilities for input considered and rather insert a single returning statement which makes debugging easier and the results more predictable. In your case for example, I would collect the results of compareTo in a collection if they differ from 0 so that after the for-loop has finished, you could decide at the state of this collection if 0 (empty collection) or the first value in the collection could be returned. I like this more formal approach, because it enforces you to think set-like as in "Give me all comparing results where compareTo results in anything else but 0. If this list is empty, the comparing result is 0, otherwise it is the first element of the list."

String compare function equals not giving correct result

I am using eclipse with java
I am trying to compare two string removing all the space between them.
Here is my code
First I am removing whitespace within the Strings.
System.out.println("["+StringUtils.deleteWhitespace(s4)+"]");
System.out.println("["+StringUtils.deleteWhitespace(s3)+"]");
// comparing Strings
if(s4.equals(s3))
{
System.out.println("Text Match");'
}
Below is the output from lines 1 and 2 that is displaying on Eclipse console:
[gnarlyadj.Somethingthatisgnarlyhasmanyknotsandbumpyareasonitssurface.nudosoadj.Algonudosotienemuchosnudosyunasuperficiellenadebultos.]
[gnarlyadj.Somethingthatisgnarlyhasmanyknotsandbumpyareasonitssurface.nudosoadj.Algonudosotienemuchosnudosyunasuperficiellenadebultos.]
From what I can see, there is no difference between two string yet it is displaying string as a mismatch.
You did not assign the results of the deleteWhitespace() operation to anything. Your two strings will therefore remain unchanged.
Store the result like so, before printing it:
s4 = StringUtils.deleteWhitespace(s4);
The method StringUtils.deleteWhitespace(s4) does not change the String referenced by s4 (Strings are immutable) but returns a new string.
If you do the following code:
s3 = StringUtils.deleteWhitespace(s3);
s4 = StringUtils.deleteWhitespace(s4);
if (s4.equals(s3)) {
System.out.println("Text Match");'
}
Then you will see that the two strings are really equal and the "Text Match" is printed.

Beginners Java Question (string output)

So I'm reading input from a file, which has say these lines:
NEO
You're the Oracle?
NEO
Yeah.
So I want to output his actual lines only, not where it says NEO. So I tried this:
if(line.trim()=="NEO")
output=false;
if (output)
TextIO.putln(name + ":" + "\"" + line.trim() + "\""); // Only print the line if 'output' is true
But thats not working out. It still prints NEO. How can I do this?
When comparing strings in Java you have to use the equals() method. Here's why.
if ( "NEO".equals(line.trim() )
I think you're looking for line.trim().equals("NEO") instead of line.trim() == "NEO"
That said, you can get rid of the output variable by instead doing
if(!line.trim().equals("NEO"))
{
TextIO.putln(name + ":" + "\"" + line.trim() + "\""); // Only print the if it isn't "NEO"
}
Strings are objects in Java. This means you can't just use the == operator to compare them, since the two objects will be different even if they both represent the same string. That's why the String object implements an equal() method, which will compare the contents of the objects, instead of just their memory addresses.
Reference
String.equals() docs
In Java, Strings are objects. And the == operator checks for exact equality.
In other terms
final String ans = line.trim();
final String neo = "NEO";
if (ans == neo) ...
implies you want to check that the ans and the neo objects are the same. They are not, since Java allocated (instantiated) two objects.
As other said, you have to test for equality using a method created for the String object, that actually, internally, checks the values are the same.
if (ans.equals(neo)) ...
try the following:
if(line.trim().equals("NEO"))

Categories