Importing Text Files to be read using Scanner - java

private void readWords() throws IOException {
initialCt = readFrom("C:\\Curses1.txt", initialWords);
midCt = readFrom("C:\\Curses2.txt", middleWords);
endCt = readFrom("C:\\Curses3.txt", endingWords);
} // readWords()
// Pre: fileName is the name of an input file. Tokens (items) in the
// file are strings separated by whitespace.
// Pre: wordList has been allocated and is large enough to hold all
// the tokens in the input file.
// Post: wordList contains all the tokens in the input file, one token
// per string.
private int readFrom(String fileName, String[] wordList) throws IOException {
int count= 0;
FileInputStream fstream = new FileInputStream(fileName);
Scanner scan2 = new Scanner (fstream);
while (scan2.hasNext()){
initialWords[count] =scan2.nextLine();
middleWords[count] = scan2.nextLine();
endingWords [count] = scan2.nextLine();
String words = scan2.next();
++count;
}
return count;
} // readFrom()
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Curses.readFrom(Curses.java:95)
at Curses.readWords(Curses.java:63)
at Curses.run(Curses.java:51)
at Curses.main(Curses.java:131)
I am trying to read in three different text files and store their values in three different arrays but java cannot find the file. This is only part of the class but this is where the error is occurring. Any help would be greatly appreciated!

i believe it is happening because of the String words = scan2.next();
if the file doesn't have the 4th line then this exception would be thrown. that is the only possible way i can think of. check the files if there is a 4th line.

Related

Trouble with FileStats and searching lines for certain words

I am having a bit of trouble with the FileStats class to show how many lines contain the text being asked for by the user. I keep getting the incorrect answer to how many lines contain the text. I believe my code is ignoring punctuation (e.g. it won't detect the.) and upper-case variations like (The).
For Example if a file contains 5268 lines, and 1137 of those lines contain the word "the", my code returns output saying it only contains 1032 of those lines contain the word "the".
Any help would be appreciated Thank you. Code is Below
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in); //creating object for scanner class
System.out.println("Enter a filename");
String file_name = input.nextLine(); //asking user to enter a file name
int word_line_count =0, line_count=0; //count variables for counting the line count and word occurance count
String search_word = input.nextLine(); //asking user to enter a search_Word
File f = new File(file_name); //Creating File Descriptor for reading input file
String[] words_sentence = null; //creating string which stores the all words in a line
FileReader file_object = new FileReader(file_name); // Creating File Reader object
BufferedReader buffer = new BufferedReader(file_object); //Creating BufferedReader object
String sentence;
while((sentence=buffer.readLine())!=null) //Reading Content from the file till the end of file
{
if (sentence.contains(search_word))
{
word_line_count++;
}
line_count++; //increment line count for every while loop iteration
}
System.out.println(file_name + " has " + line_count + " lines"); //printing the line count
System.out.println("Enter some text");
System.out.println( word_line_count+ " line(s) contain "+"\""+search_word+"\""); //printing the number of lines contains the given word
file_object.close(); //closing file object
}
}

How Can I Split a Long String Into Lines At "),"?

Having a bit of a headache trying to parse a text file correctly, it's a pull from mysql database but the data needs to be changed a fair bit before it can be inserted again.
My program is taking a .txt file and parsing it to produce a .txt file, which is simple enough.
The issue is that it is not splitting the file correctly. The file looks as follows (the middle field of each looks strange because I've changed it to random letters to hide the real data):
(92,'xxxname',4013),(93,'sss-xxx',4047),(94,'xxx-sss',3841),(95,'ssss',2593),(96,'ssss-sss',2587),(97,'Bes-sss',2589),
I want to split it so that it produces a file like:
(92, 'xxxname',4013),
(93, 'sss-xxx', 4047),
(94, 'xxx-sss', 3841),
And so on...
Current code for parsing is as follows:
public void parseSQL(File file) throws IOException {
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String line = scanner.next();
String[] lines = line.split(Pattern.quote("),"));
for (String aLine : lines) {
logLine(aLine);
}
}
}
public static void logLine(String message) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true),
true);
out.println(message);
out.close();
}
Currently the output I'm getting is roughly on track but more split up than it should be, and of course the split method is removing the ")," which is unnecessary.
Sample of the current output:
*(1,'Vdddd
Cfffff',1989
(2,'Wdd',3710
(3,'Wfffff
Hffffff
Limited-TLC',3901
(4,'ffffffun88',2714
(5,'ffffff8',1135
(6,'gfgg8*
Been playing around for a while and have done a good bit of searching here and elsewhere but out of ideas, any help would be greatly appreciated.
You can use String.replace. There's also no need to create multiple PrintWriters and close the stream every time.
public void parseSQL(File file) throws IOException {
Scanner scanner = new Scanner(file);
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
while (scanner.hasNext()) {
String line = scanner.next();
out.println(line.replace("),", ")," + System.lineSeparator()));
}
out.close();
}
The answer is simple, this line:
String line = scanner.next();
Should be:
String line = scanner.nextLine();
Thanks for your attempts folks sorry for being dumb

Constructing an object using a given file

I'm trying to use a constructor to create an object from a file, the file should contain (on the first line) an Int in String format which is meant to be the number of rows for the MD Array and then has a space followed by another Int in String format. I'm trying to "grab" these two Strings, parse them into an int and then instantiate the MD Array by using these two ints I've "grabbed." I'm just not quite sure where I'm going wrong, as I've just begun using File I/O in my coding. Here's my code.
public SeatingChart(File file) throws FileNotFoundException, DataFormatException, IOException
{
Scanner scan = new Scanner(file);
int rows = 0;
int columns = 0;
String rowStr = "";
String colStr = "";
if (scan.hasNext())
{
rowStr = scan.next();
colStr = scan.next();
}
rows = Integer.parseInt(rowStr);
columns = Integer.parseInt(colStr);
seats = new Student[rows][columns];
scan.close();
}
Any help would be much appreciated :)
From your question, You want to grab two numbers, in string format, separated by a space.
I would grab the entire line then trim the string which ensures there is no space before or after the numbers I need. Then split them based on space.
Look at this simplified step by step example. This example will create a file called numbers.txt then put in it string "5 2". Then the file will be read and taken apart to get the numbers.
import java.util.*;
import java.io.*;
import java.nio.*;
PrintWriter fileWriter = new PrintWriter("numbers.txt", "UTF-8");
fileWriter.println("5 2");
fileWriter.close();
File file = new File("numbers.txt");
Scanner input = new Scanner(file);
String numbersString;
if (input.hasNextLine()) numbersString = input.nextLine();
// Trim the string to ensure you have what you need.
numbersString = numbersString.trim();
// Split both numbers according to the space within them.
String[] numsArray = numbersString.split("\\s+");
// Get your numbers.
int row = Integer.valueOf(numsArray[0]);
int col = Integer.valueOf(numsArray[1]);

ArrayIndexOutOfBoundsException - Java - no loop print

I have a method that's reading a local CSV file and storing it in an array. I keep getting a ArrayIndexOutOfBoundsException when I try to print one of the index of the array.
The method:
public void getCsv() throws FileNotFoundException{
String fileName = "ADCSV.csv";
File file = new File(fileName);
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext()){
String data = inputStream.next();
//array of strings
String[] values = data.split(",");
System.out.println(values[4]);
}
inputStream.close();
}
All of the information in the csv is stored as general text. When I try to print this is the output:
"adminCount"
"1"
"0"
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at csvTest.test.getCsv(test.java:36)
at csvTest.test.main(test.java:19)
It starts to read the values from that particular column fine. It then errors out.
I feel like I've been looking at the problem for awhile now and looking right past the issue.
Thanks
Change your method to:
public void getCsv() throws FileNotFoundException {
String fileName = "ADCSV.csv";
File file = new File(fileName);
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()) {
String data = inputStream.next();
// array of strings
String[] values = data.split(",");
if (values.length < 5) {
System.err.println("not enough values: ");
for (int i = 0; i < values.length; i++) {
System.err.println("value " + i + ": " + values[i]);
}
continue;
}
System.out.println(values[4]);
}
inputStream.close();
}
That should show the problem. I mean it will print out the values of the line where the error will occur. Since we don't know what exactly produced the error this will be a start. Maybe somewhere is a comma where it shouldn't be or it is missing.
If the content of the local CSV file can contain errors then it would be appropriate to check the length of the splitted line and set up an error handling.

Receiving StringIndexOutOfBoundsException but unable to locate the source

My task:
Use scanner method to extract a string, a float, and an int from a line of data.
The data format is:
Random String, 240.5 51603
Another String, 41.6 59087
etc.
My source snippet:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class readTest {
public static void main(String args[]) throws FileNotFoundException
{
System.out.println ("Enter file name");
Scanner scanInput = new Scanner(System.in); //Scanner for reading keyboard input for file name
String fileName = scanInput.nextLine(); //Defines file name as a string from keyboard
File inputTxt = new File(fileName); //Declares the file based on the entered string
Scanner in = new Scanner(inputTxt);
do {
int a; //variable to count how many characters in name
String baseStringA = in.nextLine(); //read whole line as string
a = baseStringA.indexOf(","); //defines a as the posistion of the comma
String reduceStringA = baseStringA.substring(0, a); //reduces string to everything before comma
Scanner scanA = new Scanner(baseStringA).useDelimiter("[^.0-9]+"); //removes letters and comma from string
Float numberA = scanA.nextFloat();
int integerA = scanA.nextInt();
System.out.print (reduceStringA + numberA + integerA);
} while (in.hasNextLine());
}
}
So I finally managed to spit out this code after researching a few different topics (I am pretty new to any type of coding) and I was so excited that I managed to get the output I wanted. But after attempting to implement a loop to make the process repeat for all of the available lines, I frequently hit a wall with the error java.lang.StringIndexOutOfBoundsException after the program prints the output of the first line.
The full error:
String index out of range: -1
at java.lang.String.substring(Unknown Source)
at readTest.main(readTest.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
I tried to research a little, and I'm convinced it comes from my line
String reduceStringA = baseStringA.substring(0, a);
This seemed more obvious as I tried to read the actual info given by the error, but when I try to trace where the program is having problems I come up empty.
Is anybody able to spot my rookie mistake? Or am I simply going about this process entirely wrong?
The input txt:
Stringy String, 77.2 36229
More Much String, 89.4 24812
Jolly Good String, 182.3 104570
is an example of me getting the error
While the input
Random String, 240.5 51603
Another String, 41.6 59087
String String, 182.6 104570
works as intended
Which is really strange to me.
int a; //variable to count how many characters in farm name
String baseStringA = in.nextLine(); //read whole line as string
a = baseStringA.indexOf(","); //defines a as the posistion of the comma
String reduceStringA = baseStringA.substring(0, a);
If there is no comma in the baseStringA baseStringA.indexOf() will return -1. Thus then you will try to get sub string (0,-1) and thus the error.
Finally the error comes from here baseStringA.substring(0, a); because one of begin index 0 is larger than the end index a (which is -1) - more here

Categories

Resources