Count keeps coming up zero. I'm just trying to read the text file and look for the word, and display the count back to the user.
I'm not sure where it's falling apart. The If statement I think, but not sure where the syntax is going wrong. Thanks for any help!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import javax.swing.*;
public class TextSearchFromFile
{
public static void main(String[] args) throws FileNotFoundException
{
boolean run = true;
int count = 0;
//greet user
JOptionPane.showMessageDialog(null,
"Hello, today you will be searching through a text file on the harddrive. \n"
+ "The Text File is a 300 page fantasy manuscript written by: Adam\n"
+ "This exercise was intended to have the user enter the file, but since \n"
+ "you, the user, don't know which file the text to search is that is a \n"
+ "bit difficult.\n\n"
+ "On the next window you will be prompted to enter a string of characters.\n"
+ "Feel free to enter that string and see if it is somewhere in 300 pages\n"
+ "and 102,133 words. Have fun.",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
while (run)
{
try
{
//open the file
Scanner scanner = new Scanner(new File("An Everthrone Tale 1.txt"));
//prompt user for word
CharSequence findWord = JOptionPane.showInputDialog(null,
"Enter the word to search for:",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
count = 0;
while (scanner.hasNext())
{
if ((scanner.next()).contains(findWord))
{
count++;
}
} //end search loop
//output results to user
JOptionPane.showMessageDialog(null,
"The results of your search are as follows: \n"
+ "Your String: " + findWord + "\n"
+ "Was found: " + count + " times.\n"
+ "Within the file: An Ever Throne Tale 1.txt",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
} //end try
catch (NullPointerException e)
{
JOptionPane.showMessageDialog(null,
"Thank you for using the Text Search.",
"Text Search",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
} //end run loop
} // end main
} // end class
EDIT:
Need help again. The instructor changed the parameters of the project and now I need to find word fragments like "th" or "en" and count those as well.
This I feel is beyond what he has taught and I have no idea how to make that work. I've googled until I can't google anymore.
You have to provide a File Object to Scanner in order to read the file, currently everything is getting searched in a String "An Everthrone Tale 1.txt"
Scanner scanner = new Scanner(new File("An Everthrone Tale 1.txt"));
And for searching a word, you need to do like this:
while (scanner.hasNext())
{
if (findWord.equals(scanner.next()))
{
count++;
}
}
and if you want to perform case-insensitive search then use String#equalsIgnoreCase instead of String#equals
Hope this helps
Related
I'm just getting started with Java (via an edX class), and one of the assignments is to create a vacation planner program that gathers information from the user. When I run the code in terminal, it works, but the strings "name" and "place" are not displayed correctly. Instead, the lines after the string declarations are displayed as "Nice to meet you + name + where are you traveling to?". Am I missing something that would have the input assigned to "name" displayed in the sentence?
The code below is for 1 of 4 methods that will be in the program. Image of my output:
import java.util.Scanner;
public class projectplanner{
public static void main(String[] args) {
partOne();
partTwo();
partThree();
partFour();
}
public static void partOne() {
[enter image description here][1] Scanner input = new Scanner(System.in);
System.out.print("Welcome to Vacation Planner!");
System.out.print("What is your name?" + "");
String name = input.nextLine();
System.out.println("Nice to meet you " + name + "where are you travelling to?");
String place = input.nextLine();
System.out.println("Great! " + place + " sounds like a great trip.");
}
Please help me to figure out how I can get a count of the result when I do a search against a specific folder?
Also how can I ask the user if they want to perform another search?
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
}
}
}
}
If you want to count your matches you can do the following
int i=0;
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
i++;
}
}
System.out.println("Total number of results: " + i);`
As for asking the user, consider using a do-while loop in the following format
do{
// your code
// ask user and read his answer on a string called userChoice
}while (userChoice.equals('y'))
Experiment with our suggestions and you will find the answer easily enough!
I would add a variable
int count = 0;
right before the for loop, and just increment it if it's a match.
This should get you started. I am incrementing the variable count each time a match is found. I am also looping forever so it keeps asking the user for more input.
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
while(true){
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
int count=0;
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
count++;
}
}
}
}
}
Use a while loop and prompt the user to enter a phrase (such as 'exit') if they want to stop. After reading the user input, check the phrase and call a break if it matches the exit phrase.
Use a variable as Robert suggested to count the total number of files found.
package Homework;
import java.util.Scanner;
class FantasyGame{
public static void main ( String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Supercalifragilisticexpialidocious Quest!");
System.out.println("Enter the name of your character: ");
String name;
name = scan.nextLine();
System.out.println("Welcome to Supercalifragilisticexpialidocious Quest, " + (name) + "! " + "You will now assign attributes to your character, the total value assigned must not exceed 15 or be under 0, or the points will be assigned by default! (Type any NUMBER to continue)");
int ans = scan.nextInt();
System.out.println("Enter Strength (0-15): ");
int str = scan.nextInt();
System.out.println("Enter Health (0-15): ");
int hp = scan.nextInt();
System.out.println("Enter Luck (0-15): ");
int lck = scan.nextInt();
if (str + hp + lck <= 15)
{
System.out.println("Congratulations! You have successfully created your character!");
System.out.println("Name: " + (name));
System.out.println("Strength: " + (str));
System.out.println("Health: " + (hp));
System.out.println("Luck: " + (lck));
}
if (str + hp + lck > 15)
{
System.out.println("You have give your character too many attribute points! Default values have been assigned.");
System.out.println("Name: " + (name));
System.out.println("Strength: " + (5));
System.out.println("Health: " + (5));
System.out.println("Luck: " + (5));
}
}
}
I want to make a text-based game for my history class and I know basic Java enough to make a small one with just variables and stuff but I don't know how I can make it so that it runs directly as an applet with a black background and white text that shows up and responds to what you type, like the code above does in the console.
I've tried the command prompt method but all I get is "Access is Denied."
Also, when I try to export in eclipse, the launch configuration always goes to a class I don't want. Sorry but I am really confused and need a lot of help on this.
to write a simple applet, http://docs.oracle.com/javase/tutorial/deployment/applet/ this tutorial from oracle will walk you through it fairly well, it shouldn't be too hard to rearrange your code then
I figured it out. I just exported my program as a .jar and used Jar2Exe and it worked perfectly. Thanks!
You have not made you class public and that is why you are getting error "Access is denied" because it is not visible any more. Compiler is not able to find that class. Just write
....
//change is here
public class FantasyGame
{
....
}
....
Thanks !
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
edit: Write a program to read in 100 words from a file. Then, have the user search for a word until they enter 'quit'.
The program will read in up to 100 words from a file. The file may or may not contain 100 words but the array should hold up to 100 (if the list does not contain enough words, fill the rest of the array with empty strings).
After the file is read in, the program will prompt the user for a search string. The program will then search for the string and tell the user if the word was found or not. The program will continue to get search strings from the user until the user enters 'quit'
Hello I need help write a program to find a word from text file
the result should look like:
Enter a word to search for: taco
Word 'taco' was found.
Enter a word to search for: asd
Word 'asd' was NOT found.
and when user enter the word "quit" the program will quit
below is what I have so far and need help to complete
import java.io.*;
import java.util.Scanner;
public class project2 {
public static void main( String[] args ) throws IOException {
String[] list;
String search;
list = load_list( "words.txt" );
search = prompt_user( "\nEnter a word to search for: " );
while ( ! search.equals( "quit" ) ) {
System.out.println( "Word '" + search + "' was" +
( ( find_word( search, list ) ) ? "" : " NOT" ) +
" found." );
search = prompt_user( "\nEnter a word to search for: " );
}
System.out.println();
}
for(String s: list){
if(s.equals(search)){
//do whatever
}
}
Use this:
Scanner txtscan = new Scanner(new File("filename.txt"));
while(txtscan.hasNextLine()){
String str = txtscan.nextLine();
if(str.indexOf("word") != -1){
System.out.println("EXISTS");
}
}
The below code answers this question perfectly:
String word = ""; int val = 0;
while(!word.matches("quit"))
{
System.out.println("Enter the word to be searched for");
Scanner input = new Scanner(System.in);
word = input.next();
Scanner file = new Scanner(new File("newFile.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
if(line.indexOf(word) != -1)
{
System.out.println("Word EXISTS in the file");
val = 1;
break;
}
else
{
val = 0;
continue;
}
}
if(val == 0)
{
System.out.println("Word does not exist");
}
System.out.println("-------continue or quit--- enter continue or quit");
word = input.next();
}
Write a program with a word containing # character as an input. If the word doesn't contain #, it should prompt the user for a word with #. Once a word with # is read, it should output the word then terminate.
This is what I have done so far:
public class find {
public static void main(String[] args) {
System.out.println(" Please enter a word with # ");
Scanner scan = new Scanner(System.in);
String bad = "#";
String word = scan.next();
do
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
while (!word.contains(bad));
}
}
I can get it to terminate after a word containing "#" is given as input, but if I try to add a Scanner to the line after "please try again", it says while expected.
I think issue is you are missing surrounding braces for do/while:
do
if (!word.contains( bad ))
System.out.println( " Please try again " );
else
System.out.println( " " + word);
while ( !word.contains( bad ));
should be:
do
{
if (!word.contains( bad ))
System.out.println( " Please try again " );
else
System.out.println( " " + word);
}while ( !word.contains( bad ));
Some people may not like this, but my suggestion is always use open/close braces. In this case, for the code if/else also. It avoids lot of confusion.
This is where your problem lies:
do
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
while (!word.contains(bad));
You need to put braces from where the loop starts until it ends. |So this thing should like:
do {
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
} while(!word.contains(bad));
For Better Practice You should Check do...while loops here.
The problem with your code is it is not re-reading the word in your loop.
Modify your loop like this (minimum change to your code).
do {
word = scan.next();
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
}
while (!word.contains(bad));
And yes as others have pointed out try to use braces especially with nested constructs.
There are two issues.
Your code is not using the braces properly
you are not attempting to read the new word if right word is not entered.
Also I prefer while loop better in the case as opposed to do-while loop as below.
Scanner scan = new Scanner ( System.in );
String required= "#";
System.out.println( " Please enter a word with # " );
String word = scan.next() ;
//check if the right word(containing #) is entered,
//if not then loop until it is enteres
while((!word.contains(required)){
System.out.println( " Please try again " );
//read the new word as input from the user
word = scan.next() ;
}
//right word is entered, display it
System.out.println(word);
Also please note that when you use scan.next(), it reads each word separately if entered in the same line.