This question already has answers here:
Why does println(array) have strange output? ("[Ljava.lang.String;#3e25a5") [duplicate]
(6 answers)
Closed 8 years ago.
What does this mean?
I am trying to print an array pf strings that is about 570,000 strings long...I believe that is what this relates to.
It prints out when I run my program. Ignore the commented out code; this program is a work in progress.
package nGram;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
public class HashMapFun {
public static void main(String[] agrs) throws FileNotFoundException {
HashMap <String, Integer> wordFrequency = new HashMap <String, Integer> ();
String bookContent = getFile("AtlasShrugged.txt");
//Remove punctuation marks from string "bookContent"
//Split the words using spaces
String[] words = bookContent.split(" ");
System.out.println(words);
// bookContent.replace(".", "");
// bookContent.replace("!", "");
// bookContent.replace("?", "");
// bookContent.replace("(", "");
// bookContent.replace(")", "");
// bookContent.replace("-", "");
// bookContent.replace(";", "");
//Go to every word in the list
for (String word : words) {
//If I have already added the word to the frequency map
if (wordFrequency.containsKey(word)) {
int freq = wordFrequency.get(word);
freq = freq + 1;
wordFrequency.put(word, freq );
}
else {
//If not, add to HashMap
wordFrequency.put(word, 1);
}
}
// Iterator iterator = wordFrequency.keySet().iterator();
//
// while (iterator.hasNext()) {
// String key = iterator.next().toString();
// String value = wordFrequency.get(key).toString();
//
// System.out.println(key + " " + value);
// PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
// System.setOut(out);
}
//}
public static String getFile(String path) {
// Make a File object to represent this file at the path
File f = new File(path);
// Do the code in the try, and if it fails do the catch code
try {
// Make a scanner to read the file
Scanner fileScanner = new Scanner(f);
// Make a StringBuilder to create the file content
StringBuilder content = new StringBuilder();
// While the file scanner still has a line of input
while (fileScanner.hasNextLine()) {
// Append the next line of file input
content.append(fileScanner.nextLine());
// Append a newline character.
content.append("\n");
}
// Return whatever is in the StringBuilder
return content.toString();
}
// Catch any error that may occur in the above try statement
catch (FileNotFoundException e) {
System.out.println("Didn't find the file.");
}
return ""; // If all else fails, return an empty string.
}
}
java.lang.String;#50f6d9ca
What that means is that you are trying to print the memory location that was allocated from your words array which was printed here:
System.out.println(words);
You are printing a string array, not a string.
This is just the way Java prints arrays. To see each string, try
Arrays.toString(yourArray)
By the way, see this Stack Overflow answer to see the reason why you are seeing what you are seeing.
Related
I am working on an assignment in which the program needs to read a file located by user input.
The file is scanned and an array is created.
The array stores in words as strings and outputs how many times a word has been used.
Then, the output is printed out into a new file.
package TestFileReader;
import java.io.*;
import java.util.*;
public class ReadFile
{
public static void main(String[] args)
{
//Prompts user for file by asking for its location
Scanner keys = new Scanner(System.in);
String fileName;
System.out.print("Enter file location, or 'Quit' to quit: ");
fileName = keys.nextLine();
Scanner textFile = null;
//try catch block for exception
try
{
textFile = new Scanner(new File(fileName));
}
catch(FileNotFoundException s)
{
System.out.println("File not found, confirm location: ");
}
//File will be read continuously until there is no next line
while(textFile.hasNextLine())
{
String contents = textFile.nextLine();
System.out.println(contents);
}
textFile.close();
//New Class for saving read into array
}
}
While I prepared the following example, Jan also answered properly that a HashMap can be used for this job:
HashMap<String,Integer> map=new HashMap<String,Integer>();
//File will be read continuously until there is no next line
while(textFile.hasNextLine())
{
String line = textFile.nextLine();
// Split line into words
String words[]=line.split("\\s+");
for (String word : words)
{
// Get current word count
Integer count=map.get(word);
if (count==null)
{
// Create a new counter for a new word
map.put(word,1);
}
else
{
// Increase existing word counter
map.put(word,count+1);
}
}
}
// Output result
for (Map.Entry<String,Integer> entry : map.entrySet())
{
System.out.println(entry.getKey()+": "+entry.getValue());
}
textFile.close();
The HashMap gets filled with an Integer counter for each word. If the word is found again, the counter will be increased. HashMaps are usually faster than nested loops over an array when you expect more than 20 entries.
Example inout file:
This is a test
This is another test
Wuff!
Example output:
a: 1
Wuff!: 1
test: 2
another: 1
This: 2
is: 2
Since Java 8 you could also use the Streams API to accomplish this task.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ReadFile {
public static void main(String[] args) {
//Prompts user for file by asking for its location
Scanner keys = new Scanner(System.in);
String fileName;
System.out.print("Enter file location, or 'Quit' to quit: ");
fileName = keys.nextLine();
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.flatMap(s -> Stream.of(s.split("\\W")))
.filter(s -> s != null && !s.isEmpty())
.collect(Collectors.toMap(s -> s, s -> 1, Integer::sum))
.forEach((k, v) -> System.out.println(k + ": " + v));
} catch (IOException e) {
System.out.println("Cannot read file: " + fileName);
}
}
}
I'm trying to concatenate strings in new lines when a condition is met. This is my input:
Concept
soft top cove
tonneau cove
interior persennin
Concept
Innen
Innenraum
Platz im Inneren
All I want to do is to concatenate all the strings after the string concept and to get the following output:
lemma, surface
soft top cove, tonneau cove|interior persennin
Innen, Innenraum|Platz im Inneren
I know if a string value is equal concept I want to go to the other line and write the string of the next line before a comma, than the strings from the other lines delimited by "|" e.g. soft top cove, tonneau cove|interior persenning
This is my code so far. Any suggestions are welcome!
Thank you:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class Converter {
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader inputcsv = null;
List <String> zeilencsv = new ArrayList<String>();
try {
inputcsv = Files.newBufferedReader(Paths.get("ErsteDatei.csv"));
String content;
while ((content = inputcsv.readLine()) != null) {
zeilencsv.add(content);
System.out.println(content);
}
File outputcsv = new File("TwoColumnsResult.csv");
//creates new file
outputcsv.createNewFile();
FileWriter csvFilewriter = new FileWriter(outputcsv);
//arraylist loop
int counter_a=0;
int counter = 1;
for (String zeile:zeilencsv){
String concept = "Concept";
//check string value =concept?
if(zeile.toString().equals(concept)){
zeile="lemma,surface";
for(String zeile2:zeilencsv){
//here I don't know how to say give me the next line, write it as a word , put comma and than concatenate with a |
}
}
else {
counter++;
}
csvFilewriter.write(zeile+"\n");
counter++;
}
//write
csvFilewriter.flush();
//closes the file
csvFilewriter.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
so if I understood correctly you want that after finding "Concept" save the next line as text, concatenate a comma, then save the next line and concatenate a | and then save the next?
Well the code that you're using is kind of bizarre but what I would do is the next:
zeile="lemma,surface";
// I'll put a counter to distinguish where to put "," and "|"
int counter = 0;
// Then I need a string variable to save the line
String line = "";
for(String zeile2:zeilencsv){
if (count == 0){ //First iteration
line = zeile2.toString();
}
if(count == 1){ . //Second iteration add the comma
line = line + "," + zeile2.toString();
}
if(count == 2){ . //Second iteration add the pipe
line = line + "|" + zeile2.toString();
}
count++;
}
I hope that this is what you're looking for. If you would like to optimize the code, feel free to send me a message and we could work together.
I have to write code that will reverse the order of the string and write it in a new file. For example :
Hi my name is Bob.
I am ten years old.
The reversed will be :
I am ten years old.
Hi my name is Bob.
This is what I have so far. Not sure what to write for the outWriter print statement. Any help will be appreciated. Thanks!
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class FileRewinder {
public static void main(String[] args) {
File inputFile = new File("ascii.txt");
ArrayList<String> list1 = new ArrayList<String>();
Scanner inputScanner;
try {
inputScanner = new Scanner(inputFile);
} catch (FileNotFoundException f) {
System.out.println("File not found :" + f);
return;
}
while (inputScanner.hasNextLine()) {
String curLine = inputScanner .nextLine();
System.out.println(curLine );
}
inputScanner.close();
File outputFile = new File("hi.txt");
PrintWriter outWriter = null;
try {
outWriter = new PrintWriter(outputFile);
} catch (FileNotFoundException e) {
System.out.println("File not found :" + e);
return;
}
outWriter.println(???);
outWriter.close();
}
}
My suggestion is read entire file first and store sentences(you can split by .) in a LinkedList<String>(this will keep insertion order)
Then use Iterator and get sentences in reverse order. and write them into a file. make sure to put . just after each sentence.
After System.out.println(curLine ); add list1.add(curline); that will place your lines of text into your list.
At the end create a loop over list1 backwards:
for(int i = list1.size() - 1 , i > 0, --i) {
outWriter.println(list1[i]);
}
If the file contains an amount of lines which can be loaded into the memory. You can read all lines into a list, reverse the order of the list and write the list back to the disk.
public class Reverse {
static final Charset FILE_ENCODING = StandardCharsets.UTF_8;
public static void main(String[] args) throws IOException {
List<String> inLines = Files.readAllLines(Paths.get("ascii.txt"), FILE_ENCODING);
Collections.reverse(inLines);
Files.write(Paths.get("hi.txt"), inLines, FILE_ENCODING);
}
}
My bad for the title, I am usually not good at making those.
I have a programme that will generate all permutations of an inputted word and that is supposed to check to see if those are words (checks dictionary), and output the ones that are. Really I just need the last the part and I can not figure out how to parse through a file.
I took out what was there (now displaying the "String words =") because it really made thing worse (was an if statement). Right now, all it will do is output all permutations.
Edit: I should add that the try/catch was added in when I tried turning the file in a list (as opposed to the string format which it is currently in). So right now it does nothing.
One more thing: is it possible (well how, really) to get the permutations to display permutations with lesser characters than entered ? Sorry for the bad wording, like if I enter five characters, show all five character permutations, and four, and three, and two, and one.
import java.util.List;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import static java.lang.System.out;
public class Permutations
{
public static void main(String[] args) throws Exception
{
out.println("Enter anything to get permutations: ");
Scanner scan = new Scanner(System.in);
String io = scan.nextLine();
String str = io;
StringBuffer strBuf = new StringBuffer(str);
mutate(strBuf,str.length());
}
private static void mutate(StringBuffer str, int index)
{
try
{
String words = FileUtils.readFileToString(new File("wordsEn.txt"));
if(index <= 0)
{
out.println(str);
}
else
{
mutate(str, index - 1);
int currLoc = str.length()-index;
for (int i = currLoc + 1; i < str.length(); i++)
{
change(str, currLoc, i);
mutate(str, index - 1);
change(str, i, currLoc);
}
}
}
catch(IOException e)
{
out.println("Your search found no results");
}
}
private static void change(StringBuffer str, int loc1, int loc2)
{
char t1 = str.charAt(loc1);
str.setCharAt(loc1, str.charAt(loc2));
str.setCharAt(loc2, t1);
}
}
If each word in your file is actually on a different line, maybe you can try this:
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null)
{
... // check and print here
}
Or if you want to try something else, the Apache Commons IO library has something called LineIterator.
An Iterator over the lines in a Reader.
LineIterator holds a reference to an open Reader. When you have finished with the iterator you should close the reader to free internal resources. This can be done by closing the reader directly, or by calling the close() or closeQuietly(LineIterator) method on the iterator.
The recommended usage pattern is:
LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
} finally {
it.close();
}
I have this programming assignment and it is the first time in our class that we are writing code in Java. I have asked my instructor and could not get any help.
The program needs to count word pairs from a file, and display them like this:
abc:
hec, 1
That means that there was only one time in the text file that "abc" was followed by "hec". I have to use the Collections Framework in java. Here is what I have so far.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ArrayList;
// By default, this code will get its input data from the Java standard input,
// java.lang.System.in. To allow input to come from a file instead, which can be
// useful when debugging your code, you can provide a file name as the first
// command line argument. When you do this, the input data will come from the
// named file instead. If the input file is in the project directory, you will
// not need to provide any path information.
//
// In BlueJ, specify the command line argument when you call main().
//
// In Eclipse, specify the command line argument in the project's "Run Configuration."
public class Assignment1
{
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName)
{
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
System.err.println(e.getMessage());
inputStream = null;
}
return inputStream;
}
public static void main(String[] args)
{
// Create an input stream for reading the data. The default is
// System.in (which is the keyboard). If there is an arg provided
// on the command line then we'll use the file instead.
InputStream in = System.in;
if (args.length >= 1) {
in = getFileInputStream(args[0]);
}
// Now that we know where the data is coming from we'll start processing.
// Notice that getFileInputStream could have generated an error and left "in"
// as null. We should check that here and avoid trying to process the stream
// data if there was an error.
if (in != null) {
// Using a Scanner object to read one word at a time from the input stream.
#SuppressWarnings("resource")
Scanner sc = new Scanner(in);
String word;
System.out.printf("CS261 - Assignment 1 - Matheus Konzen Iser%n%n");
// Continue getting words until we reach the end of input
List<String> inputWords = new ArrayList<String>();
Map<String, List<String>> result = new HashMap<String, List<String>>();
while (sc.hasNext()) {
word = sc.next();
if (!word.equals("---")) {
// do something with each word in the input
// replace this line with your code (probably more than one line of code)
inputWords.add(word);
}
for(int i = 0; i < inputWords.size() - 1; i++){
// Create references to this word and next word:
String thisWord = inputWords.get(i);
String nextWord = inputWords.get(i+1);
// If this word is not in the result Map yet,
// then add it and create a new empy list for it.
if(!result.containsKey(thisWord)){
result.put(thisWord, new ArrayList<String>());
}
// Add nextWord to the list of adjacent words to thisWord:
result.get(thisWord).add(nextWord);
}
//OUTPUT
for(Entry e : result.entrySet()){
System.out.println(e.getKey() + ":");
// Count the number of unique instances in the list:
Map<String, Integer>count = new HashMap<String, Integer>();
List<String>words = (List)e.getValue();
for(String s : words){
if(!count.containsKey(s)){
count.put(s, 1);
}
else{
count.put(s, count.get(s) + 1);
}
}
// Print the occurances of following symbols:
for(Entry f : count.entrySet()){
System.out.println(" " + f.getKey() + ", " + f.getValue());
}
}
}
System.out.printf("%nbye...%n");
}
}
}
The problem that I'm having now is that it is running through the loop below way too many times:
if (!word.equals("---")) {
// do something with each word in the input
// replace this line with your code (probably more than one line of code)
inputWords.add(word);
}
Does anyone have any ideas or tips on this?
I find this part confusing:
while (sc.hasNext()) {
word = sc.next();
if (!word.equals("---")) {
// do something with each word in the input
// replace this line with your code (probably more than one line of code)
inputWords.add(word);
}
for(int i = 0; i < inputWords.size() - 1; i++){
I think you probably mean something more like this:
// Add all words (other than "---") into inputWords
while (sc.hasNext()) {
word = sc.next();
if (!word.equals("---")) {
inputWords.add(word);
}
}
// Now iterate over inputWords and process each word one-by-one
for (int i = 0; i < inputWords.size(); i++) {
It looks like you're trying to read all the words into inputWords first and then process them, while your code iterates through the list after every word that you add.
Note also that your condition in the for loop is overly-conservative, so you'll miss the last word. Removing the - 1 will give you an index for each word.