Java filing and highscore - java

Hi so I have an assignment due in 6 hours and I am completely lost. I have new methods added to my existing work done so far but I don't know how to do them.
The text file has names and scores, and the first method needs to check if the score is among the top 10 and return true/false:
the last method that I am lost in needs to write the high score into highscore.txt file, at the correct position(in descending order), the method uses readHighScore() method to find the line number where the record should be inserted.
public static void recordHighScore(String name, int score){
}

You can't insert data into text files. You can only append/rewrite. These are the steps:
Read data and store into objects.
Get the highest/lowest from the objects (you can also sort them with Collections.sort() or Arrays.sort())
Write the sorted objects back into the text file. (You will be overwriting the text file with new data)

Related

Writing to a specific position of a file

I have a text file which gets created by a batch script where the field position are always the same. Within that file, I want to go to a specific position and add a field to it.
For example, suppose my file has only two lines and has the following fields:
number customer_id account_no address price plan
number customer_id account_no address price plan
I want to add an extra field between address and price so the new file will look similar to this:
number customer_id account_no address newfield price plan
number customer_id account_no address newfield price plan
I couldn't find any Utility class that can go to a specific position of a line in a file and write to it.
I could do it the tedious way of placing the fields to an array including the whitespace and spitting it out field by field to a new file, however, that was too cumbersome and very tedious (since it has more than 90 fields) and was wondering if there is an easier way.
I could do it the tedious way of placing the fields to an array including the whitespace and spitting it out field by field to a new file, however, that was too cumbersome and very tedious (since it has more than 90 fields) and was wondering if there is an easier way.
If you were to do it by using Java, there is no way you can insert data in between text. It only allows you to append to the end of the file.
Anyway if you need to insert a new column and maintain the format consistency of the entire data file, you need to insert a whitespace for those rows without a value, hence rewriting all rows is still inevitable.
I couldn't find any Utility class that can go to a specific position of a line in a file and write to it
If you couldn't find one, you can write one yourself. It is actually not that tedious. Just write a utility class yourself, so you can use it in future.
//A brief example..
public final class FileUtility{
private static String filepath;
public static void setFilePath(String filepath){
FileUtility.filepath = filepath;
}
public static int searchField (String fieldname, int lineNo){
//return position of given field namein a specific line
}
public static void insertDataAt (String data, int column){
//return position of given field
}
public static boolean dataExist(String data, int lineNo){
//return true if given data exist at given line number
}
}
Forget about appending to the middle of the file. Files are sequence of bytes, so, you need to process all the bytes after insert points first to move them N bytes forward to create a place for your modification. This costs more than processing file on the fly and writing new lines to another file.

Add, Search, Delete in Java (without database) with only Arrays to hold values

I need to create a program that will accept values from users (name, age, bday, etc) and save these values in an array. Pretty easy right? But my problem is I want it to be able to save more than one set of inputs. I'm thinking of using a 2d array for this.
Example:
Element 0,0 will hold the value name1, 0,1 age1, 0,2 bday1
Element 1,0 will hold the value name2, 0,1 age2, 0,2 bday3
and so on... the user must be able to input as many sets of names, ages, and bdays as possible.
Then another functionality I need is that the program must be able to ask the user to input a searchKey, then the program will loop through the values of the 2d array until it finds that searchKey.
When it finds it, the user must be able to delete the entire row.
ex.
searchKey == name1.
When the program finds name1, the program must delete everything else in its row. (age1, bday1)
My question is.
Is it possible to do that using arrays only?
How?
Note: I'm not asking for a complete code. Just a clue on how should I do it would be greatly appreciated. Thanks!
the user must be able to input as many sets of names, ages, and bdays as possible.
Ask how many values user need to input. (get some idea from here for array)
Run input logic inside a loop.
that the program must be able to ask the user to input a searchKey, then the program will loop through the values of the 2d array until it finds that searchKey.
Once you complete above steps you will get idea(Update:Learn) how to do this
I would recommend you to go through some sample code from google with looping logic

Faster way to compare String objects

This is a method i use:
public void addSong(LibrarySong song){
//Check if doublicates exist
for(int i=0; i<intoPanel.getComponentCount(); i++){
if(song.getName().toLowerCase().equals(intoPanel.getComponent(i).getName().toLowerCase()))
return;
}
intoPanel.add(song);
}
.... to insert a new Component to a JPanel.I do this by checking if the name already exists.This works well,but when i have to D&D or insert manually 100.000 items then is running slower and slower.
My question is:
Can i use something better to do this process faster?Thanks....
Edit:
Following an answer i have changed the code to this:
String name;
public void addSong(LibrarySong song){
//Check if doublicates exist
name=song.getName().toLowerCase();
for(int i=0; i<intoPanel.getComponentCount(); i++){
if(name.equals(intoPanel.getComponent(i).getName().toLowerCase()))
return;
}
intoPanel.add(song);
}
Move the song.getName().toLowerCase() before the loop to do toLowerCase() once.
UPDATE: Actualy it's not good idea to add 100 000 components. Use e.g JList of JTable to represent the songs with a custom CellRenderer
You can write a sorted linked list class to store all your values. Because it is sorted, both insert and search will take O(logN) time, as you can use binary search.
Seems like a lot of work and for practical purposes the HashMap or HashSet are probably better.
First of all, don't add 100,000 items to your user interface. For the amount of user interface items you can add to the interface without confusing your users (a few hundred max), the performance of your linear search will be more than sufficient.
If you want to store more than a few hundred songs you will have to think about both your data structures and the user interface.
You can gain much more, both with respect to performance and with respect to user-friendliness, by choosing the right data structures and user interface. For data structure you can use for example a HashMap<String,LibrarySong>. Then you can use the following code:
if (!song.containsKey(song.getName().toLowerCase()) {
map.put(song.getName().toLowerCase(), song);
}
which almost runs in constant time.
For the user interface it probably best just to let the user enter a name, and then search the corresponding song in your data structure.
Have you considered using a database for your data storage?

Reading back into a BST from file

This is kind of a confusing question so I apologize as I'm not quite sure how to phrase it. Basically what I'm doing is working with sorting binary search trees. Throughout the program, the user adds a record to the tree, which is a node containing (int studentNumber, String firstName, String lastName, String major, double gpa). At the end of the program, the nodes are transposed to a LinkedList with a custom Node class I made, and then that list is serialized into a file.
Now, on start up, I want to basically read that file back into another list, display the list, then add it back into the BST so it can be sorted in various ways. My question stands on the point of reading each line (node) in the file and pulling the fields (int studentNumber, String firstName, String lastName, String major, double gpa) back into the tree from each "node". This is what I have so far in my read section:
public void loadRecord(LinkedList list) {
File file = new File("records.txt");
try
{
LinkedList<Node> list2;
ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
list2 = (LinkedList<Node>)input.readObject();
if (list2.size() > 0){
list.addAll(list2);
}//end if
else {
System.out.println("No elements");
}
}
//Catch Exceptions
//display list
}//end loadRecord
Once again.. I apologize if this makes no sense at all. And it's very possible I'm going in the completely wrong direction, so I appreciate any feedback. Please let me know what you think!
First, a
linked list and a binary search tree are two different data structures. You can't make one with another.
Let's say you have a list of numbers you want to store. The data is added to both structures in the same order. The linked list will look something like:
|5|-->|3|-->|7|-->|2|-->|6|-->|4|-->|8|-->|1|
"|x|" represents a node with x the data stored in it.
The arrow represents the reference a node has to its next.
data is ordered the same way it is entered.
The binary search tree:
5
/ \
/ \
3 7
/ \ / \
2 4 6 8
/
1
For each parent node there is a reference for a left node and a right node. The data in the left child node is smaller than the data in parent node and the data on the right child node is larger on that of the parent.
Therefore, whatever data is being entered it must be 'comparable' in a sense that one value can be larger or smaller than another. So if your data stored is students then one student must be of larger value than another(higher gpa, larger student number, last alphabetically in name, etc.).
Unlike a linked list, the standard API doesn't provide a binary search tree class.So you have implement your own. You need to be familiar with recursion to implement the BST. Make sure you decide how students are compared and implement the tree accordingly. Here is a link that can help :Binary Search Tree and Tree Traversal .
Next, you need to extract the student info from the record file and store it in the tree. It would help if you stated how the student information is ordered in the record.txt file.For now, I will assume that it is ordered such that data of each student is written in one line. I would implement a method in custom node(should called student) class that takes in a line,parses it, and store the data in the student's fields.
Then I would make a while loop that creates a new student, adds the current line to the appropriate method of the student object, and adds the student object into the tree as long as there is a next line in the input stream.
As I said, I will need more information on record file to explain further. Let me know if you need anymore clarifications.

Index of words found in document - Java

I am trying to write a program that takes in a text file as input, retrieves the words, and outputs each word with each line number that they are located in. I'm having a lot of trouble with this project, although I've made some progress...
So far I have an ArrayList which holds all of the words found in the document, without punctuation marks. I am able to output this list and see all the words in the text file, but I do not know where to go from here... any ideas?
example:
myList = [A, ACTUALLY, ALMOST,....]
I need to somehow be able to associate each word with which line they came from, so I can populate a data structure that will hold each word with their associated line number(s).
I am a programming novice so I am not very familiar with all the types of data structures and algorithms out there... my instructor suggested I use a dynamic multilinked list but I don't know how I would implement that verses ArrayLists and arrays.
Any ideas would be greatly appreciated. Thanks!
You should use a hash table. A hash table is a key/value pair. The key can be every word in the text file, the value, an array list containing the line numbers.
Basically, loop through every word in the text file. If that word is not in your list of words, add it as the key and the line number as the value in a list into the hash table. If that word is already in the table, append the line number to the array list.
Java has good docs on a hash table here
for you to get the methods you need.

Categories