Java string format returns nothing [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am trying to get the returned value from a class, however I believe the string.format() is causing an error resulting in no value to return.
Class:
public class FilterTime {
public String getData(String day, Integer time){
// define the result
String result = "";
String convertedDay = "";
if(day == "Friday 30th August"){
convertedDay = "30";
}
if(day == "Saturday 31st August"){
convertedDay = "31";
}
if(day == "Sunday 1st September"){
convertedDay = "01";
}
if(time == null){
result = "http://www.website.org/json.php?f=%s&type=date".format(convertedDay);
Log.d("RESULT", "r:" + result);
}else{
result = "http://www.website.org/json.php?f=%s&time=#d&type=dateAndTime".format(convertedDay, time);
Log.d("RESULT", "r:" + result);
}
return result;
}
}
When I trace result in my Activity:
FilterTime filterTime = new FilterTime();
String filteredURL = filterTime.getData(dayFilter, timeFilter);
When I trace filteredURL it returns nothing at all. So I then put the Log.d() into the class and I found that when tracing the following it also returns nothing:
if(time == null){
result = "http://www.website.org/json.php?f=%s&type=date".format(convertedDay);
Log.d("RESULT", "r:" + result);
}else{
result = "http://www.website.org/json.php?f=%s&time=#d&type=dateAndTime".format(convertedDay, time);
Log.d("RESULT", "r:" + result);
}
I cannot understand where the error is coming from because there are no errors, just a warning saying it should be accessed in a static way, but I think the error resides in the if statement.

Use equals() to compare the contents of the String :
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Hence change your code to :
if("Friday 30th August".equals(day)){
convertedDay = "30";
}
== operator compares object references, variable which contains a reference to an object. It checks if the references point to the same object.
P.S.:- Invoked equals() on the String literal to avoid any NPE due to null day.

You have incorrect String comparison, instead of == use equals.
format is printing nothing since convertedDay remains empty "" due to invalid String comparison.

String.format() is a static method. Don't call it on a String object, just call it directly like this:
String.format("http://www.website.org/json.php?f=%s&type=date", convertedDay);
That should do the formatting like you wanted

Related

bad operand types for binary operator '!=' first type: String second type: int

I have a problem concerning the display , I would like to see each items from my variable CodeA of type String which is in a JComboBox. The variable CodeA represents each identification from the table Album.
In my DaoAlbumMySql I have error message..
bad operand types for binary operator '!=' first type: String second type: int
The problem is according NetBeans the if (idCat != 0)
public ArrayList <Album> selectAlbums (String idCat)
{
ArrayList <Album> myList = new ArrayList();
String req;
if (idCat != 0)
{
req = "Select CodeA, TitreA, A.IdentC, DenomCat, " +
" DateArrivee from album A, " +
"chanteur C where A.IdentC = C.IdentC" +
" and CodeA = " + idCat + " order by 1";
}
Two problems here:
1) You are trying to compare a String to an int (0). You need to put quotation marks around it to make it a String to String comparison.
2) You are comparing with !=. This is incorrect to compare Strings. Compare with the .equals() method when comparing Strings
(As it is you are checking for (With !=) reference comparison (address comparison) The .equals() method checks for content comparison.)
Unsure what you really want do do. For the moment you compare an String to an Integer.
If idCat should not be null then you have to
if (idCat != null)
If it must not null nor empty
if ((idCat != null) && (!idCat.isEmpty())
or last if it should not contain the value "0"
if (!"0".equals(idCat))
Two comments:
1) You can't compare String with int in Java. I think you tried to detect a null value? Depending the version of Java you're using, you could use java.lang.Optional as an alternative to others provided answers
2) Try to use interface instead of implementation classes when it is possible... Here, you can replace a lot of ArrayList to List.
Regards

Why is "null" treated as string here in the below code and is concatenated to the name of the file? [duplicate]

This question already has answers here:
Concatenating null strings in Java [duplicate]
(5 answers)
Closed 4 years ago.
I have a method to check the operating system type and return a suitable path according to the type of OS. This path is used by another method which accepts this path and saves a file to t
hat location. Now if the OS is not Windows, Linux or Mac then the method returns null. The problem is that this null is treated as a string and null gets added to the name of the saved file e.g; nullFile.txt and saves it in the location where the program is stored.
What can I do to prevent this from happening?
public static String checkOS() {
String store = "";
String OS = System.getProperty("os.name").toLowerCase();
if(OS.indexOf("win") >= 0){
store = "C:/";
} else if(OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ){
store = "/home/";
} else if(OS.indexOf("mac") >= 0){
store = "/home/";
} else{
return null;
}
return store;
}
You don't show the code, but you're probably doing
String filename = checkOS() + "File.txt";
In String concatenation, null values are converted to the string "null", so you have to code an explicit null check.
String osName = checkOS();
String fileName;
if (osName == null)
// do whatever you need to do
else
filename = checkOS() + "File.txt";
As to the option of returning an empty string from checkOS instead of null, that is a possibility but in either case the caller of checkOS is going to need to test the result as I'm sure you want to do something different for that case. A null return is the most generic option.

Converted charAt() doesnt equals to the same String [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
My problem is hidden in next code:
public class saturo {
public String primer, d;
public void start() {
primer = "545640";
//d = "0";
d = String.valueOf(primer.charAt(((primer.length())-1)));
if(d == "0"){
System.out.println("This is equal: d == " + d);
}else{
System.out.println("This is not equal: d == " + d);
}
}
public static void main(String args[]) {
new saturo().start();
}
}
So as you see, the problem is that if i declare String d as "0" than the program will execute it as d is equal to "0" and return true;
But if i get character "0" from a String, convert it to String, and check if this equals to "0" then i have got a false.
I have checked if there is something wrong with character encode, but not, its right in any case. No type mismatches.
Where in this the logic?
If you want to compare the value of 2 strings, you need to use .equals()
So you would do:
if(d.equals("0"){
// your code here
}
Using == compares the strings by reference (same spot in memory) where .equals() compares the value of the strings.
use .equals not == you are comparing by reference not value

'Char' type not converting to 'String' type as expected [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
private boolean CharToString(){
String lineOfText = "XXXXXX";
String desiredResult = "X";
String actualResult = "initialised value";
for(int i = 0; i < lineOfText.length(); i ++){
actualResult = Character.toString(lineOfText.charAt(i));
}
if(desiredResult == actualResult){
return true;
} else{
return false;
}
}
So basically, this code is a reproduction of what I have, but designed to highlight what I believe the problem to be after a long time diagnosing and testing. As you can see, it sets the value of actualResult to the 'char' value of the character at the present location along lineOfText.
Every value is intended to output "X" as a String (converted from char).
However, for reasons unknown to me, despite actualResult and desiredResult both outputting "X" to my debug drawText() method (I can't work out how to use console log...), the method returns false, indicating that the two String variables are NOT equal.
Strangely, if I were to change the if() else to a switch(), it would return true (i.e. work as intended).
I've tried Googling and searching StackOverflow but my search terms are probably poor/wrong as I'm getting no useful results :(
Any help would be greatly appreciated, and sorry if this is a stupid question - I have tried for ages to figure it out myself...
p.s. Is there a good graphic map editor available online anywhere? Editing a .txt file to create a map seems overly complicated, and very difficult to maintain consistency or coherence in the development of large/intricate maps... I figure there must be SOMETHING, how else would you make a 3D java game??
Don't compare strings using ==. Always use equals(), as == only compares that they point to the same memory address, which they won't in this case.
private boolean CharToString(){
String lineOfText = "XXXXXX";
String desiredResult = "X";
String actualResult = "initialised value";
for(int i = 0; i < lineOfText.length(); i ++){
actualResult = Character.toString(lineOfText.charAt(i));
}
if(desiredResult.equals(actualResult)){
return true;
} else{
return false;
}
}
That should do it
To compare 2 strings that refer to different memory locations you should use:
if(desiredResult.equals(actualResult) {
return true;
} else {
return false;
}
If the case would have been:
String desiredResult = "test";
String actualResult = desiredResult;
In this case you could use if(desiredResult == actualResult) , but using equals() would be better practice.

If statement wont recognize string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have an if statement that takes a string, and if another string has the same value as that string do 1 thing, and if the variable doesnt equal that string do another thring
here is my code
if(Pos != "D"){
System.out.println("doesnt = D");
}
if (Pos == "D" ){//WHY ISNT THIS WORKING
System.out.println("it does = D");
}
It recognizes when the variable doesnt = D and prints "doesnt = d" but when the variable = D it does nothing. I dont know why.
thanks
Never compare Strings with == or != since these check to see if two String variables refer to the same object reference, and this is not what you're interested in. Instead use the equals(...) or equalsIgnoreCase(...) method to see if the two Strings have the same chars in the same order as that's what really matters here. i.e.,
Use equals to compare strings :
if ("D".equals(Pos))

Categories