Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is extremely odd. I am simply comparing two strings, which are the same, but they aren't comparing properly. text is a string I extract from a user conversation (it is trimmed):
String compareThis = sharedPrefs.getString("key", "default").toLowerCase().trim();
if (text.equals(compareThis)){
Toast.makeText(lol, "Good, strings matched :)", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Should be " +text +" Not " +compareThis, Toast.LENGTH_SHORT).show();
}
Now look, this code looks simple enough, but the conditional is going into the else even though the strings are equal...Now you're thinking thats because the strings aren't equal. No, because I get this toast:
Should be hello Not hello
WHAT?! Those are the same string?! The toast even shows that those are the same...Why is the comparison not working if they are both "hello"?
Thanks,
Ruchir
This is extremely odd. I am simply comparing two strings, which are the same, but they aren't..
are you sure they are the same strings ???
try get bytes and compare them (by bytes) or use codepoints
try {
byte[] bytesStr1 = Str1.getBytes("UTF-8");
byte[] bytesStr2= Str2.getBytes("UTF-8");
if(bytesStr1.length!=bytesStr.length)log("no match = size");
for(int b=0;b<bytesStr1.length;b++) {
if(bytesStr1[b] != bytesStr2[b])
return log("no match at pos: "+ b);
}
} catch (UnsupportedEncodingException e) {
// handle exception here
}
there could be many reasons why the string comparison fails -
for example
space vs. non breaking space <- trim will not help you here
simple example:
String oldString = "\uD800";
String newString = new String(oldString);
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
newString.equals(oldString) // ???? false
small appeal:
most of your(by this i mean most people here) problems can be solved by reading and understanding the basics :) - but instead you are all "drowning" from big "water"
Okay, I tried what you said and went byte by byte, but they were all the same. Also, the lengths were the same.. – Ruchir Baronia
so this mean that both strings "in your definition" are equals
instead of compare method you can use :
int pos = String.indexOf(String); //this will return you the firs position where the two strings don't match
method implementation is similar to method which i wrote on the beginning of this post
lecture:
https://docs.oracle.com/javase/tutorial/java/data/comparestrings.html
now when we we code for android I recommend to take special attention - because google is rewriting most of java classes by itself String class from Oracle is not the same as Google String class because they don't run straight on ORACLE JVM !!! - see ART (Android Runtime) - every time when i visit google & browse repos i see code changes in google api & source code of android i see much more things rewrite in pure c (as native) - google wants to break with proprietary oracle java thus is using more of open jdk implementations
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
So I am having an issue, I put my self to the test of creating a 2D sandbox game kind of for fun, but has turned out evolving into something a bit more after about a week, but, to the point, I am saving chunk data into a few files, these are just .file or, just the most basic file type I assume, and the problem persists even using .txt files.
So what's happening is after saving a file containing the object name, x, and y positions, I am creating an object in a linked list using that information, when I enter a new "chunk", but things are not exactly right, somehow, my images load up for the tiles correctly, which is handled in the constructor for that tile, being called after it is added to the list, however, what made me notice is I have a check in the tiles update method, to see if it wants to change to a different grass texture, and it doesn't happen, so I did some checking and printing, and well, I can tell that the name variable certainly contains the desired name, eg. "dirt", however it does not equal "dirt", so I thought it was catching some spaces and I even trimmed the String, and when I run a test like
if(name == "dirt")System.out.print("dirt is actually "+name);
else System.out.print("dirt is apparently not "+name);
and the result is always, "dirt is apparently not dirt", with no spaces, and even when looking in the actual file I save it to, it saves the name fine, I have them saving in an order like so;
name x y
eg.
dirt 0 560
dirt 28 560
and so on, these all load in position perfectly fine and what stumps me is that the initial image loads in correctly, which is quite explicit, a switch statement to determine what the image, material type and such should be..
I was wondering if anyone has come across something like this and what it could possibly be.
Also any code desired I will add to the desc.
(I didn't know so many people would be so quick to help. Thank you all, I know it was a simple problem, but it had me super confused, now thanks to you all I understand something about comparing variables and objects I should have really known before, and which is really important
.)
Chances are the result is "dirt" but you're not testing it correctly.
Test should be if name.equals("dirt") ... not the equality operator ==.
See: How do I compare strings in Java?
Equality in Java:
String dirt1 = "dirt";
String dirt2 = new String("dirt");
System.out.println(dirt1 == "dirt"); // TRUE
System.out.println(dirt1 == dirt2); // FALSE
System.out.println(dirt1 == dirt2.intern()); // TRUE
System.out.println(dirt1.equals(dirt2)); // TRUE
I have the following problem: I have a String that I read from a MySQL Database (with the JDBC driver) and have to compare it with another String that I receive over TCP with a BufferedReader. When I use String.equals, false is returned even if the Strings are exactly equal, I even printed both Strings to the console to make sure there aren't any typos or null objects. String.compareTo returns a negative number around -100.
I am really confused here and have no concrete idea how to fix that. Maybe it's related to the database's encoding (UTF-8)?
As requested, here is my code snippet:
public TeleportSign getTeleportSign(String target) {
// I used a HashMap, but I switched to an ArrayList in order to be able
// to compare the Strings directly.
//return signs.get(target);
for(TeleportSign s : signsList) {
// I am printing the Strings here. I even put stars to the left
// and the right of the String to make sure there are no
// spaces or new lines. s.getTarget() returns the String from the DB,
// target is the String sent over TCP.
System.out.println("*" + s.getTarget() + "* " +
String.valueOf(s.getTarget().compareTo(target))
+ " *" + target + "*");
if(s.getTarget().compareTo(target) == 0)
return s;
}
return null;
}
And the console output is:
*TDM1* -84 *TDM1*
Thanks in advance!
Captain
So I rebooted the entire system and retried. Everything works now as expected. I can't explain this to myself because I restarted the JVM multiple times and nothing happened, and a system reboot shouldn't affect a Java program like this.
I am sorry for everyone's time I wasted, but I really appreciate your quick help anyways.
EDIT: I use the trim method from String now. This method cuts off any leading null characters to prevent issues like this one. I hope this will be helpful for someone who has the same problem!
Is there a way i can create code build code by using Concatenation in Android studio/eclipse?
In other words i have 2 sets of strings one for each country i am dealing with ZA and KE. They have 2 different EULA's.
So i would like to pull the string related to the respective country.
String message = mContext.getString(R.string.eula_string_za);
above is an example of the output code. is there someway i can go about "creating" that based on If statements?
String str = "mContext.getString(R.string.eula_string_";
if (something = "ZA") {
str += "za);";
} else {
str += "ke);";
}
so if the country selected is ZA then the output code should be
mContext.getString(R.string.eula_string_za);
and if its KE it should be
mContext.getString(R.string.eula_string_ke);
and then the result will then pull the correct string from strings.xml?
Java is a compiled code, not an executed one,you can't write code this way like in an interpreted language.
The best way to manage different languages in android is to use a string.xml file for each language.
Take a look at this tutorial, it will help you a lot :
Supporting different languages in android
If you want to go this route you could try to use reflection. Have a look at Class.getField(…) if you want to use reflection.
Instead of first building a code string using a if statement you can also use the same if statement to find the correct string:
String str;
if (something.equals("ZA")) {
str = mContext.getString(R.string.eula_string_za);
} else {
str = mContext.getString(R.string.eula_string_ke);
}
Note that your condition something = "ZA" does not do what you think it does: It assigns something the string "ZA" and then evaluates itself to "ZA", so this would not even compile. The correct way would be something == "ZA", but even this does not work in the general case. You need to use String.equals(…). Some even argue you should use it the other way around (i.e. "ZA".equals(something)) to avoid a NullPointerException…
Another possibility would be to first build a Map from county to the corresponding string ID for all the EULAs you have and then asking the Map to return the correct one.
But probably the cleanest solution would be to use Androids built in mechanism, as hkN suggests.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Given a string I #eat# #hamburgers# and a StringBuilder eat: [eat, consume, like] hamburgers: [hamburgers, spinach, bananas], I want to randomly replace the words within hashmarks with randomly chosen ones from their wordbanks, so that phrases such as I like bananas and I consume spinach will be generated. Code to randomly select another word, given a token (i.e. eat, hamburgers) has been written.
I need to use this regex #[^#]+# to find words within the initial string contained by hashmarks, pass them to the replace method, and then put their random correlates back inside the initial string. I tried using StringTokenizer, but realized it's not the tool for the job.
I need to somehow extract the first word within hashmarks and pass it to the method calling for its replacement before calling the method archetypeString(#[^#]+#, replacement) in such a way so that when the loop runs again, both the word grabber&passer-to method and the replacement method are then working with the second hashed word.
tokenizer dead-end:
StringTokenizer stt = new StringTokenizer(archetype);
while(stt.hasMoreTokens()){
String temp = stt.nextToken();
if(temp.charAt(0)=='#');
}
and the getPhrase method:
public List<String> getPhrases(StringBuilder fileContent, String token) {
StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(fileContent.toString()));
List<String> list = new ArrayList<String>();
try {
while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
if (tokenizer.sval.equals(token)) {
tokenizer.nextToken(); // '['
do {
tokenizer.nextToken(); // go to the number
list.add(String.valueOf(tokenizer.sval));
} while (tokenizer.nextToken() == ',');
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
I need to use this regex #[^#]+# to find words within the initial string contained by hashmarks, pass them to the replace method, and then put their random correlates back inside the initial string. I tried using StringTokenizer, but realized it's not the tool for the job.
It is not clear from your question whether this is part of some sadistic homework assignment or just the first way you thought of to solve whatever problem you're trying to solve. This is not a regular expression problem any more than it's a StringTokenizer problem.
Look at String.format(), and the formatting capabilities of Formatter. I do not understand why you would ever need to know what the last string you generated was if your object is to generate the next one at random. Just pick a new random value and format it with String.format().
--
After reading your comment to this answer and looking at the question you referred to, I'm going to make a couple of recommendations.
(1) start with a simpler coding assignment or two, something without regular expressions. Make sure you absolutely understand the following concepts: instance variables. variable scope. public methods versus private methods. passing parameters to methods, and returning values from methods. You can do quite a bit with just that much. You don't need to study inheritance until you have all of those down cold, and I recommend that you do not try.
(2) for each coding assignment for at least your first 5, make sure you have written out what your program is to be provided as data and what output it is supposed to produce. List any constraints someone has given you separately (must use class X, must display error message, whatever).
(3) Put opening braces and closing braces on lines by themselves; match each opening brace with a closing brace indented the same amount. Indent code within each pair of braces another 2 or 3 spaces further to the right. This means that brace pairs inside other brace pairs will be indented further. I know this is not the way you see most code, and plenty of people will tell you that it is "wrong". But until you get comfortable with scope and whether a given place in your code is inside or outside a method or a loop, I think it best that you give yourself these extra visual cues. For someone not familiar with other ways of doing things, this is easiest.
(4) be careful of your terms when posting here. In the other question you refer to, you say it is about inheritance, but it uses "implements", indicating that it is implementing an interface, not inheriting from a class. It is confusing to those of us trying to help you if you get the terminology wrong.
(5) when you post here: post the entire program (these early assignments should all be under 100 lines total, no reason not to post all of it). Make sure it is properly indented; use spaces instead of tabs. In text, and maybe also in comments, point out the place in the code where you seem to have the problem (if you know). If there is an error message, post the entire error message (don't tell us what it is, and don't try to interpret it for us). Work on your code until you have a specific question: why do I get a compile error here? Why do I get (or fail to get) this output? The program outputs X but I expected Y, why is that? etc.
We're not a tutorial shop; most of us need instruction to learn to program, and you need to get most of that somewhere besides here. We are willing to help with your questions, given that your questions are specific and reasonable and you aren't expecting us to provide the instruction. By itself, "I'm lost and need help" is a bit beyond StackOverflow's normal way of operating.
Some classmates and I are working on a homework assignment for Java that requires we print an ArrayList of Strings to a PrintWriter using word wrap, so that none of the output passes 80 characters. We've extensively Googled this and can't find any Java API based way to do this.
I know it's generally "wrong" to ask a homework question on SO, but we're just looking for recommendations of the best way to do this, or if we missed something in the API. This isn't the major part of the homework, just a small output requirement.
Ideally, I'd like to be able to wordwrap the ArrayList's toString since it's nicely formatted already.
Well, this is a first for me, it's the first time one of my students has posted a question about one of the projects I've assigned them. The way it was phrased, that he was looking for an algorithm, and the answers you've all shared are just fine with me. However, this is a typical case of trying to make things too complicated. A part of the spec that was not mentioned was that the 80 characters limit was not a hard limit. I said that each line of the output file had to be roughly 80 characters long. It was OK to go over 80 a little. In my version of the solution, I just had a running count and did a modulus of the count to add the line end. I varied the value of the modulus until the output file looked right. This resulted in lines with small numbers being really short so I used a different modulus when the numbers were small. This wasn't a big part of the project and it's interesting that this got so much attention.
Our solution was to create a temporary string and append elements one by one, followed by a comma. Before adding an element, check if adding it will make the string longer than 80 characters and choose whether to print it and reset or just append.
This still has the issue with the extra trailing comma, but that's been dealt with so many times we'll be fine. I was looking to avoid this because it was originally more complicated in my head than it really is.
I think that better solution is to create your own WrapTextWriter that wraps any other writer and overrides method public void write(String str, int off, int len) throws IOException. Here it should run in loop and perform logic of wrapping.
This logic is not as simple as str.substring(80). If you are dealing with real text and wish to wrap it correctly (i.e. do not cut words, do not move comas or dots to the next line etc) you have to implement some logic. it is probably not too complicated but probably language dependent. For example in English there is not space between word and colon while in French they put space between them.
So, I performed 5 second googling and found the following discussion that can help you.
private static final int MAX_CHARACTERS = 80;
public static void main(String[] args)
throws FileNotFoundException
{
List<String> strings = new ArrayList<String>();
int size = 0;
PrintWriter writer = new PrintWriter(System.out, true); // Just as example
for (String str : strings)
{
size += str.length();
if (size > MAX_CHARACTERS)
{
writer.print(System.getProperty("line.separator") + str);
size = 0;
}
else
writer.print(str);
}
}
You can simply write a function, like "void printWordWrap(List<String> strings)", with that algorithm inside. I think, it`s a good way to solve your problem. :)