Compare input to a specific line saved in a text file JAVA - java

In order to validate a country entered by the user, I'm trying to have that country input compared to a list of countries stored in a text file. If the input matches a country stored in the text file, the validCountry would be set to 'true' and the program would be able to proceed.This is what I've got so far:
Scanner sc = new Scanner (System.in);
String country = "";
boolean validCountry = false;
while (!validCountry)
{
System.out.print("Country: ");
String countryIn = sc.next();
try{
Scanner scan = new Scanner(new File("countries.txt"));
while (scan.hasNext()) {
String line = scan.nextLine().toString();
if(line.contains(countryIn))
{
country = line;
validCountry = true;
}
}
}catch(Exception e)
{
System.out.print(e);
}
}
The above simply loops for me to re-input the country (implying that it is invalid).
This is what the countries.txt file looks like (obviously contains all the countries of the world not just the first few starting with 'A' :
Afghanistan
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
...
I'm sure it's a very simple and minor error which I can't seem to find; but I've been trying to detect it for a while but to no avail. I've checked multiple other stackoverflow answers but they didn't seem to work either. I truly appreciate any form of help :)
Please let me know if my question needs further clarification.

I tested the code and it works for me.
I initialized your variable sc like this:
Scanner sc = new Scanner(System.in);
Note that it would be better to load the file outside the while loop (for better performance)

Assuming that in String countryIn = sc.next(); the sc is a scanner that use System.in, change the .next() into nextLine():
String countryIn = sc.nextLine();
then, you should also change if(line.contains(countryIn)) because it will return true even if the given line is a substring of a country (afg will be found in afghanistan even though afg is not in the country list. use equalsIgnoreCase instead:
if (line.equalsIgnoreCase(countryIn)) {
...
}
Try if this class works:
import java.util.Scanner;
import java.io.File;
public class Country {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String country = "";
boolean validCountry = false;
while (!validCountry)
{
System.out.print("Country: ");
String countryIn = sc.nextLine();
try{
Scanner scan = new Scanner(new File("countries.txt"));
while (scan.hasNext()) {
String line = scan.nextLine();
if(line.equalsIgnoreCase(countryIn))
{
country = line;
validCountry = true;
break;
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}

Problem solved, the countries.txt file I had was encoded in UNICODE. All I had to do was change it to ANSI.

Related

replacing a string deletes everything in text

I'm trying to write a program for this question: "Write a program that will ask a string and a file name from the user and then removes all the occurrences of that string from that text file."
This is what I have so far:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class RemoveText {
public static void main(String[] args){
//creates a scanner to read the user's file name
Scanner input = new Scanner(System.in);
System.out.println("Enter a file name: ");
String fileName = input.nextLine();
java.io.File file = new java.io.File(fileName);
java.io.File newFile = new java.io.File(fileName);
Scanner stringToRemove = new Scanner(System.in);
System.out.println("Enter a string you wish to remove: ");
String s1 = stringToRemove.nextLine();
//creating input and output files
try {
Scanner inputFile = new Scanner(file);
//reads data from a file
while(inputFile.hasNext()) {
s1 += inputFile.nextLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//supposed to replace each instance of the user input string
//but instead deletes everything on the file and i don't know why
String s2 = s1.replaceAll(s1, "");
try {
PrintWriter output = new PrintWriter(newFile);
output.write(s2);
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//closing various scanners
input.close();
stringToRemove.close();
}
}
But for some reason, instead of replacing the string with whitespace, the entire text file becomes empty. What am I doing wrong?
Edit: Okay, so I took everyone's advice and managed to fix the variable problem by introducing a third String variable and using more descriptive variable names.
Scanner s1 = new Scanner(System.in);
String stringToRemove = s1.nextLine();
String fileContents = null;
try {
//stuff here
while (inputFile.hasNextLine()) {
fileContents += inputFile.nextLine();
} catch { //more stuff }
String outputContent = fileContents.replaceAll(stringToRemove, "");
My issue now is that the beginning of the new file starts with "null" before relaying the new content.
String s2 = s1.replaceAll(s1, "");
the first parameter of replaceAll method is what you are looking for to replace, and you are looking for s1, you are saying with this code clean all s1 content...
Where you went wrong is that you appended the file content to s1 which is the string you want to remove.
Try introduce s3 and then do
s2 = s3.replaceAll(s1, "");

Searching a list of names in a text file from user input

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();
}

Searching for a particular line of text in a text file

I am having issues with my synonym map. I want to be able to search a text file for a keyword or a related word in the textfile then outputting the found sentence. so my program searches for the answers to questions based on the keyword or sunonym. the way my program works is by searching a text file for a keyword in the question and then outputting the answer to the question which is the next line after then question in the text file. When i search for the main keyword in a question the program works. But when i try to ask a question with the related word the program does not recognize the input. So for example if i enter "how is the major?" the answer to that question is on the next line which is "the major is difficult" but if i enter "how is the focus" the program does not recognize the related word focus Can someone help me find the issue which lies in searching for a related word also. Here is my text file
what is the textbook name?
the textbook name is Java
how is the major?
the major is difficult
how much did the shoes cost?
the shoes cost two dollars
how is the major when cramer took it?
when cramer took it, it was okay
how is the major when jar took it?
jar said it was fine
what is the color of my bag?
the color of my bag is blue
and here is my code
public static class DicEntry {
String key;
String[] syns;
Pattern pattern;
public DicEntry(String key, String... syns) {
this.key = key;
this.syns = syns;
pattern = Pattern.compile(".*(?:"
+ Stream.concat(Stream.of(key), Stream.of(syns))
.map(x -> "\\b" + Pattern.quote(x) + "\\b")
.collect(Collectors.joining("|")) + ").*");
}
}
public static void parseFile(String s) throws IOException {
List<DicEntry> synonymMap = populateSynonymMap(); // populate the map
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
Scanner forget = new Scanner(System.in);
int flag_found = 0;
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
for (DicEntry entry : synonymMap) { // iterate over each word of the
// sentence.
if (entry.pattern.matcher(s).matches()) {
if (lineFromFile.contains(entry.key)) {
//String bat = entry.key;
if(lineFromFile.contains(s)) {
String temp = scanner.nextLine();
System.out.println(temp);
}
}
}
}
}
}
private static List<DicEntry> populateSynonymMap() {
List<DicEntry> responses = new ArrayList<>();
responses.add(new DicEntry("bag", "purse", "black"));
responses.add(new DicEntry("shoe", "heels", "gas"));
responses.add(new DicEntry("major", "discipline", "focus", "study"));
return responses;
}
public static void getinput() throws IOException {
Scanner scanner = new Scanner(System.in);
String input = null;
/* End Initialization */
System.out.println("Welcome ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
parseFile(input);
}
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
getinput();
}
}
It would seem that after you pass
if (lineFromFile.contains(entry.key))
in your parseFile(String s) method, you would want to know if your user entered input contains any of the entry.syns and replace the synonym with the key
// This is case sensitive
boolean synonymFound = false;
for (String synonym : entry.syns) {
if (s.contains(synonym)) {
s = s.replace(synonym, entry.key)
break;
}
}
Since you want to stop searching once you find a match (exact or synonym match), you'll want to have a return statement to kick out of the method or use a flag to kick out of the while (scanner.hasNextLine())
if (lineFromFile.contains(s)) {
String temp = scanner.nextLine();
System.out.println(temp);
flag_found = 1;
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
// String black = scanner.nextLine();
removedata(temp);
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
// Add return statment to end the search
return;
}
Results:

Why is my String not outputting my value correctly?

I Have a simple program where I just prompt to enter an item and the while loop will continue to ask until I enter the word "end" then it will end the program. When I enter a word like so:
it looks fine, But when I enter 2 words for an item as such I get this output:
notice how when i entered "green yellow" It prompted me after that to enter an item twice?
I can't figure out why it is doing so?
import java.util.Scanner;
public class ToDoListapp {
public static void main(String[] args) /*throws IOException*/ {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Welome to your TodoList");
boolean keepAdd = true;
String item;
//file
//PrintWriter writeFile = new PrintWriter("TodoList.txt", "UTF-8");
// File file = new File("ToDo.txt");
// BufferedWriter writeTo = new BufferedWriter(new FileWriter(file));
while (keepAdd)
{
System.out.println("Enter an item: ");
item = sc.next();
if (item.equals("end"))
{
keepAdd = false;
}
// writeTo.write(item + "\n");
}
//writeTo.close();
}
}
The default behavior of Scanner is to use whitespace as a delimiter which will be used to break input into tokens. If you just want to use the newline character as a delimiter, try to set the delimiter explicitly.
Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));
System.out.println("Welome to your TodoList");
boolean keepAdd = true;
String item;
// The rest of your code
see http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html.
By default it uses any whitespace as the delimiter. So, the call to sc.next() already has its answer with the input green yellow.

Searching content of a file

I dont have alot of experience working with files. I have a file. I have written the following to the file
Test 112
help 456
news 456
Friendly 554
fileOUT.write("Test 112\r\n");//this is a example of how I entered the data.
Now I am trying to search in the file for the word news and display all the content that is in that line that contains the word news.
This is what I have attempted.
if(fileIN.next().contains("news")){
System.out.println("kkk");
}
This does not work. The folowing does find a word news because it displays KKK but I dont have an Idea how to display only the line that it news was found in.
while(fileIN.hasNext()){
if(fileIN.next().contains("Play")){
System.out.println("kkk");
}
}
What must be displayed is news 456.
Thank You
You want to call fileIN.nextLine().contains("news")
Try using the Scanner class if you are not already. It does a wonderful job of splitting input from a stream by some delineator (in this case the new line character.)
Here's a simple code example:
String pathToFile = "data.txt";
String textToSearchFor = "news";
Scanner scanner = new Scanner(pathToFile);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.contains(textToSearchFor)){
System.out.println(line);
}
}
scanner.close();
And here's an advanced code example that does much more than you asked. Enjoy!
//Search file for an array of strings. Ignores case if caseSensitive is false.
public void searchFile(String file, boolean caseSensitive, String...textToSearchFor){
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
String originalLine = scanner.nextLine();
String line = originalLine;
if(!caseSensitive) line = line.toLowerCase();
for(String searchText : textToSearchFor){
if(!caseSensitive) searchText = searchText.toLowerCase();
if(line.contains(searchText)){
System.out.println(originalLine);
break;
}
}
}
scanner.close();
}
//usage
searchFile("data.txt",true,"news","Test","bob");
searchFile("data.txt",true,new String[]{"test","News"});
you can try this code...:D
String s = null;
File file = new File(path);
BufferedReader in;
try {
in = new BufferedReader(new FileReader(file));
while (in.ready()) {
s = in.readLine();
if(s.contains("news")){
//print something
}
}
in.close();
} catch (Exception e) {
}

Categories