0

I'm making my own Command line like windows command prompt or macs terminal. My plan was to have it take input(works) analysis it(does not work) and display it(works) then repeat.

This is the testing file for it

import java.util.Scanner;

public class addingStrings {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    //Init
    String out = "";

    String input = scan.nextLine();

    String component[] = input.split(" ");




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

        if(component[i] == "echo") {

            i++;

            while(component[i] != "\\") {

                out += component[i];

                i++;
            }
        }
    }



    System.out.println(out);
}

}

what it does is splits up the code into an array then checks each string in the array for a command such as echo or print. Once it finds one it would then print every thing after the echo command.

ex: it would read:

"echo Hello World \\"

split it into component = {"echo", "Hello", "World", "\"}

then check and find that component[0] is "echo" then display every thing until it hit \ and would display

 Hello World

Every thing works except for the if statement. for some reason if i use an array like this

 String[] component = {"echo", "Hello", "World"};

instead of splitting a String; it works fine.

Is there any way to make it read the split string array the same way as the normal array or does splitting a string to an Array output a string differently than directly saving values into an array.

  • Have you tried testing by comparing the elements of the array you read in to those of the array that you statically create? – qaphla Oct 20 '13 at 16:56

1 Answers1

1

To compare objects in java use .equals() method instead of "==" operator

change if(component[i] == "echo") to if(component[i].equals("echo"))

change while(component[i] != "\\") to while(!component[i].equals("\\"))

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
  • thanks. the if statement works now but in the while loop it has an error and says Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: 3 at TestingIsfun.addingStrings.main(addingStrings.java:26) – JavaLPyDev Oct 20 '13 at 17:12
  • @JavaLPyDev replace your while condition with this one while (i < component.length && !component[i].equals("\\")) – Prabhakaran Ramaswamy Oct 20 '13 at 17:40