Checking input format - java

I have a program I'm writing for class, and I'm stuck on the very last part. Here's what it requests, and what I'm stuck at:
Display an error if the file does not exist or the format is
incorrect.
The formatting of the input is along the lines of:
Name;Service;Price;Date
or
Bob Smith;Dinner;52.35;04-01-2014
And my code so far:
package school;
import java.util.*;
import java.io.*;
public class HotelSales{
public static void main(String[] args){
try {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
// I assume the format check would go here?
String[] array = new String[48];
double conferenceTotal = 0;
double dinnerTotal = 0;
double lodgingTotal = 0;
String line = "";
while((line = br.readLine()) != null){
array = line.split(";");
if(array[1].equals("Conference")) {
conferenceTotal += Double.parseDouble(array[2]);
} else if(array[1].equals("Dinner")) {
dinnerTotal += Double.parseDouble(array[2]);
} else if(array[1].equals("Lodging")) {
lodgingTotal += Double.parseDouble(array[2]);
}
}
System.out.println("The totals for the sales are: \n");
System.out.printf("Conference Total: $%-5.2f\n", conferenceTotal);
System.out.printf("Dinner Total: $%-5.2f\n", dinnerTotal);
System.out.printf("Lodging Total: $%-5.2f\n", lodgingTotal);
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
bw.write("The totals for the sales are: ");
bw.newLine();
bw.newLine();
bw.write("Conference Total: $" + String.format("%-5.2f",conferenceTotal));
bw.newLine();
bw.write("Dinner Total: $" + String.format("%-5.2f",dinnerTotal));
bw.newLine();
bw.write("Lodging Total: $" + String.format("%-5.2f",lodgingTotal));
br.close();
bw.close();
} catch (InputMismatchException e) { //And that this is the proper catch right?
System.out.print("Wrong input file format.\n");
e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.print("Sorry, the file was not found.\n");
e.printStackTrace();
} catch (IOException e) {
System.out.print("Oops! I/O Exception.\n");
e.printStackTrace();
}
}
}
Thanks! :)

this should work:
while((line = br.readLine()) != null){
String [] array = line.split(";");
if ( array.length != 4 ) {
throw new InputMismatchException( "Invalid ... blah blah, expected 4 elements, found " + array.length );
}
try {
if(array[1].equals("Conference")) {
conferenceTotal += Double.parseDouble(array[2]);
} else if(array[1].equals("Dinner")) {
dinnerTotal += Double.parseDouble(array[2]);
} else if(array[1].equals("Lodging")) {
lodgingTotal += Double.parseDouble(array[2]);
}
} catch ( NumberFormatException nfe ) {
throw new InputMismatchException( nfe );
}
}
and remove the line:
String[] array = new String[48];

If your input file is not separated by ;'s, then when you attempt to Double.parseDouble(array[2]), you'll get an ArrayIndexOutOfBoundsException or a NullPointerException because your array will be of size 1.
while ((line = br.readLine()) != null)
{
array = line.split(";");
if (array.length != 4)
{
throw new InputMismatchException("Invalid ... blah blah, expected 4 elements, found " + array.length);
}
try
{
if (array[1].equals("Conference"))
{
conferenceTotal += Double.parseDouble(array[2]);
}
else if (array[1].equals("Dinner"))
{
dinnerTotal += Double.parseDouble(array[2]);
}
else if (array[1].equals("Lodging"))
{
lodgingTotal += Double.parseDouble(array[2]);
}
}
catch (ArrayIndexOutOfBoundsExceptione aioobe)
{
throw new InputMismatchException(aioobe);
}

Related

Comparing integers from a text file and program that has strings involved

I've tried in vain to compare scores in my application with scores already saved in a separate text file. Comparing the score is easy enough when strings aren't involved but when I save the score and assign it a name, the program doesn't work as it cannot parse strings & integers.
Example text file:
Name, 8
Name, 1
Name, 4
Code I'm using to compare:
int highScore = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader("txt.txt"));
String line = reader.readLine();
while (line != null)
{
try {
int score = Integer.parseInt(line.trim());
if (score > highScore)
{
highScore = score;
}
} catch (NumberFormatException e1) {
//ignore invalid scores
//System.err.println("ignoring invalid score: " + line);
}
line = reader.readLine();
}
reader.close();
} catch (IOException ex) {
System.err.println("ERROR");
}
The rest of the code is fine and the score is generated as the game finishes comparing it to the score in the file, it just generates a 0 value when comparing as it reads the string and doesn't work. I'm not sure on how to use scanners/delimiters.
EDIT:
I'd like the program to execute and show the name of the user which got that highscore. So the desired output would be;
The all time high score was 8 by Name1
Currently it only says the highscore (following Michu93's input).
Run the below program. It will give you desired output. Please correct the other things, I just concentrated on output.
public class Test {
static int highScore = 0;
static String highscorer = "";
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("src/com/test/package1/txt.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
try {
String[] parts = line.split(",");
int tempScore = Integer.parseInt(parts[1].trim());
String tempHigScorer = (parts[0]);
if (tempScore > highScore) {
highScore = tempScore;
highscorer = tempHigScorer;
}
} catch (NumberFormatException e1) {
// handle NumberFormatException if any
}
}
reader.close();
} catch (IOException ex) {
System.err.println("ERROR");
}
System.out.println("The all time high score was " + highScore + " by name " + highscorer);
}
}
Remove digits from string and parse it to int:
int score = Integer.valueOf(line.replaceAll("[^\\d.]", ""));
#Edit
int highScore = 0;
String name = "";
try {
BufferedReader reader = new BufferedReader(new FileReader("txt.txt"));
String line = reader.readLine();
while (line != null) {
try {
int score = Integer.parseInt(line.split(" ")[1]);
if (score > highScore) {
highScore = score;
name = line.split(" ")[0].replace(",", "");
}
} catch (NumberFormatException e1) {
//ignore invalid scores
//System.err.println("ignoring invalid score: " + line);
}
line = reader.readLine();
}
System.out.println(String.format("The all time high score was %s by %s", highscore, name));
} catch (IOException ex) {
System.err.println("ERROR");
} finally {
reader.close(); // close stream always in finnaly block or use try with resources!!!
}
Observe that when you read a whole line you are getting a String with both Name and the Integer you want to get. I'd do the following:
int highScore = 0;
String name = "";
try {
BufferedReader reader = new BufferedReader(new FileReader("txt.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
try {
String[] parts = line.split(",");
if(parts.length > 1){
int score = Integer.parseInt(parts[1].trim());
if (score > highScore) {
highScore = score;
name = line[0];
}
}
} catch (NumberFormatException e1) {
//ignore invalid scores
//System.err.println("ignoring invalid score: " + line);
}
}
System.out.println("The all time high score was %s by %s", highScore, name);
reader.close();

Press any key with BufferedReader

I created a java file called Product.java. I also created a text file called Items.txt. Basically when the user enter the word using sequential search to search the data what they are looking from Items.txt. My main problem is when I enter 3 to display all the records or enter x to exit the program, it keeps on looping. But I don't how to resolve this problem. Can anyone solved this for me?
Items.txt
1000|Cream of Wheat|Normal Size|Breakfast|NTUC|5|3.00
1001|Ayam Brand|Small Size|Canned|NTUC|4|4.00
Product.java
import java.io.*;
import java.util.*;
public class Product {
public static void main(String[] args) {
ArrayList<Item> prdct = new ArrayList<Item>();
String inFile = "items.txt";
String line = "";
FileReader fr = null;
BufferedReader br = null;
StringTokenizer tokenizer;
int quantity;
String id, brandname, desc, category, supplier;
float price;
try{
fr = new FileReader(inFile);
br = new BufferedReader(fr);
line = br.readLine();
while(line!=null)
{
tokenizer = new StringTokenizer(line,"|");
id = tokenizer.nextToken();
brandname = tokenizer.nextToken();
desc = tokenizer.nextToken();
category = tokenizer.nextToken();
supplier = tokenizer.nextToken();
quantity = Integer.parseInt(tokenizer.nextToken());
price = Float.parseFloat(tokenizer.nextToken());
Item itm = new Item(id,brandname,desc,category,supplier,quantity,price);
prdct.add(itm);
line = br.readLine();
}
br.close();
}
catch(FileNotFoundException e){
System.out.println("The file " + inFile + " was not found.");
}
catch(IOException e){
System.out.println("Reading error!");
}
finally
{
if (fr!=null){
try
{
fr.close();
}
catch(IOException e)
{
System.out.println("Error closing file!");
}
}
}
String INPUT_PROMPT = "\nPlease enter 3 to display all records, 4 to insert record, 5 to remove old records " + "or enter 'x' to quit.";
System.out.println(INPUT_PROMPT);
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader (System.in));
line = reader.readLine();
while(reader != null)
{
for(int i=0; i<prdct.size(); i++)
{
if(prdct.get(i).id.contains(line) || prdct.get(i).brandname.contains(line) || prdct.get(i).desc.contains(line)
|| prdct.get(i).category.contains(line) || prdct.get(i).supplier.contains(line))
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
}
while("3".equals(line))
{
for(int i=0; i<prdct.size(); i++)
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
while(!line.equals("x"))
{
System.out.println(INPUT_PROMPT);
line=reader.readLine();
}
}
catch(Exception e){
System.out.println("Input Error!");
}
}
}
The problem is with this loop:
while(reader != null)
{
for(int i=0; i<prdct.size(); i++)
{
if(prdct.get(i).id.contains(line) || prdct.get(i).brandname.contains(line) || prdct.get(i).desc.contains(line)
|| prdct.get(i).category.contains(line) || prdct.get(i).supplier.contains(line))
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
}
It keeps on looping while reader is not null and it will never be. You might want to try checking something else that suits your problem better, maybe:
While(!line.equals("3"))
While(!line.equals("x"))
While(line != null)
Otherwise, even if there is an 'x', '3' or simply nothing, still (reader != null) and therefore the loop is infinite.
I suspect that the newline character is what causes the comparison to fail.
Instead of checking if:
"3".equals(line)
Try:
"3".equals(line.trim())
Same applies to the following comparison.
Try changing this..
line = reader.readLine();
while(reader != null)
{
to this..
line = reader.readLine();
while(line != null)
{
You are looping on the reader being not null, which it always will be.
you have to define these functions:
public void showAllRecords() {
// show all record here
}
public void insertRecord() {
// insert record here
}
public void removeRecord() {
// insert record here
}
public void exit() {
// insert record here
}
then
do{
System.out.println(INPUT_PROMPT);
switch(line)
{
case "3":
showAllRecords();
break;
case "4":
insertRecord();
break;
case "5":
removeRecord();
}
}while(!line.equals('x'));

Debugging File Search / Merge Code

This program is meant to see two files located in a particular folder and then merge those two files and create a third file which is does. From the third merged file it is then searching for a keyword such as "test", once it finds that key word it prints out the location and the line of the keyword which is what is somewhat doing. What is happening is when I run the program it stops after the finds the keyword the first time in a line but it will not continue to search that line. So if there is multiple keyword 'test' in the line it will only find the first one and spit back the position and line. I want it to print both or multiple keywords. I think it is because of the IndexOf logic which is causing the issue.
import com.sun.deploy.util.StringUtils;
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class Concatenate {
public static void main(String[] args) {
String sourceFile1Path = "C:/Users/me/Desktop/test1.txt";
String sourceFile2Path = "C:/Users/me/Desktop/test2.txt";
String mergedFilePath = "C:/Users/me/Desktop/merged.txt";
File[] files = new File[2];
files[0] = new File(sourceFile1Path);
files[1] = new File(sourceFile2Path);
File mergedFile = new File(mergedFilePath);
mergeFiles(files, mergedFile);
stringSearch(args);
}
private static void mergeFiles(File[] files, File mergedFile) {
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, true);
out = new BufferedWriter(fstream);
} catch (IOException e1) {
e1.printStackTrace();
}
for (File f : files) {
System.out.println("merging: " + f.getName());
FileInputStream fis;
try {
fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
while ((aLine = in.readLine()) != null) {
out.write(aLine);
out.newLine();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void stringSearch(String args[]) {
try {
String stringSearch = "test";
BufferedReader bf = new BufferedReader(new FileReader("C:/Users/me/Desktop/merged.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file");
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
}
}
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
It's because you are searching for the word once per line in your while loop. Each iteration of the loop takes you to the next line of the file because you are calling bf.readLine(). Try something like the following. You may have to tweak it but this should get you close.
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
while(indexfound > -1)
{
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
indexfound = line.indexOf(stringSearch, indexfound);
}
}

Display searched text with line numbers in a text file

So I've been working on a program that will display the line number and the line itself of the searched text string. If I search dog, and I have lines in my text file that contain the word dog, those lines and line numbers should be shown. I also have created a method that counts the characters, words, and lines of a text file. However, the problem I am having is that whenever I run my program I don't get the line numbers with the lines of the searched text. I successfully get the text from the text file in the console and I successfully get the number of lines, words, etc.
Here's my written code, I am guessing it has to do something with the fact that I don't have a "return results;" statement, but I am not sure where to put it, and if I add it to the end of "+ characters + " characters. "" line by doing "+ results", it just gives me empty brackets.
Maybe I am doing something wrong? Perhaps something to do with closing the file and stream, not sure. Please help, I've tried moving stuff around but no luck.
public String words() {
try {
int words = 0;
int numbers = 0;
int lines = 1;
int characters = 0;
int total = 0;
String c = " ";
FileReader r = new FileReader(file1);
LineNumberReader lnr = new LineNumberReader(r);
StreamTokenizer t = new StreamTokenizer(r);
ArrayList<String> results = new ArrayList<String>();
t.resetSyntax();
t.wordChars('0', '9');
t.wordChars('A', 'Z');
t.wordChars('a', 'z');
t.whitespaceChars(0, ' ');
t.eolIsSignificant(true);
while (t.nextToken() != StreamTokenizer.TT_EOF) {
switch (t.ttype) {
case StreamTokenizer.TT_NUMBER:
numbers++;
break;
case StreamTokenizer.TT_WORD:
characters += t.sval.length();
words++;
break;
case StreamTokenizer.TT_EOL:
lines++;
break;
case StreamTokenizer.TT_EOF:
break;
default:
}
}
FileInputStream fstream = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
br.close();
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
String word = find;
String line = null;
while ((line = lnr.readLine()) != null) {
if (line.indexOf(word) >= 0) {
results.add(lnr.getLineNumber() + line);
}
}
r.close();
total = numbers + words;
lnr.close();
return file1.getName() + " has " + lines + " lines, "
+ total + " words, "
+ characters + " characters. ";
} catch (IOException e) {
display(e.toString(), "Error");
}
return " ";
}
Here's the main class if needed:
import java.io.*;
import java.util.ArrayList;
import javax.swing.*;
public class BasicFile {
File file1;
JFileChooser selection;
File file2 = new File(".", "Backup File");
public BasicFile() {
selection = new JFileChooser(".");
}
public void selectFile() {
int status = selection.showOpenDialog(null);
try {
if (status != JFileChooser.APPROVE_OPTION) {
throw new IOException();
}
file1 = selection.getSelectedFile();
if (!file1.exists()) {
throw new FileNotFoundException();
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File Not Found ", "Error", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
System.exit(0);
}
}
public void backupFile() throws FileNotFoundException {
DataInputStream in = null;
DataOutputStream out = null;
try {
in = new DataInputStream(new FileInputStream(file1));
out = new DataOutputStream(new FileOutputStream(file2));
try {
while (true) {
byte data = in.readByte();
out.writeByte(data);
}
} catch (EOFException e) {
JOptionPane.showMessageDialog(null, "File has been backed up!",
"Backup Complete!", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found ",
"Error", JOptionPane.INFORMATION_MESSAGE);
}
} finally {
try {
in.close();
out.close();
} catch (Exception e) {
display(e.toString(), "Error");
}
}
}
boolean exists() {
return file1.exists();
}
public String toString() {
return file1.getName() + "\n" + file1.getAbsolutePath() + "\n" + file1.length() + " bytes";
}
public String words() {
try {
int words = 0;
int numbers = 0;
int lines = 1;
int characters = 0;
int total = 0;
String c = " ";
FileReader r = new FileReader(file1);
LineNumberReader lnr = new LineNumberReader(r);
StreamTokenizer t = new StreamTokenizer(r);
ArrayList<String> results = new ArrayList<String>();
t.resetSyntax();
t.wordChars('0', '9');
t.wordChars('A', 'Z');
t.wordChars('a', 'z');
t.whitespaceChars(0, ' ');
t.eolIsSignificant(true);
while (t.nextToken() != StreamTokenizer.TT_EOF) {
switch (t.ttype) {
case StreamTokenizer.TT_NUMBER:
numbers++;
break;
case StreamTokenizer.TT_WORD:
characters += t.sval.length();
words++;
break;
case StreamTokenizer.TT_EOL:
lines++;
break;
case StreamTokenizer.TT_EOF:
break;
default:
}
}
FileInputStream fstream = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
br.close();
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
String word = find;
String line = null;
while ((line = lnr.readLine()) != null) {
if (line.indexOf(word) >= 0) {
results.add(lnr.getLineNumber() + line);
}
}
r.close();
total = numbers + words;
lnr.close();
return file1.getName() + " has " + lines + " lines, "
+ total + " words, "
+ characters + " characters. ";
} catch (IOException e) {
display(e.toString(), "Error");
}
return " ";
}
void display(String msg, String s) {
JOptionPane.showMessageDialog(null, msg, s, JOptionPane.ERROR_MESSAGE);
}
}
You are nearly there.
reinitialize your FileReader and LineNumberReader before your while ((line = lnr.readLine()) != null) loop.
Then your ArrayList will be full of the #String that I think you desire.
what you can do is start counting the lines in the file (starting by 0), then increase by 1 every time a new line is found.. then check if the string you want to find is contained in the line, then print the number of the line where the keyword is found (using the contains() function in Java). I assumed you want to check for both upper and lower case, if you don't want that then simply remove the toLowerCase() ! So, read the file properly in Java:
long lineNumber = 0;
BufferedReader myReader = new BufferedReader(new FileReader("test.txt"));
String line = myReader.readLine();
while(line != null){
lineNumber++;
System.out.println("The line I am now examining is : " + line + " and the line number is : " + lineNumber);
if line.toLowerCase().contains(word.toLowerCase()) {
System.out.println("Line number: " + lineNumber + " contains keyword : " + word);
line = myReader.readLine();
}

Searching a FIle: Beginner Code

I am in college for programming and we were given an assignment to create a program that allows the user to open a file from their computer and obtain information from that file that is selected. One part of my assignment states the following:
Search the file line by line for a given string. The output must contain the line number, followed by the contents of the line that contains the search argument. For instance given the following the search string: Java, the program would search the file line by line generating a result such as the following:
5: on the island of Java
9: The people of JAVA loves jaVa.
Use the class LineNumberReader for this exercise.
I have my code below, and I am not sure what I am doing wrong. There is no syntax error, just seems to be a logic error. When I run the code I am able to get the file description, backup the file, get the word count, and exit properly, but when asked to search for a word as described above I am not getting the output that I am supposed to get, it only gives me the word count and no search results.
Main Class
import java.io.*;
import java.util.ArrayList;
import javax.swing.*;
public class BasicFile {
File file1;
JFileChooser selection;
File file2 = new File(".", "Backup File");
public BasicFile() {
selection = new JFileChooser(".");
}
public void selectFile() {
int status = selection.showOpenDialog(null);
try {
if (status != JFileChooser.APPROVE_OPTION) {
throw new IOException();
}
file1 = selection.getSelectedFile();
if (!file1.exists()) {
throw new FileNotFoundException();
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File Not Found ", "Error", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
System.exit(0);
}
}
void backupFile() throws FileNotFoundException {
DataInputStream in = null;
DataOutputStream out = null;
try {
in = new DataInputStream(new FileInputStream(file1));
out = new DataOutputStream(new FileOutputStream(file2));
try {
while (true) {
byte data = in.readByte();
out.writeByte(data);
}
} catch (EOFException e) {
JOptionPane.showMessageDialog(null, "Success!!!",
"Backup Complete!", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found ",
"Error", JOptionPane.INFORMATION_MESSAGE);
}
} finally {
try {
in.close();
out.close();
} catch (Exception e) {
display(e.toString(), "Error");
}
}
}
boolean exists() {
return file1.exists();
}
public String toString() {
return file1.getName() + "\n" + file1.getAbsolutePath() + "\n" + file1.length() + " bytes";
}
public String words() {
try {
int words = 0;
int numbers = 0;
int lines = 1;
int characters = 0;
int total = 0;
String c = " ";
FileReader r = new FileReader(file1);
LineNumberReader lnr = new LineNumberReader(r);
StreamTokenizer t = new StreamTokenizer(r);
ArrayList<String> results = new ArrayList<String>();
t.resetSyntax();
t.wordChars('0', '9');
t.wordChars('A', 'Z');
t.wordChars('a', 'z');
t.whitespaceChars(0, ' ');
t.eolIsSignificant(true);
while (t.nextToken() != StreamTokenizer.TT_EOF) {
switch (t.ttype) {
case StreamTokenizer.TT_NUMBER:
numbers++;
break;
case StreamTokenizer.TT_WORD:
characters += t.sval.length();
words++;
break;
case StreamTokenizer.TT_EOL:
lines++;
break;
case StreamTokenizer.TT_EOF:
break;
default:
}
}
BufferedReader bf = new BufferedReader(new FileReader(file1));
BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));
BufferedWriter output = new BufferedWriter(new FileWriter("output.txt"));
int recCount = 0;
String record = null;
while ((record = bf.readLine()) != null) {
recCount++;
out.write(recCount + ": " + record);
out.newLine();
}
out.close();
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
String word = find;
String line = null;
while ((line = lnr.readLine()) != null) {
if (line.indexOf(word) >= 0) {
results.add(lnr.getLineNumber() + line);
}
}
r.close();
total = numbers + words;
lnr.close();
return file1.getName() + " has " + lines + " lines, "
+ total + " words, "
+ characters + " characters. ";
} catch (IOException e) {
display(e.toString(), "Error");
}
return " ";
}
void display(String msg, String s) {
JOptionPane.showMessageDialog(null, msg, s, JOptionPane.ERROR_MESSAGE);
}
}
Test Class
import java.io.*;
import javax.swing.*;
public class TestBasicFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
boolean done = false;
String menu = "Enter option\n1. Open File\n2. Backup File\n3. "
+ "Word Count\n4. Exit";
while (!done) {
BasicFile f = new BasicFile();
String s = JOptionPane.showInputDialog(menu);
try {
int i = Integer.parseInt(s);
switch (i) {
case 1:
JOptionPane.showMessageDialog(null, "When the file is selected, the name, path, and size will be displayed",
"File Selection", JOptionPane.INFORMATION_MESSAGE);
f.selectFile();
if (f.exists()) {
displayInfo(f.toString(), "File");
} else {
f.selectFile();
}
break;
case 2:
f.selectFile();
if (f.exists()) {
displayInfo(f.toString(), "File");
} else {
f.selectFile();
}
f.backupFile();
break;
case 3:
f.selectFile();
if (f.exists()) {
displayInfo(f.words(), "Word Count");
} else {
f.selectFile();
}
break;
case 4:
done = true;
break;
default:
}
} catch (NumberFormatException e) {
System.exit(0);
} catch (NullPointerException e) {
System.exit(0);
}
}
}
static void displayInfo(String s, String info) {
JOptionPane.showMessageDialog(null, s, info, JOptionPane.INFORMATION_MESSAGE);
}
}
You put the results in the results list, but never print that.

Categories