-3

我想从文件中输入字符串并检查每个字符串是否与给定字符串匹配,但我做不到。提前感谢您的帮助。我的代码如下:

import java.util.*;
import java.io.*;
import org.apache.commons.io.*;
import java.nio.charset.*;

public class XYZ
{
    String s[] = {"Harry","Potter","Pirates","Of","The","Carribean"};

    XYZ()
    {
        save();
        String []copyString = load();
        for(int i=0; i<6; i++)
        {
            System.out.print("String " + i + ": " + copyString[i]);
        }
    }

这是我save()将字符串保存到文件的函数:

public void save()
{
    DataOutputStream output = null;
    try
    {
        output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("the-file-name.txt"))); 
        for(int i=0; i<6; i++)
        {
            output.writeUTF(s[i]);
        }
        output.close();
    }
    catch(IOException e){}      

}

这是我的load()函数,它返回一个字符串:

    public String[] load()
    {
        final Charset UTF_8 = Charset.forName("UTF-8");     
        String temp;
        String copyFromFile[] = new String[6];

        DataInputStream input = null;
        try
        {
            input = new DataInputStream(new BufferedInputStream(new FileInputStream("the-file-name.txt")));
            for(int i=0; i<6; i++)
            {

                temp = input.readUTF(); 
                if(temp == "Harry" || temp == "Potter"  || temp == "Pirates"  || temp == "Of"  || temp == "The"  || temp == "Carribean" )
                {
                    copyFromFile[i] = temp;
                }
                else
                {
                    System.out.println("Not matched");
                }
            }
            input.close();
        }catch (IOException e){}
        return copyFromFile;
    }

最后,我的main()功能:

public static void main(String[]arg)
{
    XYZ xyz = new XYZ();

}

}

输出:

Not matched
Not matched
Not matched
Not matched
Not matched
Not matched
4

1 回答 1

0

使用 .equals 进行字符串比较。你应该用 temp.equals() 替换 temp == "Harry" ...

于 2017-09-23T12:19:50.027 回答