Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Cant figure out whats wrong with this very simple code? public class worker { pu

ID: 3801533 • Letter: C

Question

Cant figure out whats wrong with this very simple code?

public class worker {

   public static void main(String[] args){

       //read in the file into string array of words

       String[] commands = {"a","b","c"};

       for(int i = 0; i<= commands.length; i++){

           if (commands[i] == "a") {

       System.out.print(commands[i]);

          }

           else if (commands[i] == "b") {

       System.out.print(commands[i]);

          }

           else if (commands[i] == "c") {

       System.out.print(commands[i]);

          }

           else{

               System.out.print("none of these was found!");

           }

           }

       }

}

Explanation / Answer

public class Worker {
    public static void main(String[] args){
        //read in the file into string array of words
        String[] commands = {"a","b","c"};
        for(int i = 0; i< commands.length; i++){ // Here was mistake //
            if (commands[i] == "a") {
                   System.out.print(commands[i]);
            }
            else if (commands[i] == "b") {
                   System.out.print(commands[i]);
                }
            else if (commands[i] == "c") {
                   System.out.print(commands[i]);
            }
            else{
                System.out.print("none of these was found!");
            }
        }
    }
}

Explanation :

length of command array is 3 but you was running loop 4 times from 0 to 3 (for i=0; i<=3 ;)(means 4 times i=0,1,2,3) but it should run 3 times from 0 to 2 (i=0,1,2)

So I corrected for loop (i=0; i< 3;i++)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote