java cannot find symbol method [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
1st
import java.io.*;
import java.util.*;
public class MyFile {
public String[] readFiles(String FileName){
String[] names = new String[]{};
String line = null;
try{
FileReader fileReader = new FileReader(FileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
for(int i = 0;(line = bufferedReader.readLine()) != null;i++) {
names[i] = line;
}
bufferedReader.close();
}
catch(IOException ex){
ex.printStackTrace();
}
return names;
}
public static void write(String FileName,String[] names){
try{
FileWriter fileWriter = new FileWriter(FileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
for(int i = 0; i<names.length ; i++)
{
bufferedWriter.write(names[i]);
bufferedWriter.newLine();
}
bufferedWriter.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}
public MyFile(){System.out.println("");}
}
2nd
public class Book{
public void displayAll(){
String[] bookNames;
String filename = "Books.txt";
bookNames = readFiles(filename);
for(int i=0;i<bookNames.length;i++)
{
System.out.println(""+bookNames[i]);
}
}
}
I'm a beginner in java and I am trying to create a program that will save and read books' name from a txt file.
but i get this error
Book.java:12: cannot find symbol
symbol: method readFiles(java.lang.String)
location:class com.acme.Book
bookNames = readFiles(filename);
^
i did tried to search but i just couldn't find any answer... and by the way not all of the code is written by me..
updated the mistkae (readFiles)

bookNames = readFile(filename);
You don't have readFile() method you have readFiles() method. s is missing in the end.
That should be
bookNames = readFiles(filename);

The method name is a plural
readFiles
not
readFile

You got
public String[] readFiles(String FileName){}
But you are calling
bookNames = readFile(filename); // readFile() ? should be readFiles()
You can do one of following to solve this
Change
bookNames = readFile(filename);
in to
bookNames = readFiles(filename);
Or
Change
public String[] readFiles(String FileName){}
in to
public String[] readFile(String FileName){}

as everyone meantion, you defined method readFiles and you are calling method readFile
Worth to meantion as wel, your method readFiles is defined in class MyFile while you are trying to access it from class Book which is impossible unless Book is inner class of MyFile (but this will be bad design).

Related

Java HashTable: contains key can't find existing key [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Imagining I have a dictionary.csv file:
"apple", "n.", "a red fruit"
"exercise", "n.", "sport"
"exercise", "v.", "play sport"
I have read it into type Hashtable<String, ArrayList<ArrayList>>:
content = {"apple":[["n", "a red fruit"]], "exercise"=[["n.", "sport"],["v.", "play sport"]]}
However, content.containsKey("apple") returns false. I tried hashmap and concurrentHashMap, not working as well.
Below is my code for Dictionary class.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
public class Dictionary {
private String filename;
private Hashtable<String, ArrayList<ArrayList<String>>> content = new Hashtable<>();
public Dictionary(String filename) throws FileNotFoundException {
// set the file name
this.filename = filename;
// read dictionary file into content
try (BufferedReader br = new BufferedReader((new FileReader(filename)))) {
String line;
// read every line
while ((line = br.readLine()) != null){
String[] values = line.split(",");
assert(values.length == 3);
// split word,
String word = values[0].toLowerCase();
ArrayList<String> meaning = new ArrayList<>();
meaning.add(values[1]);
meaning.add(values[2]);
// add word and meaning to the content
if (content.containsKey(word)){
ArrayList newMeanings = content.get(word);
newMeanings.add(meaning);
content.put(word, newMeanings);
}
else {
ArrayList<ArrayList<String>> meanings = new ArrayList<>();
meanings.add(meaning);
content.put(word, meanings);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void getMeaning(String rawWord){
String word = rawWord.toLowerCase();
if (content.containsKey(word)){
ArrayList<ArrayList<String>> meanings = content.get(word);
int numMeanings = meanings.size();
for (int i = 0; i < numMeanings; i++){
String[] meaningLst = (String[]) meanings.get(i).toArray();
System.out.println("Meaning " + (i+1) + ": " + meaningLst[0] + ". " + meaningLst[1]);
}
}
else {
System.out.println("Word not found");
}
}
}
Below is my code in Main class.
import java.io.FileNotFoundException;
public class Main {
public static void main(String ars[]) throws FileNotFoundException {
Dictionary dictionary = new Dictionary("dictionary.csv");
dictionary.getMeaning("apple");
}
}
I think you are inserting "apple" as a key and not apple. Remove double quotes.
Change:
String word = values[0].toLowerCase();
To:
String word = values[0].toLowerCase();
word = word.substring(1, word.length()-1);
Hi The issue is with the input it should be content.containsKey("\"apple\"") not
content.containsKey("apple") or kindly remove the " in the dictionary.csv file.

How to replace a line with something? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So my program needs to overwrite e.g line 5 in a file. Just the 5th line, keep the others.
We don't know what is the content of line 5.
But I have no idea how to do it, can't found anything about how to do this with BufferedWriter and FileWriter.
I can't write there a code, because.. I just don't know how to do it.:/
A sample solution could look like this
package teststuff;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Btest {
public static void main(String args[])
{
try
{
File file = new File("test.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "", fivthLine = "";
int x=0;
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
if(x == 4)
{
fivthLine = line;
}
x++;
}
reader.close();
String newtext = oldtext.replaceAll(fivthLine, "blah blah blah");
FileWriter writer = new FileWriter("test.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Note that this is a combination of what Emmanuel wrote and this
It will also replace whats written in the 5th line everywhere on the file, so that another line containing the same content of line 5 will also be overwritten with
"blah blah blah"
by first you can start looking for "How to count lines on a file" like this i found
https://www.geeksforgeeks.org/counting-number-lines-words-characters-paragraphs-text-file-using-java/
Then add counter++ each time you pass a line, when (counter == 5)
then do whatever you need to do..
This is a very simple example of replacing a given line in a file:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class LineReplaceTest
{
public static void main(String... args)
throws Exception
{
int lineToReplace = 5;
String replacementText = "This is a different line";
Path input = Paths.get("input.txt");
Path output = Paths.get("output.txt");
// Use try-with-resources to ensure our readers & writers are closed
try (BufferedReader reader = Files.newBufferedReader(input);
BufferedWriter writer = Files.newBufferedWriter(output)) {
String line;
int lineNumber = 0;
// While there is a line to read from input...
while ((line = reader.readLine()) != null) {
lineNumber++;
// Write out either the line from the input file or our replacement line
if (lineNumber == lineToReplace) {
writer.write(replacementText);
} else {
writer.write(line);
}
writer.newLine();
}
}
// Once we're done, overwrite the input file
Files.move(output, input);
}
}
It ignores several important things line error handling and platform-specific newline handling, but it should at least get you started.

BufferedReader/Writer not working in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I'm trying to make two basic functions which will allow me to call them from other classes in order to return a HashMap from the 'getAllData()' and to write to the file in 'writeToFile()', without any luck. I've been tampering with it for a while now and just getting a multitude of strange errors.
Code:
static HashMap<Integer ,String> getAllData(Integer choice) throws Exception{
InputStream localInputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("Shadow.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(localInputStream));
if (choice.equals(1)){
while ((!data.equals(null))){
data = br.readLine();
dataString = dataString+data;
}
writeToFile(dataString);
br.close();
}return name;
}
static void writeToFile(String data) throws IOException{;
File file = new File ("Shadow.txt");
FileWriter fileWriter = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fileWriter);
bw.write(data);
bw.newLine();
bw.flush();
bw.close();
}
With this current code, nothing happens. The file remains exactly how it is, although to me, the code should read everything from it, and then append it.
How can I fix this?
Thanks
This might help you:
static void getAllData(final Integer choice) throws Exception {
final BufferedReader br = new BufferedReader(new FileReader("Shadow.txt"));
String data = "";
final StringBuilder builder = new StringBuilder();
if(choice.equals(1)) {
while(data != null) {
data = br.readLine();
if(data != null) {
builder.append(data + "\n");
}
}
writeToFile(builder.toString());
br.close();
}
}
static void writeToFile(final String data) throws IOException {
final File file = new File("Shadow.txt");
final FileWriter fileWriter = new FileWriter(file, true);
final BufferedWriter bw = new BufferedWriter(fileWriter);
bw.write(data);
bw.flush();
bw.close();
}

why doesn't my file delete no matter why I do? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
public void removeLine(String s) throws IOException, FileNotFoundException{
File tempFile = new File("temp.txt");
FileInputStream reader = new FileInputStream(sharkFile);
Scanner scanner = new Scanner(reader);
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile, true));
String currentLine;
while(scanner.hasNextLine()){
currentLine = scanner.nextLine();
String trimmedLine = currentLine.trim();
System.out.println(trimmedLine);
trimmedLine.equals(sharkName);
if(trimmedLine.equals(sharkName)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
scanner.close();
scanner = null;
reader.close();
writer.flush();
writer.close();
writer = null;
System.gc();
if(!sharkFile.delete()){
System.out.println("Could not delete file d");
return;
}
if(!tempFile.renameTo(sharkFile)){
System.out.println("Could not rename file");
return;
}
}
I've gone through numerous threads on stackoverflow and have implemented those changes but my file just won't delete. Appreciate the help.
The File API is notoriously weak on explaining why something fail, e.g. File.delete() simply returns a boolean, and value false cannot explain why.
Use the new Path API instead.
Also, please (PLEASE!) use try-with-resources.
Scanner is slow, so better to use BufferedReader, and for writing the lines back with newlines, use a PrintWriter.
Path sharkPath = sharkFile.toPath();
Path tempPath = Paths.get("temp.txt");
Charset cs = Charset.defaultCharset();
try (BufferedReader reader = Files.newBufferedReader(sharkPath, cs);
PrintWriter writer = new PrintWriter(Files.newBufferedWriter(tempPath, cs, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)))) {
for (String currentLine; (currentLine = reader.readLine()) != null; ) {
String trimmedLine = currentLine.trim();
System.out.println(trimmedLine);
if (! trimmedLine.equals(sharkName))
writer.println(currentLine);
}
}
Files.delete(sharkPath); // throws descriptive exception if cannot delete
Files.move(tempPath, sharkPath); // throws exception if cannot move
Use below code, rename file before delete, it's appearing that you are accessing file name after delete:
try { //rename file first
tempFile.renameTo(sharkFile);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Unable to rename.");
}
try {
sharkFile.delete();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, "Unable to delete.");
}

File input/output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Ive been asked my current program to be saved into a file so it can be continued later even if the program end. However I am new to java, so I Would really appreciate if someone can help me on this :) This is the code i manage to get done, however it just creates an empty file,how am I suppose to go about this problem?
Below is not the whole program coding, i've just copied the codes that is relevant.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileWriter;
public static void main (String[] param) throws FileNotFoundException
{
try
{
fileinputoutput ();
}
catch (FileNotFoundException e)
{
System.exit(0);
}
} // END main
public static void fileinputoutput() throws FileNotFoundException
{
File input = new File("input.txt");
File output = new File("loveletter.txt");
PrintWriter outputFile = new PrintWriter(output);
Scanner check = new Scanner(System.in);
String filename = check.nextLine();
File inputfile = new File(filename);
Scanner newfile = new Scanner(inputfile);
newfile.close();
while(newfile.hasNext())
{
String write = newfile.nextLine();
System.out.println(write);
}
outputFile.close();
}
The answer is pretty obvious. The reason why you only get a blank file is that you never write anything through outputFile and close newfile before you can do anything with it. You should try something like this:
public static void fileinputoutput() throws FileNotFoundException {
File input = new File("input.txt"); // What do you use this variable for? It's never used in the code fragment you posted
File output = new File("loveletter.txt");
PrintWriter outputFile = new FileWriter(output); // I'd personally use FileWriter here
Scanner check = new Scanner(System.in);
String filename = check.nextLine();
File inputFile = new File(filename);
Scanner newfile = new Scanner(inputFile);
while(newfile.hasNext()) {
String write = newfile.nextLine();
outputFile.println(write); // You used to only output something to the console here
}
outputFile.close();
newfile.close();
check.close();
}

Categories

Resources