0

I am trying to return a string with time but somehow the returned string blank. I don't know what is the right way to do it.

static String timeConversion(String s) { 
     int hr=Integer.parseInt(s.substring(0,2));
     String min=(s.substring(3,5));
     String sec=(s.substring(6,8));
     String ap=s.substring(8,10);
     String res="";
     if(ap=="AM")
     {
         if(hr==12)
         {
             res.concat("00"+":"+min+":"+sec);
         }
         else
         {
             res.concat(hr+":"+min+":"+sec);
         }
     }
     else if(ap=="PM")
     {
         hr=hr+12;
         res.concat(hr+":"+min+":"+sec);
     }
     return res;
}
khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

2

There are two issues:

  • Since strings are immutable, you must assign the result of .concat(String) to the variable if you want it to be updated.
  • Comparing strings must be done using .equals()

With that in mind...

static String timeConversion(String s)
{
    // Expecting a string in the format "HH:MM:SSAM" or "HH:MM:SSPM"
    int hr = Integer.parseInt(s.substring(0, 2));
    String min = s.substring(3, 5);
    String sec = s.substring(6, 8);
    String ap = s.substring(8, 10);
    String res = "";
    if (ap.equals("AM")) {
        if (hr == 12) {
            res = res.concat("00" + ":" + min + ":" + sec);
        } else {
            res = res.concat(hr + ":" + min + ":" + sec);
        }
    } else if (ap.equals("PM")) {
        hr = hr + 12;
        res = res.concat(hr + ":" + min + ":" + sec);
    }
    return res;
}

As another note, while concat is OK in small doses, if you're concatenating multiple strings in a function/method (for example, in a loop), use a StringBuilder instead.

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
0
 int hr=Integer.parseInt(s.substring(0,2));
 String min=(s.substring(3,5));
 String sec=(s.substring(6,8));
 String ap=s.substring(8,10);
 String res="";

 System.out.println(ap) //see the value of ap in the console
 if(ap=="AM")// do ap.equalsIgnoreCase("AM")
 {
     if(hr==12)
     {
         res.concat("00"+":"+min+":"+sec);
         System.out.println(res) //see console and try res = res.concat ...

     }
     else
     {
         res.concat(hr+":"+min+":"+sec);
         System.out.println(res) // see console

     }
 }
 else if(ap=="PM")
 {
     hr=hr+12;
     res.concat(hr+":"+min+":"+sec);
     System.out.println(res)

 }
  System.out.println(res)
  return res;
}

you can also try to use + e.g res = res + ("00"+":"+min+":"+sec); you can also try using stringBuilder

i think your question is more like.. "how can i debug my code"; with the above solution. you will figure out where the problem is

Timetrax
  • 1,373
  • 13
  • 15