mardi 25 octobre 2016

Java - Searching through a file without using a list

I'm trying to create a program that will let a user search through a file for a specific word, without creating an array and adding all the contents of the file to it (so it could be easily ported and used with different file sizes etc). Below is my code:

package test2;

import java.io.InputStream;
import java.util.Scanner;
import javax.swing.JOptionPane;

/**
 *
 * @author Kafaka157
 */
public class Prep2 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    InputStream stream = Prep1.class.getResourceAsStream("words.txt");
    Scanner scanner = new Scanner(stream);             

    while(scanner.hasNextLine()){

        String word = JOptionPane.showInputDialog("Input word to look for: ");

        if(word.equals(scanner.next().trim())){
            JOptionPane.showMessageDialog(null, word + " found"); // found
            break;
        }else{
            JOptionPane.showMessageDialog(null,word + " not found"); // not found
            break;
        }
    }
  }
}

The above is my code, I get no build errors or anything, however it won't return found on words which I know are in the file. It seems to default to else at every instance, any help / idea where I'm going wrong? Many thanks.

Aucun commentaire:

Enregistrer un commentaire