Win a copy of Transfer Learning for Natural Language Processing (MEAP) this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Paul Clapham
  • Devaka Cooray
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Knute Snortum
  • Liutauras Vilda
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Piet Souris
Bartenders:
  • salvin francis
  • Carey Brown
  • Frits Walraven

Parse String to Integer

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys! I have a problem with my code, I have to read coordinates from a file, my file is like this
30 11
39 90
56 89
........
My code is:
                   String lines;

                   int line=1;
                   while ((lines = in.readLine()) != null)   //read from file
                   {
                       if (line ==3){
                           int num=Integer.parseInt(lines);  // string to int

                           line++;
                           continue;
                       }

                       String[] lines2=lines.split(" ");        
                       int x=Integer.parseInt(lines2[0]);
                       int y=Integer.parseInt(lines2[1]);
but when I run my programm, i have error in   "int num=Integer.parseInt(lines)" and the message is Exception in thread "main" java.lang.NumberFormatException: For input string: "56 89"
What is my mistake? I can not manage to find what it is going wrong.I searched also in internet but I do not understand.Please help me if you can!Thank you!!
 
Saloon Keeper
Posts: 11881
253
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, "56 89" does not represent an integer, does it?
 
Mark Spen
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:Well, "56 89" does not represent an integer, does it?


Yes you are right, few minutes later i understand what i did!How can manage to read these number with correct way?
 
Stephan van Hulst
Saloon Keeper
Posts: 11881
253
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could wrap the input in a Scanner and use the nextInt() for each integer, and after you've scanned a pair of integers, you call nextLine(), to move to the next line.
 
Marshal
Posts: 68899
275
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are sure you have two numbers per line and nothing else in the file, you can dispense with the nextLine() call. I would prefer to test while (scanner.hasNext()) ... because you can have problems if your file ends with an empty line, as many files do.
Note how Stephan's suggestion gives you a neat, elegant format for the loop
 
Sheriff
Posts: 15519
263
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yup, Campbell is right, you can dispense with the nextLine() call after each pair. That's an annoying nuance with Scanner. This program illustrates the problem:

The first two methods behave as might be expected. The third one, numbersThenText(), exhibits the behavior that violates the Principle of Least Astonishment because everyone will reasonably expect "Foo" to be the last output based on what you see with the first two methods. The last output will be 5, not "Foo".

Here's what happens: The Scanner.nextInt() method will skip any delimiter and line separators it encounters before the next int value it reads. It will then read the number and stops at the next delimiter or line separator but will not consume it. This is true for any numeric type input method in Scanner. So, if you have been reading numbers and then you have text on a new line, then you first have to consume the line separator after the last number. Otherwise, the next call to nextLine() will pick up anything after the number and before the line separator instead of the text on the next line. I know, it's a little confusing and that's why it's annoying. It shouldn't be this nuanced.

The fix is pretty simple:
 
Campbell Ritchie
Marshal
Posts: 68899
275
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:. . . the next call to nextLine() will pick up the new line instead of the text on the next line. . . .

The Javadoc clearly says

. . . This method returns the rest of the current line, excluding any line separator at the end. . . .

...and nobody seems to read that. Not the ranch users, not the book authors, not the teachers. They read the name of the method, which isn't accurate, and misinterpret it. As Winston once said, there are so few tutorials about how to use Scanner.
I prefer to write a utility class, so you can write KeyboardInputs.nextLine("blahblahblah"); and get what you think of as the next line or part of line returned.
 
Rancher
Posts: 3714
34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

the name of the method, which isn't accurate,


I am confused.  Are you saying that nextLine should return the line end character(s) as part of the String it reads?
 
Junilu Lacar
Sheriff
Posts: 15519
263
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is where the "gotcha" lies:

The Scanner JavaDocs wrote:If the translation is successful, the scanner advances past the input that matched.

You'll find that text in the JavaDocs for the numeric input methods. What that doesn't explicitly explain is that it doesn't consume the next line separator which is the '\n' after 5 and before "Foo" in my example.
 
Junilu Lacar
Sheriff
Posts: 15519
263
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Norm Radder wrote:

the name of the method, which isn't accurate,

I am confused.


Understandably so.

Are you saying that nextLine should return the line end character(s) as part of the String it reads?


I don't think that's the expectation.

What the sentence that Campbell quoted means is that nextLine() will start from wherever the last input method left off and read everything up to and including the next line separator. That is, the String that nextLine() will return will consist of everything up to but excluding the next line separator but nextLine() still consumes the line separator. The numeric next*() methods of scanner consume delimiters and line separators before the numbers they parse and return, not the ones after. That's the nuance.

By "not accurate" I think Campbell is saying that the behavior, at least in this nuanced case, really is better described as "read the rest of the current line."
 
Campbell Ritchie
Marshal
Posts: 68899
275
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is exactly what I meant. If you simply read nextLine(), you are going to think it means,

Go to the next line and read that line,

...and that is exactly what that method doesn't do.
 
Norm Radder
Rancher
Posts: 3714
34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does there need to be a method to read the rest of the current line?
 
Junilu Lacar
Sheriff
Posts: 15519
263
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think so. You could certainly put a less surprising facade on top of Scanner.
 
Mark Spen
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:You could wrap the input in a Scanner and use the nextInt() for each integer, and after you've scanned a pair of integers, you call nextLine(), to move to the next line.



i'll try this but my programms says Exception in thread "main" java.util.NoSuchElementException: No line found
I have tried this, my startx,y and endx,y are the first and the second line with coodrinates and i read them with this way because my algorithm is quickhull, can you help me with my error?
       int StartX = 0;
       int StartY = 0;
       int EndX = 0;
       int EndY = 0;
       //create an object of Storage to store the data from the file which will be read
       Storage s = new Storage();
       File file = new File(args[0]);
       Scanner scan = null;

     
       try {
           String line = "";
           scan = new Scanner(file);
           StartX = Integer.parseInt(scan.next());
           StartY = Integer.parseInt(scan.next());
           EndX = Integer.parseInt(scan.next());
           EndY = Integer.parseInt(scan.next());

           while (scan.hasNext()) {
               //String[] t1 = line.split(" ");
               int x = scan.nextInt();
               int y = scan.nextInt();
               Coordinate c = new Coordinate(x, y);
               s.AddFirst(c);
               scan.nextLine();
           }
           scan.close();
 
Junilu Lacar
Sheriff
Posts: 15519
263
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When posting code, please UseCodeTags (←click that, it's a link to the instructions)

You are making it so much harder than it needs to be by reading your input as String then parsing to int. The Scanner already has a method to read in integer values without having to go through the rigamarole of parsing. Read the whole thread to understand the nuances of the Scanner and why Stephan suggested adding a nextLine() call which, if your input file contains all integer values, isn't necessary.
 
Campbell Ritchie
Marshal
Posts: 68899
275
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry. I didn't notice your post earlier.

Junilu Lacar wrote:. . . The last output will be 5, not "Foo". . . .

The output is confusing because you aren't separating the different outputs from the three methods and you cannot see the limits of the result for nextLine(). I suggest you use printf and wrap the output like this:- \u201c%s\u201d, which will wrap the output in“quotes” and will allow you to see that the last output from the third method isn't 5 after all.What you might not notice is the empty line 18, where you are printing the empty String; quotes would make that obvious. The nextLine() call is reading after the 5 and before the \n and the remainder of the line has no characters is, so it returns the empty String. I added the quotes and the empty String now appears in line 20:-
 
She still doesn't approve of my superhero lifestyle. Or this shameless plug:
Two software engineers solve most of the world's problems in one K&R sized book
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic