I am making a method that prints lines in a file which contain a certain word. If the parameter is an empty String, it is supposed to print the entire file.
I've gotten the first part to work. Everything in the "else" statement works great; it scans each line and prints the lines that contain the word in the parameter.
BUT I can't get it to print the whole file when an empty String ("") is entered as the parameter "word". I'm not sure why this is.
public void printLinesWhichContain(String word) {
while (this.reader.hasNextLine()) {
String line = this.reader.nextLine();
if (word.isEmpty()) {
System.out.println(line);
} else {
Scanner lineReader = new Scanner(line);
while (lineReader.hasNext()) {
if (lineReader.next().equals(word)) {
System.out.println(line);
}
}
}
}
}
Once you have the line in String format, you can use the indexOf method to get the index of the word.
I wouldn't create a Scanner for each and every line.
I mean you might want to change the else part as follows.
int indexOfWord = line.indexOf(word);
if (indexOfWord >= 0)
{
System.out.println(line);
}
Related
I am working on a method that takes a scanner as a parameter, and the values of the text file should be added to the doublyLinkedList. Right now the method is working fine but i have an issue where if it encounters a string in the text file, it stops. I want it in such a way that i skip over any line that has a string i tried using the nextLine() but it didnt work.
public static void addList(Scanner input, DoublyLinkedList list){
Number data=null;
if(input.hasNextLine()){
if(input.hasNextInt()){
data=input.nextInt();
list.addEnd(data);
parseScanner(input, list);
}
else if(input.hasNext()){
input.hasNext();
}
}
}
I think in.hasNext() should be input.hasNext()
I think you should use hasNextInt() method of the scanner. If this method will return false, you can just read string and then again try to read int.
if (input.hasNextInt()) {
// read int
} else {
input.nextLine(); // skip line that is not a number
}
I'm learning to code Java with mooc at the moment and am doing an assignment where you take user input (and do stuff with it). The program/loop ends if user inputs nothing and enters.
So this is the right answer which I did correctly:
while (true) {
String sentence = scanner.nextLine();
if (sentence.equals("")) {
break;
}
}
However before this I also tried something like:
while (!scanner.nextLine().equals("")) { // ...
Why does that method not work? I don't see anything wrong with it.
(Below is the whole code if needed)
import java.util.Scanner;
public class AVClub {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (!scanner.nextLine().equals("")) {
String sentence = scanner.nextLine();
String[] array = splitter(sentence);
for (int i = 0; i < array.length; i++) {
if (array[i].contains("av")) {
System.out.println(array[i]);
}
}
}
}
public static String[] splitter(String sentence) {
String[] array = sentence.split(" ");
return array;
}
}
Try using scanner.hasNext() to see if there is anything else that you can read in. Instead of your splitter method, you can use StringTokenizer which will tokenize the String by spaces.
The reason your code does not work is because you are calling Scanner.nextLine() twice. Even though your code:
while (!scanner.nextLine().equals(""))
is a condition check, it reads it in and moves on. Think about it like this: The Scanner is like a book reader. When you call Scanner.nextLine(), the book reader moves to that line and reads it. When you called it again, it read an empty line. For example, if I input this:
Your reader will read in the "I like pie" and check to see that it is not a "". When it is done, and you get your sentence variable, you called the method again, which reads in the NEXT line, which is not there. So your code fails to work.
Hello I am trying to loop a file in java and output only string whose year has 2000 in it.
for some reason when I do .trim().compare(year) it still returns all of the string. I have no idea why
example of string in file are
20/04/1999-303009
13/04/2000-2799
06/10/1999-123
out of these 3 for example I want to get only 13/04/2000-2799 (note the file is huge)
Here is my code I came up with so far:
public static void main(String[] args) throws IOException {
//Initiating variables
String filedir =("c://test.txt");
ArrayList<String> list = new ArrayList<String>();
String year = "2000";
try (Scanner scanner = new Scanner(new File(filedir))) {
while (scanner.hasNextLine()){
// String[] parts = scanner.next().split("-");
if (scanner.nextLine().trim().contains(year)) {
System.out.println(scanner.nextLine());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
You are using scanner.nextLine() two times. That's an error. Call it's only once per iteration and assign the result to String value for usage.
You're calling scanner.nextLine() twice, which means that once you found a matching line, you are actually printing the next one.
the problem in your code is in the while block:
while(scanner.hasNextLine()){
//This first call returns 13/04/2000-2799
if(scanner.nextLine().trim().contains(year)){//This line finds matching value
//But this line prints the next line
System.out.println(scanner.nextLine());//this call returns 06/10/1999-123
}
}
What you could do is store the value you need in a variable and if it matches the year then you print it:
while(scanner.hasNextLine()){
//You store the value
String value = scanner.nextLine().trim();
//See if it matches the year
if(value.contains(year)){
//Print it in case it matches
System.out.println(value);
}
}
Hope this helps.
public String compWord() throws IOException, ClassNotFoundException
{
// Local constants
final int MAX_COUNT = 8;
// Local variables
BufferedReader reader = new BufferedReader(new FileReader("dictionary.txt")); // Create a new BufferedReader, looking for dictionary.txt
List<String> lines = new ArrayList<String>(); // New ArrayList to keep track of the lines
String line; // Current line
Random rand = new Random(); // New random object
String word; // The computer's word
/********************* Start compWord *********************/
// Start reading the txt file
line = reader.readLine();
// WHILE the line isn't null
while(line != null)
{
// Add the line to lines list
lines.add(line);
// Go to the next line
line = reader.readLine();
}
// Set the computers word to a random word in the list
word = lines.get(rand.nextInt(lines.size()));
if(word.length() > MAX_COUNT)
compWord();
// Return the computer's word
return word;
}
From what I understand it should only be returning words less than 8 characters? Any idea what I am doing wrong? The if statement should recall compWord until the word is less than 8 characters. But for some reason I'm still get words from 10-15 chars.
Look at this code:
if(word.length() > MAX_COUNT)
compWord();
return word;
If the word that is picked is longer than your limit, you're calling compWord recursively - but ignoring the return value, and just returning the "too long" word anyway.
Personally I would suggest that you avoid the recursion, and instead just use a do/while loop:
String word;
do
{
word = lines.get(rand.nextInt(lines.size());
} while (word.length() > MAX_COUNT);
return word;
Alternatively, filter earlier while you read the lines:
while(line != null) {
if (line.length <= MAX_COUNT) {
lines.add(line);
}
line = reader.readLine();
}
return lines.get(rand.nextInt(lines.size()));
That way you're only picking out of the valid lines to start with.
Note that using Files.readAllLines is a rather simpler way of reading all the lines from a text file, by the way - and currently you're not closing the file afterwards...
If the word is longer than 8 characters, you simply call your method again, continue, and nothing changes.
So:
You are getting all the words from the file,
Then getting a random word from the List, and putting it in the word String,
And if the word is is longer than 8 characters, the method runs again.
But, at the end, it will always return the word it picked first. The problem is that you just call the method recursively, and you do nothing with the return value. You are calling a method, and it will do something, and the caller method will continue, and in this case return your word. It does not matter if this method is recursive or not.
Instead, I would recommend you use a non-recursive solution, as Skeet recommended, or learn a bit about recursion and how to use it.
I'm reading in a text file formated like
word
definiton
word
definition
definition
word
definition
So I need to keep try of whether I'm in a definition or not based on when I reach those emtpy lines. Thing is, BufferedReader discards \n characters, and somehow comparing that empty line to String "" is not registering like I thought it would. How can I go about doing this.
Make sure you use: "".equals(myString) (which is null-safe) not myString == "".
After 1.6, you can use myString.isEmpty() (not null-safe)
You can use myString.trim() to get rid of extra whitespace before the above check
Here's some code:
public void readFile(BufferedReader br) {
boolean inDefinition = false;
while(br.ready()) {
String next = br.readLine().trim();
if(next.isEmpty()) {
inDefinition = false;
continue;
}
if(!inDefinition) {
handleWord(next);
inDefinition = true;
} else {
handleDefinition(next);
}
}
}
The BufferedReader.readLine() returns an empty string if the line is empty.
The javadoc says:
Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.
If you don't appear to be seeing an empty String, either the line is not empty, or you are not testing for an empty String correctly.
line = reader.readLine();
if ("".equals(line)) {
//this is and empty line...
}
I do not know how did you try to check that string is empty, so I cannot explain why it did not work for you. Did you probably use == for comparison? In this case it did not work because == compares references, not the object content.
This code snippets skips the empty line and only prints the ones with content.
String line = null;
while ((line = br.readLine()) != null) {
if (line.trim().equals("")) {
// empty line
} else {
System.out.println(line);
}
}
Lines only containing whitespace characters are also skipped.
try (BufferedReader originReader = getReader("now")) {
if (StringUtils.isEmpty(originReader.readLine())) {
System.out.printline("Buffer is empty");
}