• Post Reply Bookmark Topic Watch Topic
  • New Topic

Converting char to integer froms a file.  RSS feed

 
Robson Martinz
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good afternoon, everyone! I want to make a program that reads numbers from a text file and transforms them into integers and then displays on the screen, but i can not do this with numbers greater than ten as the read () method of the BufferedReader only reads character by character. If he has to read the number 34 or 2343, for example, i don't know how to turn that chars into a single integer value. How can i do this in a more elegant way than the way i show to you below? That was the solution i found, but i believe there is a cleaner and more elegant way of doing. I would also use the Integer and Character type to solve this problem. I'm trying to use less primitive data types. The following code works fine just with number 0 -> 99.

 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is a format of your file?
You don't have to read character after character.
You can read text file line by line using new BufferedReader(new FileReader(filename));
BufferedReader has a nice method readLine that will do the job.
The only thing you need to take care of is parsing Strings returned by it.
 
Robson Martinz
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is a txt file. And if i have something like this in the file:
34 5677 2 567577

How can i make these chars in four Integer?
 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, you already know how to read a line from a file from my previous post.
If you read one line you'll end up with a String "34 5677 2 567577".
First, you need to split this into separate Strings, one for each number. Class String has a method split that will do the job.
Next, you need to convert each of those Strings into int. Look for Integer.parseInt() method.
 
Robson Martinz
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, i understand.
Thank you, Pawel Pawlowicz!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!