Java code prints right but returns wrong

The following code:

public class NewClass1 {

    public static String mus = "";

    public static String musCal(String[] signal, int[] time) {
        int i = 0;
        while (i < signal.length) {
            switch (signal[i]) {
            case "x": {
                // System.out.print("x = ");
                mus = mus + "x";
                int sum = time[i];
                if (signal[i + 1] == "C") {
                    i++;
                    while (i < signal.length && signal[i] == "C") {
                        sum += time[i];
                        i++;
                    }
                } else
                    i++;
                // System.out.print(sum + " ");
                mus = sum + " ";
                break;
            }
            case "y": {
                // System.out.print("y = ");
                mus = mus + "y ";
                int sum = time[i];
                if (signal[i + 1] == "C") {
                    i++;
                    while (i < signal.length && signal[i] == "C") {
                        sum += time[i];
                        i++;
                    }
                } else
                    i++;
                // System.out.print(sum + " ");
                mus = sum + " ";

                break;
            }
            case "z": {

                // System.out.print("z = ");
                mus = mus + "z ";
                int sum = time[i];
                if (signal[i + 1] == "C") {
                    i++;
                    while (i < signal.length && signal[i] == "C") {
                        sum += time[i];
                        i++;
                    }
                } else
                    i++;
                // System.out.print(sum + " ");
                mus = sum + " ";

                break;
            }
            }
        }
        return mus;
    }

    public static void main(String[] args) {
        String signal[] = { "x", "y", "y", "C", "C", "z", "C", "C", "x", "C" };
        int time[] = { 2, 5, 1, 4, 7, 8, 2, 6, 4, 3 };

        musCal(signal, time);
        System.out.print(mus);
    }
}

The expected output from the code is:

x=2  y=5  y=12  z=16  x=7

If the comments signs // are removed to activate the System.out.print statements, the code gives the expected output. But when I was trying to collect this output in the form of ‘String mus’, as shown in the code, I got only the last element of the output string i.e. 7. Being new comer to java and programming, I need your help. Kindly help me to correct the return statement so that I may get the right output as String ‘mus’ by concatenating, or by any other suitable method.

Answer

you can also use this solution for :

replace mus=sum + " "; with mus += sum + " ";

Leave a Reply

Your email address will not be published. Required fields are marked *