Here's what I have so far, I'm just having trouble writing the second part that will say that the string in the text file isn't there if the user enters a number thats not saved in the text file (data3.txt). Also how would I make it so that the program keeps running and doesn't stop after 1 user input? Thanks!

// Import io so we can use file objects 
import java.io.*; 
public class searchfile { 
public static void main(String args[]) { 
try { 
// Open the file data3.txt as a buffered reader 
BufferedReader bf = new BufferedReader(new FileReader("data3.txt")); 
// Start a line count and declare a string to hold our current line. 
int linecount = 0; 
String line; 
// Let the user know what we are searching for 
// i.e. just printing to the console, not actually searching. 
System.out.println("Searching for " + args[0] + " in file..."); 
// Loop through each line, stashing the line into our line variable. 
while (( line = bf.readLine()) != null) 
{
// Count lines. We read a line this variable (linecount) increments by one 
linecount++; 
for(int index = 0; true; index++) { 
try { 
int indexfound = line.indexOf(args[index]); 
// If greater than -1, means we found the word 
if (indexfound > -1) {
System.out.println("Word was found at position " + indexfound +" on line " + linecount);
else
System.out.println("word not found");
}
}
catch(ArrayIndexOutOfBoundsException ex) { 
break; 
}
}
}
bf.close(); 
}
catch (IOException e) { 
System.out.println("IO Error Occurred: " + e.toString()); 
}
}
}

Recommended Answers

All 13 Replies

how would I make it so that the program keeps running and doesn't stop after 1 user input

Put the code inside of a loop like a while loop. Stay in the loop until the all the user input has been read.

Please edit your post and format the code. Unformatted code is hard to read and understand.
Statements should not all start in the first column.
See: http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#262

How can I get to the program to tell me if the number the user inputs is not in the .txt file ??

tell me if the number the user inputs is not in the .txt file

I'm not sure what you mean by a number. text files contain String data.
Does the user enter an int value or a String? If the user enters an int do you convert it to a String? Say the user enters 12 and the file has a line with 1234 on it. If you use Strings, then "1234" contains the String "12". But if you use int value, then 1234 is not a match for 12.

Can you give some examples? Some user input and some lines in the file that match and some lines that do not match.

There are a couple problems in your code.

1) Line 19, you do NOT need a for loop to check the existence of a substring inside a string. The only occasion you need a loop is when you check each character of a string one by one.
2) Line 21, you will likely get ArrayIndexOutOfBoundException most of the time from accessing args[index]. That's the place where you wrongly access the argument variables. You need only args[0], not args[index].

Said that, you do not need try-catch statement at all for the checking of indexOf() in your code. Also, one more comment is that the check of indexOf() is case-sensitive. So if the text contains "Me and You" as a string and a user enters "me" as the input, the indexOf() will return -1 because it cannot find the substring ("me" is not equal to "Me").

ah sorry NormR1 late night lol, heads a tad foggy. By numbers I meant when the user is prompted for input by the program, for instance it asks me for my input Ill type in 13. If 13 is in my data3.txt which it is, it'll return "Found," however, I'm looking to find what to write if a number that the user enters is not in the text file. something like "Number not found" etc

If 13 is in my data3.txt which it is, it'll return "Found,"

If the code does not return "Found" would that mean the number was not found?

Please edit your post and format the code. Unformatted code is hard to read and understand.

Yes that would mean that the number was not found. I've re-edited my code quite a bit, here it is: (also, I'm having trouble running it as it's given me arrayoutofbounds, and i'm using jGrasp and it's not running in there)

import java.util.*; // import scanner
import java.io.*;
public class Homeworkhelp3 {
    public static void main(String[] arg){
        int[] database; //signifies what database we are going to be using
        FileInputStream fstream = null;
        try {
            fstream = new FileInputStream(arg[0]); //reads file that we are looking for to run program
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        DataInputStream in = new DataInputStream(fstream); 
        BufferedReader br = new BufferedReader(new InputStreamReader(in));//reading data from ("data3.txt")
        String size=null;
        int linecount = 0;
        try {
            size = br.readLine();//indicates the size of the file
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        database= new int[Integer.parseInt(size)];//sets the data for program
        int counter=0;
        String strLine;
        try {
            while ((strLine = br.readLine()) != null);   { //parses the data in
                database[counter]=Integer.parseInt(strLine);
                counter++;//counter incremtented +1 each time, after ever input, allows user to input another number
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Scanner stdin = new Scanner(System.in);// declare scanner
        while(stdin.hasNext())//allows continuous input for user to keep inputting numbers for program to search .txt file
        {
            boolean foundint=false;
            int compareint=stdin.nextInt();
            for(int i =0;i<Integer.parseInt(size);i++)//number input by  user is searched for, loop depicts whether or not if the input is in txt file or not
            {
                if(compareint==database[i])// is in the list
                {
                    System.out.println(compareint+ " This number is in the list!" + linecount);
                    foundint=true;
                }
            }
            if(!foundint) //signifies if the input by user is in the .txt file or not
            {
                System.out.println(compareint+" This number is not in the list");
            }
        }
        System.out.println("Goodbye, Have a nice day !");
    }
}

Here's what i'm being asked to do:

Use the ReverseList.java program we studied in class as example for reading input
from a file whose name is supplied as a command-line argument: (never studied any of this lol)
a. check to make sure that a command line argument is supplied
b. set up a scanner object to read from a file
c. read the data in the file and store it in an array (named, for example, list)
2. Set up a scanner object to read input from the keyboard (from System.in)
3. As long as there is input to be read, read input, see if the value read is in the array list or
not and print an appropriate message.
4. You will need 3 loops (one for reading data from the file, one for reading user inputs, and
for one checking whether or not the value supplied by the user is in the list. The last loop
will be nested inside the second loop. The first and third loops could be for loops like theone in ReverseList.java and the second one would be a while loop in the example
copy.java that we also did in class.
5. To see whether or not a value is in the array list, you will have to use an if statement to
compare values. If you find a value, then you need to exit from the nested for loop using the
break statement.

it's given me arrayoutofbounds

Please copy the full text of the error message and paste it here. It has important info about the error.

Look at where the error message points to and see why the array's index is out of bounds.
How long is the array? What is the value of the index?
Remember array indexes go from 0 to the array length-1

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at Homeworkhelp3.main(Homeworkhelp3.java:8)

What array is referenced at line 8? Does that array have any contents?

The program is expecting there to be args passed to it on the commandline:

java Homeworkhelp3 <PUT THE ARGS HERE>

a file whose name is supplied as a command-line argument:

I'm sorry where? Getting bit confused now

The command line is what you pass to the OS when you want to execute a program.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.