0
public static boolean stringToBoolean (String horv) { 
    if (horv == "H") {
        return true;
    } if (horv == "V") {
        return false;
    } else {
        return true;
    }

This is a small part of a program I am creating. The program is reading from a file and inputting the data into an array. For this part it is reading what will either be a "H" or "V" from the file and converting it to a boolean value. The problem is when I run the program I am only getting true for every value, even the ones that have a "V" as their variable.

4 Answers4

2

Change the code to be:

if ("H".equals(horv)) { return true; }
...
KevinO
  • 4,303
  • 4
  • 27
  • 36
2

Try This

public static boolean stringToBoolean (String horv) { 
    if ("H".equals(horv)) { // use equals method for string comparison 
        return true;
    } if ("V".equals(horv)) {
        return false;
    } else {
        return true;
    }
Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
1

String variables should be compared with equals() method in java.

Areca
  • 1,292
  • 4
  • 11
  • 21
1

In Java you have compare String with a method equals() Like this

public static boolean stringToBoolean (String horv) { 
  if (horv.equals("H"))  return true;
  if (horv.equals("V"))  return false;
  return true;
}
Muhammad Suleman
  • 2,892
  • 2
  • 25
  • 33