Java: Error with reading in file with delimiter - java

I have a file with multiple fields that i need to store individually into an array.
Steve;stiffy;123;88
Sam;sammy;456;55
But when i try storing them i keep getting error saying java.util.NoSuchElementException
Here is my code for storing the data
void loadCustomer(){
try {
Scanner sc = new Scanner(new File("CustomerInfo.txt"));
sc.useDelimiter(";");
while (sc.hasNext())
{
cusName.add(sc.next());
cusUser.add(sc.next());
cusPass.add(sc.next());
cusCCNum.add(sc.next());
}
}
I could get it to work by changing
cusCCNum.add(sc.next());
to
cusCCNum.add(sc.nextLine());
but it will ignore the delimiter and when i print out cusCCNum.get(1), it will display
;88
instead of
88
Where did i go wrong?

There is no delimiter between 88 and Sam..
scanner.useDelimiter(";|\n");

Use String tokenizer instead of delimiter.
Get input as a string and parse it by ; character as token.
Learn, how to use stringtokenizer here

You are causing the exception while you are calling the 4 next elements for each one check if there is 1 next element, this would do the following:
while (RecentElement is not the last one)
{
Read (RecentElement + 1)
Read (RecentElement + 2)
Read (RecentElement + 3)
Read (RecentElement + 4)
}
And somewhen you get the exception of the next() method because you access an element that is just not there:
Throws: NoSuchElementException - if no more tokens are available
You should use the new line as a delimiter and for each new line parse the data from the record, for example using the split function:
sc.useDelimiter("\n");
while (sc.hasNext())
{
for(String g: sc.next().split(";"))
System.out.println(g);
}

Looks like you need to read each line, token it using delimeter and set values to array.
I could do it via StringTokenizer.
while (sc.hasNextLine()) {
StringTokenizer st = new StringTokenizer(sc.nextLine(),";");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
}
I am surprised and need to read more on Scanner api to see why its not working with scanner.

Related

Why am I getting an InputMismatchException with?

I created a Scanner in java to read through a file of data regarding a city. The file is formatted as such:
Abbotsford,2310,2
Adams,1967,1
Algoma,3167,2
When reading through the file, I get an InputMismatchException when scanning the last item on each line (This item needs to be an int).
public void fileScanner(File toScan) throws FileNotFoundException {
Scanner sc = new Scanner(toScan);
sc.useDelimiter(",");
System.out.println(sc.next());
System.out.println(sc.nextInt());
System.out.println(sc.nextInt());
Any ideas as to why? I'd imagine it has something to do with my use of the "," delimiter.
You are using only one delimiter i.e. , but your file contains \r or \n so try to use multiple delimiters. Also, use a loop to read the entire file:-
Scanner sc = new Scanner(toScan);
sc.useDelimiter(",|\\r\\n");
while (sc.hasNext()) {
System.out.println(sc.next());
System.out.println(sc.nextInt());
System.out.println(sc.nextInt());
}
OUTPUT:-
Abbotsford
2310
2
Adams
1967
1
Algoma
3167
2
The delimiter you're using is comma(,)
The system looks for the next comma, which comes only after Adams. So the input for the system looks like 2 Adams which is obviously not an Int , rather a String and hence the inputMisMatch.
If you make your data something like below, your code would work great.
Abbotsford,2310,2,
Adams,1967,1,
Algoma,3167,2,
Also I see there's no loop to read all the data. Your code will read just the first line.

How to make an array of Strings to store words of a "dictionary" from a .txt file?

I need to make a dictionary that takes words from a .txt file. These words (separated line by line) need to be stored in a String array. I have already gotten to the point of separating the words and adding them to a new .txt file, but I have no idea how to add them each to a String array. There are
You need to count the lines in the file. Create an array of that size.
Then for each line in the file, read it and insert it into the array at the index[lineReadFrom].
Since you are not allowed to use ArrayList or LinkedList objects, I would suggest to save every found word "on the fly" while you are reading the input file. These is a series of steps you could follow to get this done:
1. Read the file, line by line: Use the common new BufferedReader(new FileInputStream("/path/to/file")) approach and read line by line (as I assume you are already doing, looking at your code).
2. Check every line for words: Break every possilbe word by spaces with a String.split() and remove punctuation characters.
3. Save every word: Loop through the String array returned by the String.split() and for every element that you considered a word, update your statistics and write it to your dictionary file with the common new BufferedWriter(new FileWriter("")).write(...);
4. Close your resources: Close the reader an writer after you finished looping through them, preferably in a finally block.
Here is a complete code sample:
public static void main(String[] args) throws IOException {
File dictionaryFile = new File("dict.txt");
// Count the number of lines in the file
LineNumberReader lnr = new LineNumberReader(new FileReader(dictionaryFile));
lnr.skip(Long.MAX_VALUE);
// Instantiate a String[] with the size = number of lines
String[] dict = new String[lnr.getLineNumber() + 1];
lnr.close();
Scanner scanner = new Scanner(dictionaryFile);
int wordNumber = 0;
while (scanner.hasNextLine()) {
String word = scanner.nextLine();
if (word.length() >= 2 && !(Character.isUpperCase(word.charAt(0)))) {
dict[wordNumber] = word;
wordNumber++;
}
}
scanner.close();
}
It took about 350 ms to finish executing on a 118,620 line file, so it should work for your purposes. Note that I instantiated the array in the beginning instead of creating a new String[] on each line (and replacing the old one like you did in your code).
I used wordNumber to keep track of the current array index so that each word would be added to the array at the right location.
I also used .nextLine() instead of .next() since you said that the dictionary was separated by line instead of by spaces (which is what .next() uses).

How do I separate a string like this line by line?

I have a string that I want to read line by line:
"8688642986379252 Michael_Thompson 816 2500.0
8904000405634912 Barbara_Martin
8610835007621519 Charles_Jackson 1019 52800.0"
It goes on on and on in that format.
I tried separating it using for loops, charAt() and reducing the size of the string using substring() but I failed miserably.
I'm sure it's something simple but I just can't get it. Any ideas?
I would suggest using str.split("\n"). It will produce an array of strings, one index for each line. This is assuming you can read the whole thing into a string. If the input is large, this won't work.
Use Scanner to read line by line using nextLine. Then, split every String by blank space" ":
Scanner scanner = new Scanner(stringWithBreaklines);
while (scanner.hasNext()) {
String line = scanner.nextLine();
String[] content = line.split(" ");
//do what you want/need with content
}
If the String is inside a file, then read the file directly using Scanner:
Scanner scanner = new Scanner(new File("file.txt"));
//same code as above...
Use the java.util.Scanner class to read tokens one by one.
http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

How do I change the delimiter from a text file?

Let's say I got a textfile.txt that I want to read from. This is the text in the file:
23:years:old
15:years:young
Using the useDelimiter method, how can I tell my program that : and newlines are delimiters? Putting the text in one line and using useDelimter(":"); works. The problem is when I got several lines of text.
Scanner input = new Scanner(new File("textfile.txt));
input.useDelimiter(:);
while(data.hasNextLine()) {
int age = input.nextInt();
String something = input.next();
String somethingelse = input.next();
}
Using this code I will get an inputMisMatch error.
Try
scanner.useDelimiter("[:]+");
The complete code is
Scanner scanner = new Scanner(new File("C:/temp/text.txt"));
scanner.useDelimiter("[:]+");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
The output is
23
years
old
15
years
young
Use this code
Scanner input;
String tokenizer[];
try {
input = new Scanner(new File("D:\\textfile.txt"));
input.useDelimiter("\\n");
while(input.hasNextLine()) {
tokenizer = input.next().split(":");
System.out.println(tokenizer[0]+" |"+tokenizer[1]+" | "+tokenizer[2]);
}
}catch(Exception e){}
It will give you output like
23 |years | old
15 |years | young
You have two ways to do this:
Concatenate the string to make it one line.
delimit "newline" first, then delimit ":" each return string token.
If all you want is to get everything split up all at once then I guess you can use
useDelimiter(":\\n")
That should split on both : and newspace but it is not the most efficient way of processing data, especially if each line of text is set out in the same format and represents a complete entry. If that is the case then my suggestion would be to only split on a new line to begin with, like this;
s.useDelimiter("\\n");
while(s.hasNext()){
String[] result = s.next.split(":");
//do whatever you need to with the data and store it somewhere
}
This will allow you to process the data line by line and will also split it at the required places. However if you do plan on going through line by line I recommend you look at BufferedReader as it has a readLine() function that makes things a lot easier.
As long as all the lines have all three fields you can just use input.useDelimiter(":\n");
you probably wants to create a delimiter pattern which includes both ':' and newline
I didn't test it, but [\s|:]+ is a regular expression that matches one or more whitespace characters, and also ':'.
Try put:
input.useDelimiter("[\\s|:]+");

How to test for blank line with Java Scanner?

I am expecting input with the scanner until there is nothing (i.e. when user enters a blank line). How do I achieve this?
I tried:
while (scanner.hasNext()) {
// process input
}
But that will get me stuck in the loop
Here's a way:
Scanner keyboard = new Scanner(System.in);
String line = null;
while(!(line = keyboard.nextLine()).isEmpty()) {
String[] values = line.split("\\s+");
System.out.print("entered: " + Arrays.toString(values) + "\n");
}
System.out.print("Bye!");
From http://www.java-made-easy.com/java-scanner-help.html:
Q: What happens if I scan a blank line with Java's Scanner?
A: It depends. If you're using nextLine(), a blank line will be read
in as an empty String. This means that if you were to store the blank
line in a String variable, the variable would hold "". It will NOT
store " " or however many spaces were placed. If you're using next(),
then it will not read blank lines at all. They are completely skipped.
My guess is that nextLine() will still trigger on a blank line, since technically the Scanner will have the empty String "". So, you could check if s.nextLine().equals("")
The problem with the suggestions to use scanner.nextLine() is that it actually returns the next line as a String. That means that any text that is there gets consumed. If you are interested in scanning the contents of that line… well, too bad! You would have to parse the contents of the returned String yourself.
A better way would be to use
while (scanner.findInLine("(?=\\S)") != null) {
// Process the line here…
…
// After processing this line, advance to the next line (unless at EOF)
if (scanner.hasNextLine()) {
scanner.nextLine();
} else {
break;
}
}
Since (?=\S) is a zero-width lookahead assertion, it will never consume any input. If it finds any non-whitespace text in the current line, it will execute the loop body.
You could omit the else break; if you are certain that the loop body will have consumed all non-whitespace text in that line already.
Scanner key = new Scanner(new File("data.txt"));
String data = "";
while(key.hasNextLine()){
String nextLine = key.nextLine();
data += nextLine.equals("") ? "\n" :nextLine;
}
System.out.println(data);
AlexFZ is right, scanner.hasNext() will always be true and loop doesn't end, because there is always string input even though it is empty "".
I had a same problem and i solved it like this:
do{
// process input
}while(line.length()!=0);
I think do-while will fit here better becasue you have to evaluate input after user has entered it.

Categories