Java 我需要打印字符串数组中的所有唯一单词,但不确定如何打印
因此,完整的程序从文件中读取一个故事,并将每个单词存储在字符串数组中。阅读完故事后,我需要打印故事中所有独特的单词,但我不知道如何打印。这是我的Java 我需要打印字符串数组中的所有唯一单词,但不确定如何打印,java,Java,因此,完整的程序从文件中读取一个故事,并将每个单词存储在字符串数组中。阅读完故事后,我需要打印故事中所有独特的单词,但我不知道如何打印。这是我的 import java.util.*; import csci1140.*; import java.io.*; public class Story{ public static final void main(String[] args){ String[] storyArray = new String[28203];
import java.util.*;
import csci1140.*;
import java.io.*;
public class Story{
public static final void main(String[] args){
String[] storyArray = new String[28203];
String fileName = "MultiLineStory.txt";
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(fileName));
}catch(FileNotFoundException fnfe){
System.out.println("Unable to find file: " + fileName);
}
try{
String input = null;
for(int i = 0; i < storyArray.length; i++){
if((input = reader.readLine()) != null){
String fill = input;
storyArray[i] = fill;
}
// System.out.print(storyArray[i] + " ");
}
} catch(IOException ioe){
ioe.printStackTrace(System.err);
} finally {
try{
reader.close();
}catch(Exception e){}
}
long start = System.nanoTime();
Arrays.sort(storyArray);
long end = System.nanoTime();
System.out.println("\n\nArrays.sort took " +((end - start)/1E9) + " Sec");
distinctValues(storyArray);
}
public static boolean distinctValues(String[] array){
int count = 0;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] == array[i + 1]) {
count++;
return true;
}
}
System.out.println(count);
return false;
}
}您可以使用哈希集并将数组的所有元素放入其中。然后一个接一个地打印出来
String[] allWordsArray = ...;
HashSet<String> uniqueWordsSet = new HashSet<>(Arrays.asList(allWordsArray));
for (String word : uniqueWordsSet)
{
System.out.println(word);
}
试试这个:
package com;
import java.util.*;
import java.io.*;
/*to print unique words which are not repeated*/
public class UniqueWords {
public static final void main(String[] args){
ArrayList<String> allWords = new ArrayList<String>();
Map<String, Integer> map = new HashMap<String, Integer>();
String fileName = "C:\\TestFiles\\MultiLineStory.txt";
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(fileName));
String input = null;
if((input = reader.readLine()) != null){
String arr[] = input.split(" ");
allWords.addAll(Arrays.asList(arr));
}
System.out.println(allWords.size());
}catch(FileNotFoundException fnfe){
System.out.println("Unable to find file: " + fileName);
} catch(IOException ioe){
ioe.printStackTrace(System.err);
} finally {
try{
reader.close();
}catch(Exception e){}
}
for(String word : allWords)
{
if(!map.containsKey(word))
map.put(word, 1);
else
map.put(word, map.get(word)+1);
}
Set<String> keySet = map.keySet();
for(String key : keySet)
if(map.get(key)==1)
System.out.println(key);
}
}
Java之于Javascript,犹如痛苦之于绘画,火腿之于仓鼠。他们完全不同。强烈建议有抱负的程序员尝试学习他们试图编写代码的语言的名称。发布问题时,请适当标记。忽略数组并查看哈希集是什么。从文件中读取故事并将每个单词存储在字符串数组中。否。此代码将故事的每一行存储在数组中。在.txt文件中,故事的每一个单词都是它自己的行。为什么只有数组?你不能使用集合吗?还请共享几行文件以及预期的输出。