gpt4 book ai didi

java - 基本java中存在导入、类困惑

转载 作者:行者123 更新时间:2023-12-01 11:21:22 25 4
gpt4 key购买 nike

我有一个程序,它导入一个字符串文件,解析它以获取正确的单词,然后过滤并打印唯一的单词。我已经设置了一个类来导入 .txt 文件并将单词放入 ArrayList 中:

public class RawText 
{
ArrayList<String> allWords = new ArrayList<String>(); //raw list of words

/**
* This method reads strings from file, filters for only upper/lowercase strings and adds to allWords
* @throws IOException
* @params filename: a string filename
*/
public void add(String filename) throws IOException
{
File inFile = new File(filename); //inst. file import for raw
Scanner read = new Scanner(inFile); //inst. scanner object

while (read.hasNext()) //reads until end of text
{
String word = read.next(); //scanner reads next complete string
word = word.replaceAll("[^a-zA-Z", ""); //filters out non-alphabet chars
allWords.add(word); //adds 'stripped-down' string to list
}
read.close();
}

}

以及Main(),过滤方法和打印:

public class Source1 {
static ArrayList<String> allWords = new ArrayList<String>();
static ArrayList<String> uniqueWords = new ArrayList<String>();

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
RawText rt = new RawText(); //Inst. class for import
Source1 source = new Source1(); //Inst. class variables
rt.add("text.txt"); //creates arraylist of raw words
removeRepeats(); //run method to filter out repeats

printArray(source.allWords); //prints unfiltered array
printArray(source.uniqueWords); //prints filtered array
}

/**
* matches words against previously used words, and strips out repeats
* @params words any string array to be filtered for repeat words
*/
public static void removeRepeats()
{
boolean isUnique = false; //default State for rejecting repeat words
uniqueWords.add(0) = allWords.get(0);//Prime the matching algorithm at first word

int i = 0; //i counts up each raw word to be tested
while (i < allWords.size())
{
int j = 0; //j counts up each previous unique word
while (j < uniqueWords.size()) //runs through all current uniques
{
isUnique = true; //set state to true
if (allWords.get(i) == uniqueWords.get(j))
isUnique = false; //if any words match, eval to false
j++;
}

if (isUnique = true) //Only if state remains true, add raw word to uniques
uniqueWords.add(allWords.get(i));
i++;
}
}

我需要知道是否有更合适/有效的方法来设置我的类,以及 uniquewords.add() 是否有原因无法在 removeRepeats() 方法的第二行中工作。

谢谢。

最佳答案

您的一些问题:

uniqueWords.add(0) = allWords.get(0);

在这里,您将一个整数 0 添加到字符串的 ArrayList 中。您可能想要:

uniqueWords.add(allWords.get(0));

此外,稍后您将字符串与 == 进行比较:

if (allWords.get(i) == uniqueWords.get(j))

== 仅应在比较原始数据类型时使用。要比较字符串,请使用 equals(String) 或 equalsIgnoreCase(String) 方法:

if (allWords.get(i).equalsIgnoreCase(uniqueWords.get(j))

关于java - 基本java中存在导入、类困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31189133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com