Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

String and Int File Input  RSS feed

 
Aron Simbaba
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone,

I have been working on a problem that gives me five names and numbers in a text file as follows:

Sammy 3
Bill 2
Bobby 5
Smith 1
Jessica 8

This problem wants me to find the greatest number out of this list and to display it in this format:

Jessica has the most things with 8 things!


I have been stuck on trying to figure out how to separate the numbers and names in a way to where, when I compare the numbers I can pair them back up with the strings. I have only been able to code the file input and store it into an array. Here is what it looks like:


This is not a homework assignment, just a problem for practice and understanding.
 
Paweł Baczyński
Bartender
Posts: 2054
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would read the file line by line and call String.split(" ") on each line.
This assumes a name is always a single word.

You can create a class that holds a name and a number and have it to implement Comparable.
Alternatively, you can write a simple Comparator.
This would make a task of finding the biggest element pretty simple.

One question. What do you want to return if there is a tie for the first place?

One note. I don't like the idea of your method returning null.
If the method can't read the file make it throw an exception.
 
Liutauras Vilda
Marshal
Posts: 4641
318
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you required to use arrays? ArrayList could be more useful here, as you wouldn't need to count lines and define size as you do now.
Also, why you returning null on line 42 ?
 
Campbell Ritchie
Marshal
Posts: 55717
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are simply finding the largest value, that can easily be done without using an array at all.

[edit]Insert without which I had missed out earlier[/edit]
 
Aron Simbaba
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all, I have figured out the problem
 
Campbell Ritchie
Marshal
Posts: 55717
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And how did you do it?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!