Java Scanner class reads one line and then stops - java

I have this problem with a method using the Scanner class. I am reading my text file with Scanner and then parse the int into an array.
public static void readItems()
{
try
{
File file = new File(System.getProperty("user.home") + "./SsGame/item.dat");
Scanner scanner = new Scanner(file);
int line = 0;
while (scanner.hasNextLine())
{
String text = scanner.nextLine();
text = text.replaceAll("\\W", "");
System.out.println(text.trim());
PlayerInstance.playerItems[line] = Integer.parseInt(text);
line++;
}
scanner.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (NumberFormatException e2)
{
e2.printStackTrace();
}
}
Heres the item.txt file:
1
1
2
3
4
I run the code and I get the following output:
1
I have tried using scanner.hasNextInt() and scaner.nextInt(); for this but then it won't print anything at all.
If I remove the parseInt part then the file will finish reading and all the numbers will be printed. Any ideas?
This the exception thrown:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at game.player.ReadPlayer.readItems(ReadPlayer.java:56)
at game.player.ReadPlayer.read(ReadPlayer.java:11)
at game.Frame.<init>(Frame.java:32)
at game.Frame.main(Frame.java:54)

I'm guessing Integer.ParseInt() is throwing an NumberFormatException because your line still contains the \n.
If you call Integer.ParseInt(text.trim()) instead, it may fix it.
If you did your Exception handling properly, we would have a better idea.

This is because, you have a NumberFormatException, while parsing integer.
Add in catch section something like this
System.out.println(e.getCause());
And see, that you have an exception, that's why this code prints only first digit.

You need to be careful when you use the Scanner.
If you are reading more data, with Scaner like input.nextInt(); then it will read only one int. The carriage return isn't consumed by nextInt. One solution is that add input.nextLine(); so that it moves to the next line.
Other Solution is, which I prefer is to use BufferedReader;
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String tempStr = bufferRead.readLine();
// Do some operation on tempStr
Hope this helps.

Related

Why does my code keep waiting for user input

Ok so I have a text file like so
dears fears
heart heart
sail ruin
etc
I'm trying to run the scanner through each line so I can
create a WordLadder object which requires the 2 strings in each line.
try {
Scanner sc = new Scanner(new File("input.txt"));
while (sc.hasNext()) {
String s = sc.next();
String s2 = sc.next();
WordLadder wl = new WordLadder(s, s2);
System.out.print(wl.toString());
}
}
catch (FileNotFoundException ex)
System.out.print("File not found");
}
For some reason, when I run the debugger, as far as I can tell, it runs through once then it waits for user input. It creates a word ladder with dears and fears and prints the solution for that word ladder. Then second loop it waits for user input instead of doing it again.
I'm thoroughly confused because when I do something like this
try {
Scanner sc = new Scanner(new File("input.txt"));
while (sc.hasNext()) {
String s = sc.next();
System.out.println(s);
}
}
catch (FileNotFoundException ex)
{
System.out.print("File not found");
}
It prints all the words. But any variation I tried of trying to put those words in a wordladder object it waits for user input. Any ideas?
I just tried your code and I have no issues unless I have a file with an odd number of Strings. In that case, I get the following error:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at Main.main(Main.java:19)
This is expected since you are reading 2 Strings for each sc.hasNext().
So it seems to me that the issue might be the content of your input.txt file.

Why is my scanner reading numbers in a text file as a string?

I have a text file that has grocery items followed by the isle they are on in a text file. For some reason, my scanner is only picking up on the data as a string and not a string and an int. Below is my code that is super simplified to try and troubleshoot:
public static void readItems(String filename){
String groceryItem;
int groceryIsle;
String specialArea;
try{
FileInputStream fis = new FileInputStream(filename);
Scanner s = new Scanner(fis);
while (s.hasNext()){
**System.out.println(s.next());**
}
} catch(IOException ex){
Logger.getLogger(GroceryPlanner.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Can not open the file!");
}
}
This just prints out all of the names of the items and the isle number. When I change the highlighted line of the code to s.nextInt(), I get
Exception in thread "main" java.util.InputMismatchException
Here is a link to snippet of the input file
I would appreciate any help.
You're probably assuming nextInt grabs the next int, but that's not the case: it scans the next token of the input as int. If it finds a String instead, an InputMismatchException is thrown.
Since your input starts with a String, this exact exception is thrown.

Exception in thread "main" NumberFormatException

Exception in thread "main" java.lang.NumberFormatException: For input string: "1001"
I dont understand why this code throws exception.
1001 elma 87 --> This is the text file and I'm sure this is a number.
public class Food {
public String[][] foodArray = new String[1000][100];
public int sayac = 0;
public void readText() {
try (Scanner sc = new Scanner(new BufferedReader(new FileReader("food.txt")))) {
while (sc.hasNextLine()) {
String bilgiler = sc.nextLine().trim();
foodArray[sayac] = bilgiler.split("\t");
System.out.println(Integer.parseInt(foodArray[sayac][0]));
sayac++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "1001"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Food.readText(Food.java:13)
at Main.main(Main.java:11)
The only problem that I can see that in the file the character that is separating the words is not a tab (\t) character, but maybe just spaces. That's why it is not able to split the line correctly. Can you show us what the exact stack trace is?
Delimiting character is not tab(\t) which is why the line is not getting split in different parts and whole line is stored at 0th index of the array. And when you use parseInt it tries to parse the whole line which is 1001 elma 87
I would suggest using bilgiler.split(" ") which will take care of single or multiple spaces used as delimiter.
your file line separator might not be tabs, i advise you to print the split array and use bilgiler.split("\\s+"); to split all the spaces between words

Java Scanner Split Strings by Sentences

I am trying to split a paragraph of text into separate sentences based on punctuation marks i.e. [.?!] However, the scanner splits the lines at the end of each new line as well, even though I've specified a particular pattern. How do I resolve this? Thanks!
this is a text file. yes the
deliminator works
no it does not. why not?
Scanner scanner = new Scanner(fileInputStream);
scanner.useDelimiter("[.?!]");
while (scanner.hasNext()) {
line = scanner.next();
System.out.println(line);
}
I don't believe the scanner splits it on line breaks, it is just your "line" variables have line breaks in them and that is why you get that output. For example, you can replace those line breaks with spaces:
(I am reading the same input text you supplied from a file, so it has some extra file reading code, but you'll get the picture.)
try {
File file = new File("assets/test.txt");
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[.?!]");
while (scanner.hasNext()) {
String sentence = scanner.next();
sentence = sentence.replaceAll("\\r?\\n", " ");
// uncomment for nicer output
//line = line.trim();
System.out.println(sentence);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
This is the result:
this is a text file
yes the deliminator works no it does not
why not
And if I uncomment the trim line, it's a bit nicer:
this is a text file
yes the deliminator works no it does not
why not

reading a long type from a text file in Java

i'm trying to read long types from a text file with using readLine() method of BufferedReader class and then i parse the first token (which is long type number) with using StringTokenizer but i'm facing with an exception error which is java.lang.NumberFormatException
this is an example of my text file;
2764841629 Quaroten Ilen
1398844030 Orden Nenama
1185252727 Inja Nenaptin
2370429126 Quaren Inaja
1502141743 Otin Una
1993687334 Quarwennaja Nenoten
1015934104 Polen Meritna
2363674760 Otja Ie
1904629749 Neninin Ordja
3047965620 Algnaja Nenja
here is the code i read from a text file and assing the long value to my long variable
private void registerData() throws FileNotFoundException{
try {
String regPatName;
String regPatSurname;
long regPatID;
FileInputStream fis = new FileInputStream("src\\assignment_3\\injuredPersonList.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while( ( line = reader.readLine() ) != null) {
StringTokenizer st = new StringTokenizer(line, " ");
while(st.hasMoreTokens()){
regPatID = Long.parseLong(st.nextToken());
regPatName = st.nextToken();
regPatSurname = st.nextToken();
Patient regPatient = new Patient(regPatName, regPatSurname, regPatID);
hashMethod(regPatient);
}
}
} catch (IOException ex) {
Logger.getLogger(personTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void hashMethod(Patient regPatient){
Long idPat = new Long(regPatient.getPatientID());
int keyID;
keyID = (int) Math.sqrt(Integer.parseInt(idPat.toString().substring(0, 5) + idPat.toString().substring(5, 10))) % (50000);
System.out.println(keyID);
}
and finally this the error which i'm facing;
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "2481765933 Otna"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:419)
at java.lang.Long.parseLong(Long.java:468)
at assignment_3.personTest.registerData(personTest.java:58)
at assignment_3.personTest.<init>(personTest.java:33)
at assignment_3.personTest$1.run(personTest.java:161)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
i will be very appreciated if you can help me and also thanks anyway.
You probably have a tab character instead of spaces to separate your fields. Add the tab to your set of delimiters (" \t").
Also, always close your streams and readers in a finally block (only the outermost one must be closed: closing the BufferedReader will close the InputStreamReader, which will close the FileInputStream).
Clearly you're trying to parse a non-numeric string, the stack trace shows it: 2481765933 Otna. You should split the input and parse the numeric part, something like this:
String[] data = line.split("\\s+");
regPatID = Long.parseLong(data[0]);
regPatName = data[1];
regPatSurname = data.length == 3 ? data[2] : "";
The above is much simpler than using StringTokenizer. In fact, the usage of StringTokenizer is discouraged, practically deprecated - nowadays, the preferred way to parse a string is either using the split() method for simple cases or the Scanner class for complex cases.
You are using the wrong delimiter (" ") since your text file may contain more than one space character between tokens. StringTokenizer is a legacy class, don't use it unless you have a good reason to. String.split() should suffice:
String[] result = line.split("\\s+");
regPatID = Long.parseLong(result[0]);
regPatName = result[1];
regPatSurname = result[2];
But I think that Scanner is the best fit for your problem:
// Java 7 try-with-resources synthax.
// If you are using Java <=6, declare a finally block after the catch
// to close resources.
try (InputStream myFile = ClassLoader.getSystemResourceAsStream("MyTextFile.txt");
Scanner sc = new Scanner(myFile)) {
while (sc.hasNext()) {
regPatID = sc.nextLong();
regPatName = sc.next();
regPatSurname = sc.next();
System.out.printf("%d - %s %s\n", regPatID, regPatName, regPatSurname);
}
} catch (Exception e) {
// Do something about exceptions
}
Both versions correctly parses your example input.
Here is a third fully working Java 6 Version.

Categories

Resources