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.
Related
I'm new to java and I need help with this problem I encountered. This class reads data from text file and adds it to the array Movie. The problem is that when it reads the text file, it skips every other line.
public class ReadFile{
private File f;
Scanner sc;
int index;
public ReadFile(){
f = new File("db.txt");
try {
sc = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("An Error occured, File couldn't be opened.");
}
}
public int FileRead(Movie[] film, int index){
sc.useDelimiter(",");
this.index = index;
while(sc.hasNext()){
film[index] = new Movie();
film[index].setTitle(sc.next());
film[index].setYear(sc.next());
film[index].setRuntime(sc.next());
film[index].setActorOne(sc.next());
film[index].setActorTwo(sc.next());
film[index].setDirector(sc.next());
if(sc.hasNextLine()){
sc.nextLine();
}
index++;
}
System.out.println("count is "+ index);
sc.close();
return index;
}
}
nextLine() doesn't actually do what you think it does.
Furthermore, neither does .useDelimiter(",") - presumably, your file is something like:
Jurassic Park,1993,128,Jeff Goldblum,Jeff Goldblum's looks,Steven Spielberg
The Fly,1986,96,Jeff Goldblum,A fly,David Cronenberg
The problem is, computer is as computer does. You said the separator between tokens is a comma. And nothing else. So, this whole thing is a single token:
Steven Spielberg
The Fly
As in, "Steven Spielberg\nThe Fly" is what your sc.next() call returns for the first movie in the setDirector line. Seems stupid? Well, you told the computer: Tokens are things separated by commas. That whole thing is surrounded by commas so, you asked for it, you got it: That's the next() token in the file. Then you do an otherwise useless nextLine call which eats the rest of that The Fly line, thus, resulting in not only skipping every other movie, but having a mangled combo of the directory and the name of the movie on the next (otherwise skipped) line, mangled together. You know, like The Fly? Get it? [Note to self: It's a movie from 1987, no, they wont get it!]
The fix is possibly to tell scanner that either a comma or a newline counts as a separator; .useDelimiter(",|\r?\n") would do that. And forget about the hasNextLine + nextLine part, that does nothing, you should just get rid of that. Your code will fail if there's a 'broken' line in there (one that doesn't include precisely 5 commas), and that nextLine stuff isn't going to fix that problem, thus, get rid of it.
Alternatively, forget scanner - read line by lines using e.g. Files.readAllLines, then process line-by-line, using .split(",") to break it into parts.
I'm coding a program that takes in lines from an input text file.
It is supposed to be a set of strings on a single line separated by the newline character. So, my input file looks like this:
0110\n011\n0111\n100001
However, when I go to print out each line, it comes out as one entire string, including the new line characters - '0110\n011\n0111\n100001'
This is my code - it works fine for Scanner when it's a static string, but not when it's from a file.
File input = new File(input.txt);
Scanner scanner = new Scanner(input);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
When I change the scanner to read a String s, like Scanner scanner = new Scanner(s) for a String s = "0110\n011\n0111\n100001", it works correctly and prints out 4 lines, which means it recognizes the \n character, as such:
String s = "0110\n011\n0111\n100001";
Scanner scanner = new Scanner(s);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
The only thing that's holding me back is that we have to separate the input file strings by \n. That's a requirement for our project.
Any idea why this happens? Is my text file wrong, is there a way to split it up by \n? Does Scanner read lines in files differently than just static strings? Should I just switch to BufferedReader? I can't wrap my head around this. I read through some forums and manuals and I couldn't find anything on it. If I can do anything, or provide anything else, please let me know.
\n is a new line symbol, which when in a string is interpreted as such, but in your file you should just hit the enter key, which will make a new line for you and the scanner will read everything right.
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
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.
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|:]+");