I was having trouble getting my program to read from a file "lexicon.txt"
My task was to have the program scan a user input and getting the word count for the program in return. Do you guys know what's going on in my code?
import java.io.*;
import java.util.Scanner;
public class searchFile {
public static void main (String args[]) throws IOException {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the file name (e.g: nonamefile.txt)");
String objective = reader.nextLine();
if (!(objective.equals("lexicon.txt"))) {
System.out.println("ERROR: Missing File");
}
else {
Scanner reader2 = new Scanner(System.in);
Scanner lexicon = new Scanner(new File("lexicon.txt"));
int wordCount = 0;
System.out.println("What word do you need to look up?");
String objective2 = reader2.nextLine();
while (lexicon.hasNext()) {
String word = lexicon.next();
if (word.equalsIgnoreCase(objective2)){
wordCount++;
}
}
System.out.println("Word count = " + wordCount);
}
} // end main method (String Args[])
} // end class searchFile
I ran your code on my computer. It is to help you. may be you are not doing same.
Please enter the file name (e.g: nonamefile.txt)
lexicon.txt
What word do you need to look up?
three
Word count = 3
The text I used in lexicon.txt was that :
one
two two
three three three
And it is working fine.
Remember, just copy paste is not like what you think it. there could be any character in clipboard when you copy that you cannot see, and pasting it also pastes these code too in your text file.
Scanner.next() looks for the next string delimited by word boundries.
Suppose there is a text that you copy pasted :
which is not visible in notepad :
So when you will search for "Hello", it will not be there.
You will have to search for instead, but you cannot write this easily.
Related
The program I am writing needs to read 4 lines of data from a text file containing an ID, Name, Level, and Salary for an employee. It then needs to create a formatted email address and print all of this to standard output. The text file can contain an unknown number of employees, so a while loop must be used with the hasNext() method to confirm there is more data to read.
My program freezes (using Dr. Java) as soon as the while loop begins, and I cant figure out why.
Here is my code so far
public static void main(String[] args) throws IOException {
File file = new File("employeeInput.txt");
if (file.exists()) { //check if file exists
Scanner inputFile = new Scanner(file); //opens file
String companyName = inputFile.nextLine();
System.out.println(companyName);
System.out.println();
System.out.println("----------------------------");
while (inputFile.hasNext()); {
String studentID = inputFile.nextLine();
System.out.println(studentID);
String studentName = inputFile.nextLine();
System.out.println(studentName);
String employeeLevel = inputFile.nextLine();
System.out.println(employeeLevel);
double salary = inputFile.nextDouble();
System.out.println(salary);
}
inputFile.close();
}
else {
System.out.println("The file employeeInput.txt does not exist");
}
}
}
I understand this code is not complete and does everything the program needs to, but I do not get why it's freezing at the while loop..
Any help or advice would be appreciated. This is my first class ever in programming language, so go easy on me :)
I keep getting an error and I am unsure why. This is my code
public class test {
public static void main(String[] args) throws FileNotFoundException {
Scanner inscan = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputfilename = inscan.nextLine();
File inputfile = new File(inputfilename);
Scanner in = new Scanner(inputfile);
String inputline = in.nextLine();
ArrayList<String> Names = new ArrayList<String>();
in.nextLine();
in.nextLine();
int total = 0;
while(in.hasNextLine()){
in.nextInt();
String Mname = in.next();
int Number = in.nextInt();
Names.add(Mname);
total += Number;
}
in.close();
for (String Mname : Names) {
System.out.println(Mname);
}
System.out.println("total number is " + total);
}
}
Prints:
hi
total number is 38
This is what the text file looks like.
test
test
1 mike 34
2 hi 38
I am first skipping the first two lines. Then getting all the names. Then printing the total number of all those names. It is now working with no errors but only prints one thing.
You're not pointing to the file properly. In order for your program to read names.txt, names.txt must be in the program's root directory. If you're running this from eclipse, that's the project's main folder. If you're running this from something like Dr. Java, this would be wherever your .java file is. Depending on what ide you're using to compile and run this, you can Google where the root directory of your project should be.
When you export this as a .jar file, the root directory becomes the directory from which the .jar is being run.
Edit: nevermind, disregard that, I see that the error is occurring on a different line of code. My bad :/
Edit 2: actually, do NOT disregard that, I just realized I was looking at the right line of code - the txt file's location is likely the problem (I think)
Part of your input routine is done in a loop. I'm guessing it is that way to facilitate the lines which (probably) all follow the same pattern (after the first two lines).
The problem is that your loop reads one line an "bits" of the second line. It is the "bits" of the second line being read that is problematic. Those bits prevent the beginning of the loop from reading where you probably want it to start reading.
I would recommend the loop reading just one line, or doing away with the loop and reading both lines before processing (depending on if the file has many or 2 lines of input).
Your code has three calls to in.nextLine() before it starts scanning line for tokens (ie int ID, name and number). This means it skips the two header lines, but also the first line of data.
I also noticed that you are not advancing to the next line once you have finished scanning tokens. So at the end of your while loop another call to in.nextLine() should get you in the right position for the next iteration.
This seems to work with my local testing:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class test {
public static void main(String[] args) throws FileNotFoundException {
Scanner inscan = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputfilename = inscan.nextLine();
File inputfile = new File(inputfilename);
Scanner in = new Scanner(inputfile);
String inputline = in.nextLine();
ArrayList<String> Names = new ArrayList<String>();
in.nextLine();
int total = 0;
while(in.hasNextLine()){
in.nextInt();
String Mname = in.next();
int Number = in.nextInt();
Names.add(Mname);
total += Number;
in.nextLine();
}
in.close();
for (String Mname : Names) {
System.out.println(Mname);
}
System.out.println("total number is " + total);
}
}
So I'm attempting to simulate a very basic search engine by reading a text file filled with data and then have a user search the file using some keywords, and then whichever "websites" contained in the text file that contain that keyword are returned back to the user. My code so far can read the text file (as far as I know), however no matter the entered keyword, the console almost always states that no results can be found (the text file doesn't contain the keyword(s). Thanks everyone.
Here's the appropriate code:
package myquery;
import java.util.Scanner;
import java.util.*;
import java.io.*;
public class MyQuery{
public static void main(String[] args){
Hashtable<String, ArrayList<String> > hash = new Hashtable<String, ArrayList<String> >();
Scanner input = new Scanner(System.in);
System.out.println("Here is where your .txt file(s) should be located for this program to work properly:");
System.out.println(new java.io.File("").getAbsolutePath());
System.out.println("\nEnter the filename that you want to Search values for. For example \"MyQuery.txt\"");
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(input.nextLine()));
System.out.println("The file was found :) Here are the contents:");
while(reader.ready())
{
String currentline = reader.readLine();
String[] result = currentline.split("\\s");
for(int i = 0; i < result.length; i++)
{
if(!hash.containsKey(result[i]))
{
ArrayList<String> temp = new ArrayList<String>(1);
temp.add(currentline);
hash.put(result[i], temp);
}
else
{
ArrayList<String> temp = (ArrayList<String>)hash.get(result[i]);//
temp.add(currentline);
}
}
}
}
catch(Exception e)
{
System.out.println("Your file was not found unfortunately. Please try again.");
System.exit(1);
}
System.out.println(hash);
do
{
System.out.println("Enter a key to search for the value it is associated with.\n");
System.out.println(hash.get(input.nextLine()));
System.out.println("\nWant to try again? If so, press return and then follow the prompt. Type \"-1\" to quit");
}
while(!input.nextLine().equals("-1"));
try
{
reader.close();
}
catch(Exception e)
{
System.out.println(e);
System.exit(1);
}
}
}
And an example of one line in the text file:
www.Mets.com, "The New York Mets", baseball, team, NY
Here's an example of how the program should respond:
Enter a key to search for the value it is associated with.
Mets
www.Mets.com The New York Mets
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit
But here's what I'm getting instead:
Enter a key to search for the value it is associated with:
Mets
null
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit
ALTHOUGH. If I enter a word that matches any word besides the first/last ones, it works.
For example
Enter a key to search for the value it is associated with:
New
[www.Mets.com, "The New York Mets", baseball, team, NY, www.nytimes.com, "The New York Times", news]
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit
I'm currently in an Introductory Java class at University and I'm having a bit of trouble. Last semester we started with Python and I became very acquainted with it and I would say I am proficient now in writing Python; yet Java is another story. Things are alot different. Anyway, Here is my current assignment: I need to write a class to search through a text document (passed as an argument) for a name that is inputted by the user and output whether or not the name is in the list. The first line of the text document is the amount of names in the list.
The text document:
14
Christian
Vincent
Joseph
Usman
Andrew
James
Ali
Narain
Chengjun
Marvin
Frank
Jason
Reza
David
And my code:
import java.util.*;
import java.io.*;
public class DbLookup{
public static void main(String[]args) throws IOException{
File inputDataFile = new File(args[0]);
Scanner stdin = new Scanner(System.in);
Scanner inFile = new Scanner(inputDataFile);
int length = inFile.nextInt();
String names[] = new String[length];
for(int i=0;i<length;i++){
names[i] = inFile.nextLine();
}
System.out.println("Please enter a name that you would like to search for: ");
while(stdin.hasNext()){
System.out.println("Please enter a name that you would like to search for: ");
String input = stdin.next();
for(int i = 0;i<length;i++){
if(input.equalsIgnoreCase(names[i])){
System.out.println("We found "+names[i]+" in our database!");
break;
}else{
continue;
}
}
}
}
}
I am just not getting the output I am expecting and I cannot figure out why.
Try this
You should trim() your values as they have extra spaces
if(input.trim().equalsIgnoreCase(names[i].trim()))
I have run your example it runs perfectly after using trim(), you have missed to trim()
Create a seperate scanner class to read line by line.You can use BufferedReader also.
final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String str= scanner.nextLine();
if(str.contains(name)) {
// Found the input word
System.out.println("I found " +name+ " in file " +file.getName());
break;
}
}
If you use Java 8:
String[] names;
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
names = stream.skip(1).toArray(size -> new String[size]);
} catch (IOException e) {
e.printStackTrace();
}
I need help to read data from text file and give output based on user input.
Here is data I have saved in notepad under "data.txt" file
C|C,370,0.154
C||C,680,0.13
C|||C,890,0.12
C|H,435,0.11
C|N,305,0.15
C|O,360,0.14
C|F,450,0.14
C|Cl,340,0.18
O|H,500,0.10
O|O,220,0.15
O|Si,375,0.16
N|H,430,0.10
N|O,250,0.12
F|F,160,0.14
H|H,435,0.074
this is how I have data in notepad. yes, each entry is separated by comma
I know basic reading operation Scanner class reads line and spits out text from each line but this time I am inputting either number of bonds or bond length and it gives me the output of remaining two value.
Assignment:
No, I am not here to ask you to do homework but rather help me learn the process.
import java.io.*;
import java.io.FileNotFoundException;
import java.util.*;
public class LearnReadText
{
public static void main (String args[]) throws FileNotFoundException
{
Scanner input = new Scanner(System.in);
String strResponse="";
do
{
System.out.println("\nChapter 7");
System.out.println("L - Bond Length");
System.out.println("N - Bond Numbers (1=single, 2=double, 3=triple)\n");
System.out.println("Q - quit program.");
strResponse = input.nextLine();
strResponse = strResponse.toUpperCase();
Scanner file = new Scanner(new File("data.txt"));
file.close();
}
while (!strResponse.equals("Q"));
System.out.println("\n\nThank you and have a nice day.");
input.close();
}
}