将字符串拆分为数组,然后在Java中的if语句中使用它们

时间:2013-10-20 16:53:23

标签: java

我正在创建自己的命令行,如Windows命令提示符或macs终端。我的计划是让它接受输入(工作)分析(不起作用)并显示它(工作)然后重复。

这是它的测试文件

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);
}

}

它的作用是将代码拆分为数组,然后检查数组中的每个字符串以查找echo或print等命令。一旦找到它,它就会在echo命令之后打印出所有东西。

例如: 它会读到:

"echo Hello World \\"

将其拆分为component = {“echo”,“Hello”,“World”,“\”}

然后检查并发现组件[0]是“echo”然后显示每个东西,直到它击中\ 并将显示

 Hello World

除if语句外,每件事都有效。出于某种原因,如果我使用像这样的数组

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

而不是拆分字符串;它工作正常。

有没有办法让它以与普通数组相同的方式读取分割字符串数组 或者将字符串拆分为数组输出字符串与直接将值保存到数组中的方式不同。

1 个答案:

答案 0 :(得分:1)

要比较java中的对象,请使用.equals()方法而不是“==”运算符

if(component[i] == "echo")更改为if(component[i].equals("echo"))

while(component[i] != "\\")更改为while(!component[i].equals("\\"))

相关问题