包含方法无法正常工作

时间:2014-10-15 07:53:59

标签: java

我尝试使用contains方法搜索句子中的单词,但它只适用于句子中的第一个单词。

例如,在“喜欢Shakira的照片”中搜索“Shakira”时,我的程序无法找到它。另一方面,在同一个句子中搜索“喜欢”有效。

这是我正在使用的代码:

package fules;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class fule {

    public static int i,x,n,k,ba,sh,fe;

    public static void main(String[] args) throws FileNotFoundException  {

        File s=new File("C:/Users/taha/Desktop/tt.in");
        Scanner m=new Scanner(s);
        fule obj=new fule();
        i=m.nextInt();//test case
        n=m.nextInt();
        k=m.nextInt();
        for (int l=0;l<6;l++){
            boolean q=contains((m.next()),("taha"));
            if(q) {
                ba++;
            }
            boolean w=contains((m.next()),("Shakira"));
            if(w)
                sh++;
        }
        boolean e=contains((m.next()),("Fegla"));
        if(e) {
            fe++;
        }

        System.out.println("ba="+ba+" sh="+sh+" fe="+fe);
        m.close();
    }

    static boolean contains (String s1,String s2)
    {
        return s1.contains(s2);
    }
}

这是 (tt.in)

中的输入
1
6 2
liked Badr's photo
liked Shakira's photo
liked Badr's photo
liked Fegla's photo
liked Shakira's photo
commented on Shakira's photo

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

您正在使用next()方法获取Finds and returns the next complete token from this scanner。因此,您只阅读句子的第一个单词。

尝试将next()替换为nextLine()

如果要将相同的String与多个模式进行比较,请将该String存储在变量中。目前,您对contains()的每次调用都会从扫描仪中读取新的字符串。

你应该写这样的东西:

        String input = m.nextLine();
        boolean q=contains(input,"Badr");
        if(q)
        {
            ba++;
        }
        boolean w=contains(input,"Shakira");
        if(w)
            sh++;
        }
        boolean e=contains(input,"Fegla");
        if(e)
        {
            fe++;
        }

这会在“喜欢夏奇拉的照片”中找到“夏奇拉”。

当然,有更有效的方法来编写相同的代码。

        String input = m.nextLine();
        if (input.contains("Badr"))
            ba++;
        if (input.contains("Shakira"))
            sh++;
        if (input.contains("Fegla"))
            fe++;
相关问题