Home > Software design >  Extra space in output
Extra space in output

Time:10-29

What in the below code is causing the actual output to be 12/13/ 2003 instead expected 12/13/2003 ?

String inputDate= "";
int monthInt = 0;
String month, day, year;

while (!inputDate.equals("-1")) {
    inputDate = scnr.nextLine();
    if (inputDate.contains(",")) {
        month = inputDate.substring(0, inputDate.indexOf(" "));
        day = inputDate.substring(inputDate.indexOf(" ")   1, inputDate.indexOf(", "));
        year = inputDate.substring(inputDate.indexOf(",")   1, inputDate.length());
        monthInt = getMonthAsInt(month);
        System.out.println(monthInt   "/"   day   "/"   year);
     }
}

I have tried to edit some of the areas that had " " but that one space is not being rectified.

CodePudding user response:

I suspect you are putting a space in the date just before the year. Change this:

year = inputDate.substring(inputDate.indexOf(",")

to:

year = inputDate.substring(inputDate.indexOf(", ")

CodePudding user response:

The quick fix is to add .trim() to all strings

System.out.println(monthInt.trim()   "/"   day.trim()   "/"   year.trim());

But you have to pay attention on the substring function for year. You should sdd 2, to skip a space after the comma.

  • Related