I'm attempting collect all the methods in a Java file using the Eclipse AST package. I believe that I have the CompilationUnit created successfully. However when I attempt to use a visitor to collect the information it doesn't go past the main() method of the file I'm testing.
public void parseCode(String fileName) {
String strSource = "";
try {
strSource = codeToString(fileName);
} catch (Exception e) {
e.printStackTrace();
}
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setSource(strSource.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(new NullProgressMonitor());
SCTVisitor v = new SCTVisitor();
cu.accept(v);
System.out.println(v.m);
}
public class SCTVisitor extends ASTVisitor{
List<SimpleName> m = new ArrayList<SimpleName>();
SCTVisitor(){
System.out.println("What is love");
}
#Override public boolean visit(MethodInvocation node) {
this.m.add(node.getName());
return true;
}
}
This is part of the file I'm using to test:
import java.util.Map;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
public class WordCount {
public static void main(String[] args) {
System.out.println("Cheese");
countWordsViaGUI();
}
// allow user to pick file to exam via GUI.
// allow multiple picks
public static void countWordsViaGUI() {
setLookAndFeel();
try {
Scanner key = new Scanner(System.in);
do {
System.out.println("Opening GUI to choose file.");
Scanner fileScanner = new Scanner(getFile());
Stopwatch st = new Stopwatch();
st.start();
ArrayList<String> words = countWordsWithArrayList(fileScanner);
st.stop();
System.out.println("time to count: " + st);
System.out.print("Enter number of words to display: ");
int numWordsToShow = Integer.parseInt(key.nextLine());
showWords(words, numWordsToShow);
fileScanner.close();
System.out.print("Perform another count? ");
} while(key.nextLine().toLowerCase().charAt(0) == 'y');
key.close();
}
catch(FileNotFoundException e) {
System.out.println("Problem reading the data file. Exiting the program." + e);
}
}
My results are:
[println, countWordsViaGUI]
My expected results are:
[println, countWordsViaGUI, setLookAndFeel, scanner, println, getFile, Scanner, ...]
Please let me know if you have any insight into this problem.
Related
I'm writing a ChatBot program where, if the ChatBot doesn't have information to answer a question by the user, it asks the user how to answer the question, and then stores it in a txt file. Later, when another question is asked, the information is retrieved from the txt file and the whole thing starts over (or at least is supposed to).
The program works, however, after one query from the user, and I press enter again for a second try, nothing happens anymore.
Here is my code:
import java.io.*;
import java.util.*;
import java.nio.file.*;
import java.util.stream.Stream;
public class Main {
public static void main(String args[]) {
System.out.println("Bot: Hello!! My name's HiBot! What's up?");
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
if (response.toLowerCase().contains("bye") || response.toLowerCase().contains("see ya")
|| response.toLowerCase().contains("gtg")) {
System.out.println("Bot: Ok, see ya. Nice talking to you!");
}
processor(response);
}
public static void processor(String reply) {
try {
BufferedReader reader = new BufferedReader(new FileReader("convos.txt"));
int count = 0;
try {
String line = reader.readLine();
while (line != null) {
count++;
if (line.toLowerCase().contains(reply.toLowerCase())) {
try (Stream<String> lines = Files.lines(Paths.get("convos.txt"))) {
line = lines.skip(count).findFirst().get();
System.out.println("Bot: " + line);
recur();
} catch (IOException e) {
System.out.println("Bot: Something happened π\n" + e);
}
reader.close();
return;
}
reader.close();
}
System.out.println("Bot: Sorry, I'm dumb. How should I reply?");
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
teach(reply, response);
recur();
} catch (IOException e) {
System.out.println("Bot: Something happened π\n" + e);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void teach(String context, String reply) {
try {
try {
FileWriter learn = new FileWriter("convos.txt", true);
PrintWriter out = new PrintWriter(learn);
out.println(context + "\n" + reply);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
System.out.println("Bot: Something happened π\n" + e);
}
System.out.println("Bot: Thank you for teaching me!! I'm smarter now!");
}
public static void recur() {
int trickLoop = 1;
while (trickLoop > 0) {
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
if (response.toLowerCase().contains("bye") || response.toLowerCase().contains("see ya")
|| response.toLowerCase().contains("gtg")) {
System.out.println("Bot: Ok, see ya. Nice talking to you!");
System.exit(0);
}
processor(response);
}
}
}
I also think that there's definitely a better way to write the code. Does anyone have any suggestions?
EDIT: I have convos.txt but I didn't show it here.
Issue1 :
Initially file doesn't exist and you are not creating it. so it gave following error
Bot: Hello!! My name's HiBot! What's up?
You: hi
java.io.FileNotFoundException: convos.txt (The system cannot find the file specified)
Issue 2 :
You are doing recursion using recur method which can be risky here in the case of continuous inputs as your resources will not be closed right away and can result into further resource starvation issues.
You can simply use infinite while loop.
Improvement1 :
Don't you think that once user inputs bye/see ya/gtg program should close ?
Improvement2 :
Repeated calls to string.toLowerCase() in main method.
Improvement3 :
This line line = lines.skip(count).findFirst().get(); can result into NoSuchElementException
I have added improvement 2 and 3 in the below code.
Here i updated the code below which works as per your details in the question
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.stream.Stream;
public class Main {
public static void main(String args[]) {
System.out.println("Bot: Hello!! My name's HiBot! What's up?");
while (true) {
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
String lowercaseResponse = response.toLowerCase();
if (lowercaseResponse.contains("bye") || lowercaseResponse.contains("see ya")
|| lowercaseResponse.contains("gtg")) {
System.out.println("Bot: Ok, see ya. Nice talking to you!");
}
processor(response);
}
}
public static void processor(String reply) {
BufferedReader reader = null;
try {
File file = new File("convos.txt");
if (file.createNewFile())
System.out.println("Conversations file created");
reader = new BufferedReader(new FileReader(file.getName()));
int count = 0;
String line = reader.readLine();
while (line != null) {
count++;
if (line.toLowerCase().contains(reply.toLowerCase())) {
try (Stream<String> lines = Files.lines(Paths.get("convos.txt"))) {
line = lines.skip(count).findFirst().map(Object::toString).orElse("I don't know how to respond");
System.out.println("Bot: " + line);
} catch (IOException e) {
System.out.println("Bot: Something happened while reading conversation file π\n" + e);
}
reader.close();
return;
}
line = reader.readLine();
}
reader.close();
System.out.println("Bot: Sorry, I'm dumb. How should I reply?");
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
teach(reply, response);
} catch (FileNotFoundException e) {
System.out.println("Bot: File not found π\n" + e);
} catch (IOException e) {
System.out.println("Bot: Something happened π\n" + e);
} finally {
try {
reader.close();
} catch (IOException e) {
System.out.println("Bot: Something happened while closing the file reader π\n" + e);
}
}
}
public static void teach(String context, String reply) {
try {
try {
FileWriter learn = new FileWriter("convos.txt", true);
PrintWriter out = new PrintWriter(learn);
out.println(context + "\n" + reply);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
System.out.println("Bot: Something happened π\n" + e);
}
System.out.println("Bot: Thank you for teaching me!! I'm smarter now!");
}
}
Output : For the first time
Bot: Hello!! My name's HiBot! What's up?
You: hi
Conversations file created
Bot: Sorry, I'm dumb. How should I reply?
You: hello
Bot: Thank you for teaching me!! I'm smarter now!
You:
hi
Bot: hello
You:
Output : When Convos.txt is created already
Bot: Hello!! My name's HiBot! What's up?
You: hi
Bot: hello
You: hi
Bot: hello
You: hi
Bot: hello
You:
Let me know if i missed anything.
I saw this question because someone edited the question.
Here's one test run. The "convos.txt" file exists and has a couple of response / reply text lines.
Bot: Hello! My name's HiBot! What's up?
You: hi
Bot: Hi
You: how are you
Bot: Fine. How are you?
You: Good
Bot: Sorry, I'm ignorant. How should I reply?
You: That's good to hear.
Bot: Thank you for teaching me a new reply! I'm smarter now!
You: bye
Bot: Ok, see ya. Nice talking to you!
I eliminated the multiple System.in Scanner instances. In the reorganized code, I only needed one Scanner instance. There should only be one System.in Scanner instance in your code.
I created a separate ResponseMap class to hold a HashMap for the response / reply text.
I created a separate FileHandler class to handle the reading and writing of the text file. I read the file into the Map once in the beginning. I write the Map into the file once at the end. Even when you have 10,000 response / reply lines, the entire file should easily fit into memory.
Because I made the Map value a List of String instances, you can manually create multiple replies for the same response. This adds a bit of variety to the chatbot.
Here's the complete runnable code.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
public class ChatbotExample {
public static void main(String[] args) {
new ChatbotExample().runChatbot();
}
public void runChatbot() {
Scanner scanner = new Scanner(System.in);
String[] exitResponses = { "bye", "see ya", "gtg" };
List<String> exitList = Arrays.asList(exitResponses);
boolean running = true;
System.out.println("Bot: Hello! My name's HiBot! What's up?");
ResponseMap responseMap = new ResponseMap();
FileHandler fileHandler = new FileHandler(responseMap);
fileHandler.readFile();
while (running) {
System.out.print("You: ");
String response = scanner.nextLine();
String lowercaseResponse = response.toLowerCase();
if (exitList.contains(lowercaseResponse)) {
System.out.println("Bot: Ok, see ya. Nice talking to you!");
running = false;
} else {
generateReply(scanner, responseMap, lowercaseResponse);
}
}
fileHandler.writeFile();
scanner.close();
}
private void generateReply(Scanner scanner, ResponseMap responseMap,
String lowercaseResponse) {
String text = responseMap.getResponse(lowercaseResponse);
if (text == null) {
System.out.println("Bot: Sorry, I'm ignorant. How should I reply?");
System.out.print("You: ");
String reply = scanner.nextLine();
responseMap.addResponse(lowercaseResponse, reply);
System.out.println("Bot: Thank you for teaching me a new reply! "
+ "I'm smarter now!");
} else {
System.out.println("Bot: " + text);
}
}
public class FileHandler {
private final File file;
private final ResponseMap responseMap;
private final String separator;
public FileHandler(ResponseMap responseMap) {
this.responseMap = responseMap;
this.separator = " ;;; ";
this.file = new File("convos.txt");
createFile(this.file);
}
private void createFile(File file) {
try {
if (file.createNewFile()) {
System.out.println("Conversations file created");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void readFile() {
try {
BufferedReader reader = new BufferedReader(
new FileReader(file));
String line = reader.readLine();
while (line != null) {
String[] parts = line.split(separator);
responseMap.addResponse(parts[0], parts[1]);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeFile() {
try {
FileWriter writer = new FileWriter(file, false);
PrintWriter output = new PrintWriter(writer);
Map<String, List<String>> responses = responseMap.getResponses();
Set<String> responseSet = responses.keySet();
Iterator<String> iterator = responseSet.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
List<String> text = responses.get(key);
for (String reply : text) {
String s = key + separator + reply;
output.println(s);
}
}
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ResponseMap {
private final Map<String, List<String>> responses;
private final Random random;
public ResponseMap() {
this.responses = new HashMap<>();
this.random = new Random();
}
public Map<String, List<String>> getResponses() {
return responses;
}
public String getResponse(String key) {
List<String> possibleResponses = responses.get(key);
if (possibleResponses == null) {
return null;
} else {
int index = random.nextInt(possibleResponses.size());
return possibleResponses.get(index);
}
}
public void addResponse(String key, String text) {
List<String> possibleResponses = responses.get(key);
if (possibleResponses == null) {
possibleResponses = new ArrayList<>();
responses.put(key, possibleResponses);
}
possibleResponses.add(text);
}
}
}
VIP group of companies introduce a new shopping mall βLe Leβ . To promote the mall they had approached β6th Eventβ a famous commercial event organizer to organize an event of lucky draw. The organizer has to collect name, phone and email id of all the visitors during promotion time and give it to the company.
The organizer needs an automated application and wants to store records in a text file called βvisitors.txtβ.
Records should to be stored in the following structure
Name1,phonenumber1,emailId1;Name2,phonenumber2,emailId2;
In a record, each attributes should be separated using comma (,) and records should be separated using semi colon (;).
Create a Java Application which has two classes called Main.java and FileManager.java
In FileManager class implement the following methods [method skeletons are given]
static public File createFile() β This method should create the file and return it.
static public void writeFile(File f, String record) β In the method, first parameter is the file reference in which records to be added and second parameter is a record, This record should append in the file. [Record should be as per the given format]
static public String[] readFile(File f) β This method accept file to be read, returns all records in the file.
[Note : Donβt modify the signature of the given methods]
In Main class use the following Input and Output statements and call the needed methods from FileManager class to manipulate files.
Enter Name
John
Enter Phone Number
1234567
Enter Email
johnpeter#abc.com
Do you want to enter another record(yes/no)
yes
Enter Name
Grace
Enter Phone Number
98765412
Enter Email
gracepaul#xyz.com
Do you want to enter another record(yes/no)
no
Do you want to display all records(yes/no)
yes
John,1234567,johnpeter#abc.com
Grace,98765412,gracepaul#xyz.com
FileManager class
//import necessary packages
import java.io.*;
import java.util.*;
#SuppressWarnings("unchecked")//Do not delete this line
public class FileManager
{
static public File createFile()
{
File file =new File("visitors.txt");
try{ file.createNewFile();}
catch (IOException e)
{
e.printStackTrace(); //prints exception if any
}
return file;
}
//change the return type as per the requirement
static public void writeFile(File f, String record)
{ try {
BufferedWriter out = new BufferedWriter(
new FileWriter(f.getName(), true));
out.write(record+";");
out.close();
}
catch (IOException e) {
System.out.println("exception occoured" + e);
}
}
static public String[] readFile(File f)
{
List<String> tokens = new ArrayList<String>();
try{
File myObj = new File(f.getName());
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
// String [] arr= myReader.nextLine().split(";");
// tokens = Arrays.asList(arr);
tokens.add(myReader.nextLine());
}
myReader.close();
}
catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
String[] tokenArray = tokens.toArray(new String[0]);
//=tokenArray.split(";");
return tokenArray;
}
}
Main class
import java.util.*;
import java.io.FileNotFoundException;
//import necessary packages
import java.io.File;
#SuppressWarnings("unchecked")//Do not delete this line
public class Main
{
public void abcd(){
Scanner in = new Scanner(System.in);
System.out.println("Enter Name");
String name=in.next();
System.out.println("Enter Phone Number");
long phone=in.nextLong();
System.out.println("Enter Email");
String id= in.next();
FileManager f= new FileManager();
File x =f.createFile();
f.writeFile(x,name+","+phone+","+id);
System.out.println("Do you want to enter another record(yes/no)");
String choice=in.next();
if(choice.equals("yes")){
abcd();
}
if(choice.equals("no"))
{String []q=f.readFile(x);
String pl[]=q[0].split(";");
for(int i=0;i<pl.length;i++)
{
System.out.println(pl[i]);
}
System.exit(0);
}
}
public static void main(String[] args)
{
Main asd=new Main();
asd.abcd();
}
}
This program gives me desired output but not able to run all test cases.
Getting error could not append multiple files. Dont know is this.But it works perfectly on compiler. And you should at least try to code rather then simply asking someone to code.
//all test case passed
import java.io.*;
import java.util.*;
#SuppressWarnings("unchecked")//Do not delete this line
public class FileManager
{
static public File createFile()
{
File myObj = new File("visitors.txt");
try{
if(new File("visitors.txt").isFile()==false)
myObj.createNewFile();
}
catch (IOException e)
{
e.printStackTrace(); //prints exception if any
}
return myObj;//change the return type as per the requirement
}
static public void writeFile (File f, String record)
{
try
{
FileWriter fw = new FileWriter(f.getName(),true); //the true will append the new data
fw.write(record+"\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
static public String[] readFile(File f)
{
List<String> list=new ArrayList<String>();
try{
File myObj = new File(f.getName());
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String str=myReader.nextLine();
String[] parts = str.split(";");
for (String part : parts) {
list.add(part);
}
}
myReader.close();
}
catch(FileNotFoundException ex){}
String[] strings = list.stream().toArray(String[]::new);
return strings;
//change the return type as per the requirement
}
}
I have my code. I think it's all right, but it is not. It keeps telling me at the beginning of each method that there is a ';' expected and it's also an 'illegal start of expression' with the void. I do not know how to fix it. Can someone please help me fix these errors?
Here's an example of the Errors:
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:203: error: ';' expected
void arrayList **()** throws FileNotFoundException();
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: illegal start of expression
**void** output()
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: ';' expected
void output **()**
My code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp{
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// scrubber();
//Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
void arrayList() throws FileNotFoundException();
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
//Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
// void scrubber()
// {
//
// }
//
//
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
}
You should use a Java IDE like Eclipse when programming Java, it would point out to you the most obvious mistakes in your code.
You missed a } after the while loop for your readFile() method (thanks to Sweeper for this one).
The syntax in your arrayList() method is wrong.
void arrayList() throws FileNotFoundException(); {
No semicolon at the end of this defintion, no parenthesis at the end too, you are describing the class, not a method. Here is the correct way:
void arrayList() throws FileNotFoundException {
1 useless } at the end of your class file.
Find below your code, with a proper layout and without syntax errors. Please use an IDE next time, that would avoid you an awful lot of trouble.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam ?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
}
void arrayList() throws FileNotFoundException
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
// Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
throws FileNotFoundException();
This should be
throws FileNotFoundException
and similarly in all cases.
Rather trivial. Don't just make up the syntax. Look it up.
I am relatively new to Java programming. Recently I decided to create a random system that stores, writes, and reads information on request. When reading a file I have already written with the program, I get the following errors:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at ReadFile.readFile(ReadFile.java:24)
at User.main(User.java:35)
I'm assuming this errors are a result of the User class calling on the ReadFile class, because the rest of the program works fine so far.
The User class that pertains:
import java.io.*;
import java.util.*;
public class User
{
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException
{
Scanner user_input = new Scanner(System.in);
String input;
System.out.println("User Information System:");
System.out.println("Please type the full name of the person you wish to lookup.");
input = user_input.nextLine();
System.out.println("UIS currently has the following data on " + input + ":");
if(input.equals("First Last"))
{
System.out.println("Opening Data on " + input + "...");
}
else
{
System.out.println("No Data found.");
}
if(input.equals("/create"))
{
CreateFile create = new CreateFile();
create.openFile();
create.addRecords();
create.closeFile();
}
if(input.equals("/read"))
{
ReadFile read = new ReadFile();
read.openFile();
read.readFile();
read.closeFile();
}
}
}
As well as the ReadFile class:
import java.io.*;
import java.util.*;
public class ReadFile
{
static Scanner scanner;
public void openFile()
{
try
{
scanner = new Scanner(new File("TestFile.txt"));
}
catch(Exception e)
{
System.out.println("Error reading file.");
}
}
public void readFile()
{
while(scanner.hasNext()) //Find a way to shorten this to a loop of printing whatever is in the file.
{
String a = scanner.nextLine();
String b = scanner.next();
String c = scanner.next();
System.out.printf("%s %s %s\n", a,b,c);
}
}
public void closeFile()
{
scanner.close();
}
}
I'm trying to make it so my program
chooses a file
reads the code one line at a time
uses an interface to do three different things
convert to uppercase
count the number of characters
save to a file ("copy.txt")
I'm stuck with the formatting parts. For instance, I'm not sure where the println commands needs to be. Any help will definitely be appreciated. I'm a beginner and still learning basic things.
Interface for Processing Individual Strings:
public interface StringProcessor
{
void process(String s);
}
Processing Class:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
import javax.swing.JFileChooser;
class FileProcessor
{
private Scanner infile;
public FileProcessor(File f) throws FileNotFoundException
{
Scanner infile = new Scanner(System.in);
String line = infile.nextLine();
}
public String go(StringProcessor a)
{
a.process(line);
}
}
Driver Class:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
import javax.swing.JFileChooser;
public class Driver
{
public static void main(String[] args) throws FileNotFoundException
{
JFileChooser chooser = new JFileChooser();
File inputFile = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
inputFile = chooser.getSelectedFile();
}
FileProcessor infile = new FileProcessor(inputFile);
int total=0;
}
}
This Would Make Each Line Uppercase:
public class Upper implements StringProcessor
{
public void process(String s)
{
while (infile.hasNextLine())
{
System.out.println(infile.nextLine().toUpperCase());
}
}
}
This Would Count Characters:
public class Count implements StringProcessor
{
public void process(String s)
{
while (infile.hasNextLine())
{
int charactercounter = infile.nextLine().length();
total = total+charactercounter;
}
}
}
This Would Print to a File:
import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class Print implements StringProcessor
{
public void process(String s)
{
PrintWriter out = new PrintWriter("copy.txt");
while (infile.hasNextLine())
{
out.println(infile.nextLine());
}
out.close();
}
}
Java was one of the first programming languages I learned and once you get it, it's so beautiful. Here is the solution for you homework, but now you have a new homework assignment. Go and figure out what is doing what and label it with notes. So next time you have a similar problem you can go over your old codes and cherry pick what you need. We were all noobs at some point so don't take it to bad.
StringProcessor.java
public interface StringProcessor {
public String Upper(String str);
public int Count(String str);
public void Save(String str, String filename);
}
FileProcessor.java
import java.io.FileWriter;
public class FileProcessor implements StringProcessor{
public FileProcessor(){
}
// Here we get passed a string and make it UpperCase
#Override
public String Upper(String str) {
return str.toUpperCase();
}
// Here we get passed a string and return the length of it
#Override
public int Count(String str) {
return str.length();
}
// Here we get a string and a file name to save it as
#Override
public void Save(String str, String filename) {
try{
FileWriter fw = new FileWriter(filename);
fw.write(str);
fw.flush();
fw.close();
}catch (Exception e){
System.err.println("Error: "+e.getMessage());
System.err.println("Error: " +e.toString());
}finally{
System.out.println ("Output file has been created: " + filename);
}
}
}
Driver.java
import java.io.File;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class Driver {
#SuppressWarnings("resource")
public static void main(String[] args){
System.out.println("Welcome to the File Processor");
Scanner scan = new Scanner(System.in);
System.out.print("\nWould you like to begin? (yes or no): ");
String startProgram = scan.next();
if(startProgram.equalsIgnoreCase("yes")){
System.out.println("\nSelect a file.\n");
JFileChooser chooser = new JFileChooser();
File inputFile = null;
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
inputFile = new File(chooser.getSelectedFile().getAbsolutePath());
try{
Scanner file = new Scanner(inputFile);
file.useDelimiter("\n");
String data = "";
FileProcessor fp = new FileProcessor();
while (file.hasNext()){
String line = file.next();
System.out.println("Original: " +line);
System.out.println("To Upper Case: " +fp.Upper(line));
System.out.println("Count: " +fp.Count(line));
System.out.println();
data += line;
}
System.out.println("\nFile Processing complete!\n");
System.out.print("Save copy of file? (yes or no): ");
String save = scan.next();
if(save.equalsIgnoreCase("yes")){
fp.Save(data, "copy.txt");
System.out.println("\nProgram Ending... Goodbye!");
}else{
System.out.println("\nProgram Ending... Goodbye!");
}
}catch (Exception e){
e.printStackTrace();
}
}
}else{
System.out.println("\nProgram Ending... Goodbye!");
}
}
}
text.txt
some text here to test the file
and to see if it work correctly
Just a note when you save the file "copy.txt", it will show up in your project folder.
As your problem operates on streams of characters, there is already a good Java interface to implement. Actually, they are two abstract classes: FilterReader or FilterWriter β extending either one will work. Here, I've chosen to extend FilterWriter.
For example, here is an example of a Writer that keeps track of how many characters it has been asked to write:
import java.io.*;
public class CharacterCountingWriter extends FilterWriter {
private long charCount = 0;
public CharacterCountingWriter(Writer out) {
super(out);
}
public void write(int c) throws IOException {
this.charCount++;
out.write(c);
}
public void write(char[] buf, int off, int len) throws IOException {
this.charCount += len;
out.write(buf, off, len);
}
public void write(String str, int off, int len) throws IOException {
this.charCount += len;
out.write(str, off, len);
}
public void resetCharCount() {
this.charCount = 0;
}
public long getCharCount() {
return this.charCount;
}
}
Based on that model, you should be able to implement a UpperCaseFilterWriter as well.
Using those classes, here is a program that copies a file, uppercasing the text and printing the number of characters in each line as it goes.
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
try (CharacterCountingWriter ccw = new CharacterCountingWriter(new FileWriter(args[1]));
UpperCaseFilterWriter ucfw = new UpperCaseFilterWriter(ccw);
Writer pipeline = ucfw) { // pipeline is just a convenient alias
String line;
while (null != (line = in.readLine())) {
// Print count of characters in each line, excluding the line
// terminator
ccw.resetCharCount();
pipeline.write(line);
System.out.println(ccw.getCharCount());
pipeline.write(System.lineSeparator());
}
pipeline.flush();
}
}