I'm reading a text file line by line and converting it into a string.
I'm trying to figure out how to check if the last line of the file is a specific word ("FILTER").
I've tried to use the endsWith(String) method of String class but it's not detecting the word when it appears.
Rather naive solution, but this should work:
String[] lines = fileContents.split("\n");
String lastLine = lines[lines.length - 1];
if("FILTER".equals(lastLine)){
// Do Stuff
}
Not sure why .endsWith() wouldn't work. Is there an extra newline at the end? (In which case the above wouldn't work). Do the cases always match?
.trim() your string before checking with endsWith(..) (if the file really ends with the desired string. If not, you can simply use .contains(..))
public static boolean compareInFile(String inputWord) {
String word = "";
File file = new File("Deepak.txt");
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
word = input.next();
if (inputWord.equals(word)) {
return true;
}
}
} catch (Exception error) {
}
return false;
}
With
myString.endsWith("FILTER")
the very last characters of the last line are checked. Maybe the method
myString.contains("FILTER")
is the right method for you? If you only want to check the last ... e.g.20 chars try to substring the string and then check for the equals method.
Related
I am trying to allow an input that is only made with characters a-zA-Z and also haves space. Example: "Chuck Norris".
What happens with the code below is that the scanner input.next() doesn't allow the mentioned example input string.
I expect this output: Success! but this is the actual output: Again:
try {
String input_nome = input.next(); // Source of the problem
if (input_nome.matches("[a-zA-Z ]+")) {
System.out.print("Success!");
break;
} else {
System.err.print("Again: ");
}
} catch (Exception e) {
e.printStackTrace();
}
SOLUTION
The source of the problem is the used scanner method.
String input_nome = input.next(); // Incorrect scanner method
String input_nome = input.nextLine(); // Correct scanner method
Explanation: https://stackoverflow.com/a/22458766/11860800
String t = "Chuck Norris";
t.matches("[a-zA-Z ]+")
Does in fact return true. Check for your input that it actually is "Chuck Norris", and make sure the space is not some weird character. Also instead of space, you can use \s. I also recommend 101regex.com
Please refer this link :
Java Regex to Validate Full Name allow only Spaces and Letters
you can use the below Regular Expression
String regx = "^[\\p{L} .'-]+$";
This should work for all scenarios and unicode.
I am trying to compare a .txt file that has a list of words, and a String[] array that is also filled with words.
Solved thank you.
Assuming you're ultimately just trying to get a list of words that are in both files:
Scanner fileReader = new Scanner(file);
Set<String> words = new HashSet<>();
while (fileReader.hasNext()) {
String s = fileReader.next();
words.add(s);
}
fileReader.close();
Scanner otherFileReader = new Scanner(otherFile);
List<String> wordsInBothFiles = new ArrayList<>();
while (otherFileReader.hasNext()) {
String s = otherFileReader.next();
if (words.contains(s)) {
wordsInBothFiles.add(s);
}
}
otherFileReader.close();
// Do whatever it is you have to do with the shared words, like printing them:
// for (String s : wordsInBothFiles) {
// System.out.println(s);
// }
If you check the documentation it will usually explain why a method throws an exception. In this case "no line was found" means you've hit the end of your file. There are two possible ways this error could come about:
String nextLine = scanner.nextLine(); //problem 1: reads a file with no lines
while (scanner.hasNextLine()) {
linearSearch(words,nextLine);
System.out.println(nextLine);
}
scanner.nextLine(); //problem 2: reads after there is not next line
Since you loop appears to be infinite I'd wager you're getting the exception from the first line and can fix it by adding the following check before String nextLine = scanner.nextLine();:
if(!scanner.hasNextLine()) {
System.out.println("empty file: "+filePath)
return; //or break or otherwise terminate
}
Beyond that you may still have some other issues but hopefully this resolves your present problem.
this is my first post so forgive me if i have posted incorrectly. I have a task that i need to complete but i cant get it to work properly. the compiler that i use is bluej. what i need to do is to use scanner to read a text file and compare a user input to the text file. if the input string compares then it should print out that ""The word is on the text file". Unfortunately i cant get this to work. My code reads the file because it prints out to the console but no comparison it s happening. please have a look at my code and give me some pointers. i have been trying to use .equals():
private boolean searchFromRecord(String recordName, String word) throws IOException
{
// Please write your code after this line
File file = new File(recordName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
for(int i = 0; scanner.hasNextLine(); i++){
String compare = scanner.nextLine();
IO.outputln("word#" + i + ":" + compare);
}
scanner.close();
if (scanner.equals(word)){
return true;
} else{
return false;
}
}
return true;
}
this is what i get output in the console:
Input a word: IRON
AA 888
word#0:BULLET
word#1:1
word#2:AE 1688
word#3:CHEERS
word#4:GAMES
word#5:IRON MAN
word#6:WOLF
word#7:Testing
word#8:Wonderful
The word "IRON" is not in the record.
Here are some problems, along with why they are problems & a suggestion on how they could be fixed:
Problem: closing a scanner within the a loop that uses it will cause an exception. Reason: after we go through the loop once, the scanner will be closed. when we loop through again, an error will occur since the loop uses the scanner, which means the scanner should be "open". Possible solution: move scanner.close() to after the while loop.
Problem: we shouldn't return true at the end of this method. Reason: I'm guessing that this method is supposed to return true if the word is found, and false otherwise. Now, the only way to get to this return statement is if our word doesn't exist in the recordFile; it should return false. Possible solution: return false at the end of the method instead.
Problem: the first line in recordFile will never be checked for equality with word Reason: each method call of scanner.nextLine() will return each line from the recordFile as a String once and only once. In your code, it is called once in the beginning of the while loop's body, but not used to compare with word, then after, it is used in the for loop for comparison Possible solution: remove the line: System.out.println(scanner.nextLine());.
Problem: scanner.equals(word) will probably always return false. Reason: scanner is a Scanner, and word is a String, they should never be equal. Possible solution: replace scanner.equals(word) with compare.equals(word)
Problem: word is not actually compared with each compare. Reason: it is outside the for loop. Possible solution: move the if else block into the end of the for loop's body.
I don't think the while loop is really needed. I strongly recommend that the while loop, is removed, but keep the body.
Problem: Moving the if else block into the for loop, and above the scanner.close() means that the scanner.close() will never be run. Reason: once a return statement is executed, the flow of control immediatly exits the method, and returns to where the method was invoked which makes code after return statements useless. Possible solution: instead of returning right away, declare some sort of boolean variable that will store the return value. have the return value be modified throughout the method, then return the variable at the very end, after scaner.close()
There are many many other ways to fix each of these problems other than the ones suggested here.
I hope you find this helpful! :)
your code, refactored to implement the suggested solutions above:
private boolean searchFromRecord(String recordName, String word) throws IOException {
// Please write your code after this line
Boolean wordFound = false; // indicates if word exists in recordFile.
File file = new File(recordName); // file at path "recordName"
Scanner scanner = new Scanner(file); // reads records from "file"
// iterate through the recordFile, to see if "word" already exists
// within recordFile.
for(int i = 0; scanner.hasNextLine(); i++) {
// read the record from the file
String compare = scanner.nextLine();
IO.outputln("word#" + i + ":" + compare);
// compare the record with our word
if (compare.equals(word)){
wordFound = true;
break; // bail out of loop, our work here is done
}
}
// clean up, and return...
scanner.close();
return wordFound;
}
First, scanner is not a String and it will not equal a String. Second, you are dropping lines - scanner.nextLine() gets the next line, and you print it (but don't save it or compare it). I think you wanted something more like this,
// eats and tosses input.
// System.out.println(scanner.nextLine());
String line = scanner.nextLine();
for(int i = 0; scanner.hasNextLine(); i++){
String compare = scanner.nextLine();
IO.outputln("word#" + i + ": " + compare + " to line: " + line);
if (line.contains(compare)){ // "IRON MAN" starts with "IRON", it doesn't equal IRON.
return true;
}
}
scanner.close();
return false; // <-- default.
Another flavor is to read the whole file into a String variable and look for specified String inside the String.
Code:
File file = new File("C:\\Users\\KICK\\Documents\\NetBeansProjects"
+ "\\SearchWordinFile\\src\\searchwordinfile\\words.txt");
String s="";
try(Scanner input = new Scanner(file)){
input.useDelimiter("\\A");
if (input.hasNext()) {
s = input.next();
}
}catch(Exception e){
System.out.println(e);
}
if(s.contains("IRON"))
System.out.println("I found IRON");
}
Output:
I found IRON
My File content
BULLET
1
AE 1688
CHEERS
GAMES
IRON MAN
WOLF
Testing
Wonderful
I'm having trouble printing out the final result without each word being on its own line. The output should be formatted just as the input was. Here is the code I used to read the data and print it:
Scanner sc2 = null;
try {
sc2 = new Scanner(new File(dataFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
boolean b;
while (b = s2.hasNext()) {
String s = s2.next();
System.out.println(pig(s));
}
}
The actual instructions were as follows: "Translate the Declaration of Independence ("declaration.txt") into PigLatin. Try to preserve the paragraphs. There are several ways to do this, but they all use nested loops. You may want to look at nextLine, next, split, or StringTokenizer."
We haven't been taught how to use any of the methods listed there, though.
The println method is short for "print line". It prints the given output to the target output device followed by a newline. Check out the other methods in that class for the solution.
Update
The problem here is that to my knowledge java.util.Scanner throws out the whitespace (delimiter) between words. Check out java.util.StringTokenizer for a similar class that can be configured to return the whitespace characters one at a time.
I am expecting input with the scanner until there is nothing (i.e. when user enters a blank line). How do I achieve this?
I tried:
while (scanner.hasNext()) {
// process input
}
But that will get me stuck in the loop
Here's a way:
Scanner keyboard = new Scanner(System.in);
String line = null;
while(!(line = keyboard.nextLine()).isEmpty()) {
String[] values = line.split("\\s+");
System.out.print("entered: " + Arrays.toString(values) + "\n");
}
System.out.print("Bye!");
From http://www.java-made-easy.com/java-scanner-help.html:
Q: What happens if I scan a blank line with Java's Scanner?
A: It depends. If you're using nextLine(), a blank line will be read
in as an empty String. This means that if you were to store the blank
line in a String variable, the variable would hold "". It will NOT
store " " or however many spaces were placed. If you're using next(),
then it will not read blank lines at all. They are completely skipped.
My guess is that nextLine() will still trigger on a blank line, since technically the Scanner will have the empty String "". So, you could check if s.nextLine().equals("")
The problem with the suggestions to use scanner.nextLine() is that it actually returns the next line as a String. That means that any text that is there gets consumed. If you are interested in scanning the contents of that line… well, too bad! You would have to parse the contents of the returned String yourself.
A better way would be to use
while (scanner.findInLine("(?=\\S)") != null) {
// Process the line here…
…
// After processing this line, advance to the next line (unless at EOF)
if (scanner.hasNextLine()) {
scanner.nextLine();
} else {
break;
}
}
Since (?=\S) is a zero-width lookahead assertion, it will never consume any input. If it finds any non-whitespace text in the current line, it will execute the loop body.
You could omit the else break; if you are certain that the loop body will have consumed all non-whitespace text in that line already.
Scanner key = new Scanner(new File("data.txt"));
String data = "";
while(key.hasNextLine()){
String nextLine = key.nextLine();
data += nextLine.equals("") ? "\n" :nextLine;
}
System.out.println(data);
AlexFZ is right, scanner.hasNext() will always be true and loop doesn't end, because there is always string input even though it is empty "".
I had a same problem and i solved it like this:
do{
// process input
}while(line.length()!=0);
I think do-while will fit here better becasue you have to evaluate input after user has entered it.