Hello so i have an assignment and my code is not working. I ask a user to input a filename and after that it freezes and does not process the number of lines. im doing something wrong but im not sure what? can someone please help me im really desperate this part is crashing my whole program and i might fail and i dont know who to ask :( for help
public static void fileReader()
{
Scanner sc = new Scanner(System.in);
int catNum;
int dogNum;
int fishNum;
String fileName;
System.out.println("Please enter the Name of the file you want to read in
from");
fileName = sc.nextLine();
System.out.println("this is the file name --> "+fileName);
catNum = TestFile.getNum(fileName, "cat");
dogNum = TestFile.getNum(fileName, "dog");
fishNum = TestFile.getNum(fileName, "fish");
System.out.println("THE CAT IS" +catNum);
System.out.println("THE DOG IS" +dogNum);
System.out.println("THE FISH IS" +fishNum);
}
i dont see anything wrong after i ask for the file name it freezes
public static int getNum (String fileName, String word) {
Scanner sc = new Scanner(System.in);
int lineNum = 0;
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
try {
fileStrm = new FileInputStream (fileName);
rdr = new InputStreamReader (fileStrm);
bufRdr = new BufferedReader (rdr);
line = bufRdr.readLine();
while (line != null)
{
String firstWord = processString(line);
if(firstWord.equalsIgnoreCase(word)) //this submodule i going to get the number to create each array like e.g. how many states so that it can create it in country object
{
lineNum++;
line = bufRdr.readLine() ;
}
}
fileStrm.close();
}
catch (IOException e)
{
if (fileStrm != null)
{
try
{
fileStrm.close();
}
catch(IOException ex2)
{
System.out.println("This is Error");
}
}
System.out.println("error reading file !!" +e.getMessage());
}
return lineNum; }
the file looks something like this (each line is like this):
CAT:NAME=doopie:SHORTNAME=doop:LANGUAGE=English:AREA=America:POPULATION=2222:POPREF=Census2016
Look at this while loop:
while (line != null)
{
String firstWord = processString(line);
if(firstWord.equalsIgnoreCase(word)) //this submodule i going to get the number to create each array like e.g. how many states so that it can create it in country object
{
lineNum++;
line = bufRdr.readLine() ;
}
}
If firstWord.equalsIgnoreCase(word) returns false, then what will happen? The value of line will never be updated and the loop will never exit.
Related
I'm trying to write a do while loop that will read a file that the user input and read it out and will loop until the user types end. The do part is working, but my while just isn't being activated and I'm struggling to figure out why.
public static void readingFiles() throws Exception {
BufferedReader reader = null;
Scanner input = null;
boolean fileFound = true;
do {
System.out.print("Enter a file name or Type END to exit: ");
input = new Scanner(System.in);
if(input.hasNextLine())
{
try {
File f = new File(input.nextLine());
reader = new BufferedReader(new FileReader(f));
String str = null;
while((str = reader.readLine()) != null)
{
System.out.println(str);
}
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found. Please try again.");
fileFound = false;
continue;
}
catch (IOException e)
{
System.out.println("There was an IOException. Please try again.");
continue;
}
catch (Exception e)
{
System.out.println("There was an exception. Please try again.");
continue;
}
finally
{
{
if(fileFound)
reader.close();
}
}
}
} while(!input.nextLine().equalsIgnoreCase("end"));
}
I've tried using an if statement before my input.hasNextLine() but then it would ignore the rest of the whole program and do nothing and only typing end would work. I've tried using && in my current if statement too but that didn't work. And I tried using a boolean that I set to true if string contained end. I think the problem may be in the input.hasNextLine but I'm not sure why or what to change it to?
Thanks for any help
Calling input.nextLine() again will not preserve your previous input string.
Store it in a variable, and compare that
public static void readingFiles() throws Exception {
BufferedReader reader = null;
String filename = null;
Scanner input = new Scanner(System.in);
boolean fileFound = true;
do {
System.out.print("Enter a file name or Type END to exit: ");
if(input.hasNextLine()) {
filename = input.nextLine();
try {
File f = new File(filename);
// reader =
...
} while (!filename.equalsIgnoreCase("end");
I'm having issues with using try-catch blocks in java. I'm writing a method that reads a user input file and prints it out to the console. This is what I have -
static Scanner input = new Scanner(System.in);
public static String readingFiles(String fileout) {
boolean find = false;
while(!find) {
try {
File f = new File(input.nextLine());
Scanner scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
}
}
ArrayList<String> list = new ArrayList<String>();
while (input.hasNext())
{
list.add(input.nextLine());
}
String output = list.toString();
return output;
}
It just seems like a mess and I have no idea what to do with it at this point. I had it working a few times, in that it would output what the file said but then if I purposefully entered the wrong file name it would loop "file not found" endlessly and I couldn't figure out how to return the loop to the beginning so the user could input a different file name.
Now it just does nothing even when i enter the correct file name, it returns nothing until i press enter again and it'll return file not found.
I call it using this in my main menu method -
case 1:
System.out.println("You chose Read File. Enter your file name: ");
System.out.println(Question4.readingFiles(input.nextLine()));
pressEnter();
break;
edit: I now have this, which works but only prints the first line of my file?
public static String readingFiles(String fileout) {
boolean find = false;
String result = "";
while (!find) {
try {
File read = new File(fileout);
Scanner check = new Scanner(read);
result = check.nextLine();
find = true;
check.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found. Please try again.");
break;
}
}
return result;
}
Check the following code.
public static void readFiles() throws Exception {
int i = 1;
BufferedReader reader = null;
Scanner input = null;
boolean fileFound = true;
while(i <= 5){
System.out.print("Enter a file name::::");
input = new Scanner(System.in);
if(input.hasNextLine()){
try {
File f = new File(input.nextLine());
reader = new BufferedReader(new FileReader(f));
String str = null;
while((str = reader.readLine()) != null){
System.out.println(str);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
fileFound = false;
i++;
continue;
} catch (IOException e) {
System.out.println("IOException");
i++;
continue;
} catch (Exception e) {
System.out.println("Some Other Exception");
i++;
continue;
} finally{
if(fileFound)
reader.close();
}
}
i++;
}
}
Please note this method will read files 5 times. If you want to change it, you can pass an int parameter to the method and accordingly change the first while condition. Ensure you give complete path of the file with escape characters. For example, if file location is 'C:\abc.txt', you need to input 'C:\\abc.txt'. Else, it will display 'File Not Found' in console.
public class readingFiles {
public static String readingFiles(String fileout) {
try {
//find a file with the same name as the value of "fileout"
File f = new File(fileout);
Scanner scan = new Scanner(f);
//create a list to hold the file output
ArrayList<String> list = new ArrayList<String>();
//loop through the output line by line and add to the list
while (scan.hasNext())
{
list.add(scan.nextLine());
}
//convert the list into a String value to pass back to the caller
String output = list.toString();
scan.close();
return output;
} catch (FileNotFoundException e) {
//if file is not found, return a value of -1
System.out.println("File Not Found.");
return("-1");
}
}
Okay a few things:
Your first while loop is unnecessary. I think you are trying to loop through files in the folder to look for a specific file name. However the Scanner scan = new Scanner(f); line already does this.
The reason your code infinitely prints "File not found." is because you never set the find condition to true to exit the loop.
You never use the fileout value you pass into the method. And your code asks the user for the filename input twice (once in the main method, once in the readingFiles method).
Using a list, then converting to String results in an output of [line1, line2, line3, etc] not sure if this is what you want.
As for why your second attempt prints only the first line, You have removed the while loop which loops through the file reading every line, therefore it only reads one line before stopping.
I am having an issue trying to search a text file for the exact input that a user enters. I want to output the sentence not only by direct user input but i want the program to recognize some word(s) that would signal the desired text. I got searching for the keyword part down pack and working but i am only able to search the text based on the keyword. I want to search based on the keyword and the entire inputted sentence. For example if the keyword is e-mail and the user enter's what is mars e-mail? and the text file contains "mars e-mail is mars3433#aol.com, john e-mail is anonymous" i want to output mars e-mail is ... instead of both sentences. I am completely stuck trying to figure out this issue, Can anyone help me?
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 removedata(String s) throws IOException {
File f = new File("data.txt");
File f1 = new File("data2.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while ((line = br.readLine()) != null) {
if (line.contains(s)) {
System.out.println("Enter new Text :");
String newText = input.readLine();
line = newText;
System.out.println("Thank you, Have a good Day!");
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
public static void parseFile(String s) throws IOException {
File file = new File("data.txt");
Scanner forget = new Scanner(System.in);
Scanner scanner = new Scanner(file);
int flag_found = 0;
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
flag_found = 1;
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(lineFromFile);
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
}
}
if (flag_found == 0) {// input is not found in the txt file so
// flag_found remains 0
writer();
}
}
public static void writer() {
Scanner Keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
File file = new File("data.txt");
try (BufferedWriter wr = new BufferedWriter(new FileWriter(
file.getAbsoluteFile(), true))) { // Creates a writer object
// called wr
// file.getabsolutefile
// takes the filename and
// keeps on storing the old
System.out.println("I Do not know, Perhaps you want to teach me?"
+ "..."); // data
while ((Keyboard.hasNext())) {
String lines = Keyboard.nextLine();
System.out.print(" is this correct ? ");
String go = input.nextLine();
if (go.equals("no")) {
System.out.println("enter line again");
lines = Keyboard.nextLine();
System.out.print(" is this correct ? ");
go = input.nextLine();
}
else if (go.equals("yes")) {
wr.write(lines);
// wr.write("\n");
wr.newLine();
wr.close();
}
System.out.println("Thankk you");
break;
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
}
private static List<DicEntry> populateSynonymMap() {
List<DicEntry> responses = new ArrayList<>();
responses.add(new DicEntry("student", "pupil", "scholar"));
responses.add(new DicEntry("office", "post", "room"));
responses.add(new DicEntry("topics", "semester talk"));
return responses;
}
public static void getinput() throws IOException {
List<DicEntry> synonymMap = populateSynonymMap(); // populate the map
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();
String[] inputs = input.split(" ");
int flag_found = 0;
for (DicEntry entry : synonymMap) { // iterate over each word of the
// sentence.
if (entry.pattern.matcher(input).matches()) {
// System.out.println(entry.key);
parseFile(entry.key);
flag_found = 1;// Input is found
}
}
if (flag_found == 0) {// input is not found in the txt file so
// flag_found remains 0
writer();
}
}
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
getinput();
}
}
So my methods work like this, the parse file method searching the text file for the keyword in the sentence. My writer( ) writes to the file if the input is not found and my remove data ( ) erases the line and updates it with the new string upon user request. and get input is just a method to get information from the scanner.
In my opinion, additional obstacle is fact, that some word can repeat in unrelated sentences. My solution seems to be quite long for me, but it works. However when I test it, I didn't use your dicEntry. It is impossible to hard-code all synonyms, so you should reconsider this approach.
I added one class, jast as data holder for int repetition variable (see below) and particular sentence:
public class Pair {
int repetitions;
String sentence;
public Pair(int rep, String string){
repetitions = rep;
sentence = string;
}
public int getRepetitions() {
return repetitions;
}
public String getSentence() {
return sentence;
}
}
Then I wrote a method, which loop through input sentence, and file content, looking for sentence from file, in which most inputs words repeted. I pretty sure, it is not most efficient way, but I don't know another :P.
public static String getMostAppropriate(String[] input) throws IOException{
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
ArrayList<Pair> pairs = new ArrayList<>();
int repetitions = 0;
while (scanner.hasNextLine()) {
String newLine = scanner.nextLine();
String[] line = newLine.split(","); // this regex depends on your file format style,
String oneSentence = "";
for(String sentence : line){ // for sentence in file lines
for(String string : sentence.split(" ")){ // for words in these sentences
for(String word : input){ // for words from input
if(word.equals(string)){
repetitions += 1;
oneSentence = sentence;
}
}
}
pairs.add(new Pair(repetitions,oneSentence));
repetitions = 0;
}
}
return mostCommon(pairs);
}
The argument is String[] inputs form your getInput method. In return statement I called another new method, which looks for sentences with most repetitions:
public static String mostCommon(ArrayList<Pair> pairs){
Pair max = new Pair(0,"");
String result = "";
for(Pair pair : pairs){
if(pair.getRepetitions() > max.getRepetitions()){
result = pair.getSentence();
max = pair;
}else if(pair.getRepetitions()==max.getRepetitions()){
result += "; " + pair.getSentence();
}
}
return result;
}
If some sentences have same number of repetitions, it returns both(or more) connected into one sentence (sentence; sentence; etc.).
Implementation into your code I left for you, if you are interested.
As I said, I didn't use your dicEntry, still you can add it as additional loop, but chacking whole dictionary will not be too effective with my method.
Also, if I were you, I would divide some of your methods into smaller one, I mean like: read file in one, ask for additional input in another. Because it is easier to implement changes this way. You don't need to keep eye on whole method, just arguments they pass to each other.
I hope you will find something useful in my post.
I'm creating a program that simple creates objects of soccer teams and then stores the names and records of the teams in a text file.
I'm trying to create sections in my file however so I can print out teams that are on the same continent.
Pretend the next line of text is the beginning of my text file
North America
End North America
Hey guys
If I want my objects of teams who are in North America only to be written in between those two lines of text how would I do that?
The results I have gotten so far aren't working correctly, the team name and records are being printed right after "End North America".
Below is my code thus far.
import java.util.*;
import java.io.*;
public class Teams {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner nameInput = new Scanner(System.in);
System.out.println("Team Creator!");
System.out.println("-----------------------------");
System.out.println("Select an option");
System.out.println("");
System.out.println("1. Create-A-Team");
System.out.println("");
int optionSelection = input.nextInt();
if(optionSelection==1) {
System.out.println("Please enter the name of the team you'd like to create");
String teamName = nameInput.nextLine();
Team team = new Team();
team.createTeam(teamName);
}
}
}
class Team {
String name;
int wins,loses;
boolean northAmericanTeam = true;
public void createTeam(String name) {
Team newTeam = new Team();
newTeam.name = name;
this.wins = 0;
this.loses = 0;
System.out.println("You created " + name + "!");
System.out.println("Wins: " + wins);
System.out.println("Loses: " + loses);
if(northAmericanTeam == true) {
BufferedReader reader = null;
try(PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter("teaminfo.txt", true)))) {
File file = new File("teaminfo.txt");
reader = new BufferedReader(new FileReader(file));
String line;
String nAmerica ="North America";
while ((line = reader.readLine()) != null) {
System.out.println(line);
if(line.equals(nAmerica)) {
write.println(name+"" + ": Wins[" +wins+"] Loses[" +loses+"]");
write.close();
}
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
reader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I don't really know if this is the best solution, but you can maybe do this with pattern.
private static final Pattern pAmerica = Pattern.compile("End\\sNorth\\sAmerica");
And then, in your printer, you can match it and write after :
while ((line = reader.readLine()) != null) {
System.out.println(line);
Matcher mAmerica = pAmerica.matcher(line);
if(mAmerica.find()) {//Maybe using mAmerica.matches() here can be better
write.println(name+"" + ": Wins[" +wins+"] Loses[" +loses+"]");
write.close();
}
}
Never forget to compile your pattern in a static way, to ensure minimum perf used, they are hard to compile ^^
You are assuming that the writer will be placed at the place where the reader has reached, which is not right.
The moment the reader reaches line 5 for example, the writer will still be attempting to write at the end of the file.
You can read the whole file (if it's not that big) into a StringBuilder and then manipulate it, and write i back to the File:
StringBuilder filecontent = new StringBuilder("Yor File Contents");
if (filecontent.indexOf("North America") != -1){
filecontent.insert(filecontent.indexOf("North America\n" + "North America\n".length(), "\n" + name+"" + ": Wins[" +wins+"] Loses[" +loses+"]")
}
// write filecontent.toString() to the File again
So this is what I have so far :
public String[] findStudentInfo(String studentNumber) {
Student student = new Student();
Scanner scanner = new Scanner("Student.txt");
// Find the line that contains student Id
// If not found keep on going through the file
// If it finds it stop
// Call parseStudentInfoFromLine get the number of courses
// Create an array (lines) of size of the number of courses plus one
// assign the line that the student Id was found to the first index value of the array
//assign each next line to the following index of the array up to the amount of classes - 1
// return string array
}
I know how to find if a file contains the string I am trying to find but I don't know how to retrieve the whole line that its in.
This is my first time posting so If I have done anything wrong please let me know.
You can do something like this:
File file = new File("Student.txt");
try {
Scanner scanner = new Scanner(file);
//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if(<some condition is met for the line>) {
System.out.println("ho hum, i found it on line " +lineNum);
}
}
} catch(FileNotFoundException e) {
//handle this
}
Using the Apache Commons IO API https://commons.apache.org/proper/commons-io/ I was able to establish this using FileUtils.readFileToString(file).contains(stringToFind)
The documentation for this function is at https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#readFileToString(java.io.File)
Here is a java 8 method to find a string in a text file:
for (String toFindUrl : urlsToTest) {
streamService(toFindUrl);
}
private void streamService(String item) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(lines -> lines.contains(item))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
When you are reading the file, have you considered reading it line by line? This would allow you to check if your line contains the file as your are reading, and you could then perform whatever logic you needed based on that?
Scanner scanner = new Scanner("Student.txt");
String currentLine;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Perform logic
}
}
You could use a variable to hold the line number, or you could also have a boolean indicating if you have passed the line that contains your string:
Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Do task
passedLine = true;
}
if(passedLine)
{
//Do other task after passing the line.
}
lineNumber++;
}
This will find "Mark Sagal" in Student.txt. Assuming Student.txt contains
Student.txt
Amir Amiri
Mark Sagal
Juan Delacruz
Main.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
final String file = "Student.txt";
String line = null;
ArrayList<String> fileContents = new ArrayList<>();
try {
FileReader fReader = new FileReader(file);
BufferedReader fileBuff = new BufferedReader(fReader);
while ((line = fileBuff.readLine()) != null) {
fileContents.add(line);
}
fileBuff.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(fileContents.contains("Mark Sagal"));
}
}
I am doing something similar but in C++. What you need to do is read the lines in one at a time and parse them (go over the words one by one). I have an outter loop that goes over all the lines and inside that is another loop that goes over all the words. Once the word you need is found, just exit the loop and return a counter or whatever you want.
This is my code. It basically parses out all the words and adds them to the "index". The line that word was in is then added to a vector and used to reference the line (contains the name of the file, the entire line and the line number) from the indexed words.
ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
//Add the path to the list of file paths
textFilePaths.push_back(path);
int lineNumber = 1;
while(!txtFile.eof())
{
txtFile.getline(line, 200);
Line * ln = new Line(line, path, lineNumber);
lineNumber++;
myList.push_back(ln);
vector<string> words = lineParser(ln);
for(unsigned int i = 0; i < words.size(); i++)
{
index->addWord(words[i], ln);
}
}
result = true;
}
Here is the code of TextScanner
public class TextScanner {
private static void readFile(String fileName) {
try {
File file = new File("/opt/pol/data22/ds_data118/0001/0025090290/2014/12/12/0029057983.ds");
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java TextScanner1"
+ "file location");
System.exit(0);
}
readFile(args[0]);
}
}
It will print text with delimeters