【问题标题】:Read each individual word in string per 'if'每个'if'读取字符串中的每个单词
【发布时间】:2017-09-27 13:05:06
【问题描述】:

有没有办法让 Java 读取字符串中每个“if”的每个单词? 我会尽力解释这个...

public class test{
    public static void main(String[] args){
        String sentence = "testing1 testing2 testing3 testing4"

        //Scan first word \/ 
        if(sentence.equals("testing1"){
            //scan second word \/
            if(sentence.equals("testing2"){
                //scan third word \/
                if(sentence.equals("testing3"){
                    System.out.println("Works good!")
                }
            }
        }
    }
}   

如果你能帮助我,我将不胜感激。

【问题讨论】:

  • 我不明白你的问题,你能详细说明一下吗?

标签: java string if-statement


【解决方案1】:
String[] array = sentence.split(" ");

//Scan first word \/ 
if(array[0].equals("testing1"){
    //scan second word \/
    if(array[1].equals("testing2"){
        //scan third word \/
        if(array[2].equals("testing3"){
            System.out.println("Works good!")
        }
    }
}

【讨论】:

  • 不要添加不必要的代码,而是考虑为您的答案编写解释并编辑。
【解决方案2】:

您可以像下面这样使用 Scanner.next():

String sentence = "testing1 testing2 testing3 testing4";
try (Scanner sc = new Scanner(sentence)) {
    if (sc.next().equals("testing1")) {
        if (sc.next().equals("testing2")) {
            if (sc.next().equals("testing3")) {
                if (sc.next().equals("testing4")) {
                    System.out.println("Works good!");
                }
            }
        }
    }
}

【讨论】:

  • 也可以考虑使用"The try-with-resources Statement"
  • @KeionBeats 很高兴为您提供帮助。您还可以使用一个 if 语句,例如: if (sc.next().equals("testing1") && sc.next().equals("testing2") && sc.next().equals("testing3") && sc.next().equals("testing4"))
【解决方案3】:

如果我正确理解了您的问题,您可以尝试以下方法:

public static void main(String[] args){
    String sentence = "testing1 testing2 testing3 testing4";
    String[] arrayOfWords = sentence.split(" "); // split the sentence according to the spaces
    Scanner in = new Scanner(System.in);

      //Scan first word
      System.out.println("Insert First Word");
      if(arrayOfWords[0].equals(in.next())){
            System.out.println("Insert Second Word");
            if(arrayOfWords[1].equals(in.next())){ 
               System.out.println("Insert Third Word");
               if(arrayOfWords[2].equals(in.next())){
                     System.out.println("Works good!");
               }
            }
        }
}

例如:

Insert First Word
testing1
Insert Second Word
testing2
Insert Third Word
testing3
Works good!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    相关资源
    最近更新 更多