How to update Java HashTable? - java

I have two Hashtables and one LinkedList in order like:
Hashtable<Character, Hashtable<String, LinkedList<String>>> hashTab = new Hashtable();
Hashtable<String, LinkedList<String>> string_list = new Hashtable();
LinkedList<String> data_list = new LinkedList();
Now i have a function through which i am passing values in the hashtables and linkedlist
public String createPlayerAccount(String FirstName, String LastName, int Age, String Username, String Password, String IPAddress)
{
char username_first_char = Username.charAt(0);
try
{
boolean username_exists = hashTab.get(username_first_char).containsKey(Username);
if(!username_exists)
{
String data_string = FirstName + " " + LastName + " " + Age + " " + Password + " " + IPAddress + playerStatus; //Pass user details to a string
data_list.add(data_string); //Add user details to the linked list
string_list.put(Username, data_list);
hashTab.put(username_first_char, string_list);
return("Dear " + FirstName + ", You have successfully registered");
}
else
{
return("Username already exists");
}
}
catch(Exception e)
{
String data_string = FirstName + " " + LastName + " " + Age + " " + Password + " " + IPAddress +" "+ playerStatus; //Pass user details to a string
data_list.add(data_string); //Add user details to the linked list
string_list.put(Username, data_list);
hashTab.put(username_first_char, string_list);
return("Username successfully added \n ");
}
}
The playerStatus is set to 0 by default. Now i am creating another function for Signin() in which i want the value of playerStatus to be updated to 1. What should i do?
Signin():
public String playerSignIn(String Username, String Password, String IPAddress)
{
char username_first_char = Username.charAt(0);
try
{
String user_profile;
boolean username_exists = hashTab.get(username_first_char).containsKey(Username);
if(username_exists)
{
playerStatus = "1";
//String data_string = Password + " " + IPAddress +" "+ playerStatus; //Pass user details to a string
//data_list.add(data_string); //Add user details to the linked list
//string_list.put(Username, data_list);
//hashTab.put(username_first_char, string_list); //Add user details to the linked list
//return();
//hashTab.put(username_first_char, string_list);
//user_profile = hashTab.get(username_first_char).get(Username).get(0);
return(user_profile);
/*String data_string = Username + " " + Password + " " + IPAddress +" "+ "1"; //Pass user details to a string
data_list.add(data_string); //Add user details to the linked list
string_list.put(Username, data_list);
hashTab.put(username_first_char, string_list);
String get_user_data = hashTab.get(username_first_char).get(Username).get(0);
String[] user_record = get_user_data.split(" ");
String users_status = user_record[5];*/
//return("User status updated: " + user_record[5]);
}
else
{
return("Invalid username or password");
}
}
catch(Exception e)
{
return("PAWNED");
}
}
NOTE: This is the server side of the code. I am making a Client-Server distributed System.

As mentioned in the comments, you need to create a POJO (object class) that will hold information about a given player. I'd name that class Player. If you need to have a string with the information about the player, for sending to the clients, just have a toString() method on the Player class.
When I developer multiplayer games, on the server side I usually use a ConcurrentHashMap to store the information. If the messaging system you are using needs hashtable then you will have headaches with synchronization, which can cause deadlocks if you don't know what you are doing.
Start refactoring your code. After you are using the Player class, the code should be much more readable, and you should be able to spot where another POJO might be useful too.

Related

program printing extra null that I can't seem to get rid of

public class Student {
private String courses = null;
}
.....Some code here.......
//Enroll in courses
public void enroll() {
//Get inside a loop and user hits Q
do {
System.out.print("Enter Course to Enroll(Q to quit): ");
Scanner in = new Scanner(System.in);
String course = in.nextLine();
if (!course.equals("Q")) {
courses = courses + "\n " + course;
tuitionBalance = tuitionBalance + costOfCourse;
}
else{ break; }
}while ( 1!= 0);
}
......Some code here......
//Show Status
public String showInfo() {
return "Name: " + firstName + " " + lastName +
"\nGrade level: " + gradeYear +
"\nStudent ID: " + studentId +
"\nCourses Enrolled:" + courses +
"\nBalance: $" + tuitionBalance;
}
}
Everything seems to be running just fine. But there's an extra null printed after the Courses Enrolled that sticks out like a sore thumb. How could I get rid of it? I've tried setting the String variable courses to null and also without assigning but doesn't seem to affect the result
Name: Frank Kuo
Grade level: 1
Student ID: 11001
Courses Enrolled:null
Math101
Balance: $0
You can replace private String courses = null; with private String courses = ""; to get rid of the null.

SQLITE delete method in Java

I have a method that should delete a Person(a row) from my database.
I am getting the error message that I created in the catch. I just started working with Databases and I have mostly been piecing together different techniques. I'm not sure what to do
public static void deletePerson(String firstNameOfPersonToDelete, String lastNameOfPersonToDelete) {
Statement stmt = null;
try {
// Create database connection
Connection c = DriverManager.getConnection("jdbc:sqlite:PERSON.db");
// Create Statement object
stmt = c.createStatement();
// Get person we're about to delete
String getPersonQuery = "SELECT SSN FIRSTNAME, LASTNAME, AGE, CREDITCARD FROM PERSON WHERE FIRSTNAME = '"
+ firstNameOfPersonToDelete + "' AND LASTNAME = '" + lastNameOfPersonToDelete + "'";
ResultSet rs = stmt.executeQuery(getPersonQuery);
String ssn = rs.getString("SSN");
String firstName = rs.getString("FIRSTNAME");
String lastName = rs.getString("LASTNAME");
String age = rs.getString("AGE");
String creditCard = rs.getString("CREDITCARD");
String deletePersonStatement = "DELETE FROM PERSON WHERE FIRSTNAME = '" + firstName + "' AND LASTNAME = '"
+ lastName + "'";
stmt.executeUpdate(deletePersonStatement);
System.out.println("The following record was deleted:\n" + ssn + "\n" + firstName + " " + lastName + "\n"
+ age + "\n" + creditCard);
System.out.println("\nThe database contains the following records: ");
ArrayList<Object> myPeople = findAllPeople();
for (Object element : myPeople) {
System.out.println(element.toString());
}
} catch (SQLException e) {
e.printStackTrace(System.err);
System.out.println("Error: The person: \"" + firstNameOfPersonToDelete + " " + lastNameOfPersonToDelete
+ "\" was not found. No records were deleted.");
System.out.println("\nThe database contains the following records: ");
ArrayList<Object> myPeople = findAllPeople();
for (Object element : myPeople) {
System.out.println(element.toString());
}
}
}
java.sql.SQLException: no such column: 'SSN'Error: The person: "Fitzgerald Grant" was not found. No records were deleted.
at org.sqlite.jdbc3.JDBC3ResultSet.findColumn(JDBC3ResultSet.java:48)
at org.sqlite.jdbc3.JDBC3ResultSet.getString(JDBC3ResultSet.java:443)
at Test.deletePerson(Test.java:181)
at Test.main(Test.java:65)
SELECT SSN FIRSTNAME, LASTNAME, AGE, CREDITCARD FROM ...
^
This is the same as SSN AS FIRSTNAME, i.e., in the output of the query, the SSN column is renamed to FIRSTNAME. You apparently forgot a comma.
In any case, you got this error because there is no SSN column.
You have to ensure that you create this table with this column, or if you have an old database, that you add this column.

how do you put a string into a specific spot in an array based on a number in java?

How would I put a string into an array in a specific spot based on a number?
public Student(String firstName, String lastName, String studentNumber, int grade){
courseTimeTable = new String[] {"Block " + courseBlock + ": " + course, "Block " + courseBlock + ": " + course};
}
public void setCourse(int block, String courseCode) {
course = courseCode;
courseBlock = block;
}
So how would I put the "course" into the "courseTimeTable" array based on the "courseBlock"
You will need to know the maximum size of courseTimeTable first.
Then you can do:
courseTimeTable = new String[<maximumSize>];
courseTimeTable[courseBlock] = ...;

Null Pointer Exception Error, not sure why

So I had to create a method that separated input string into first/middle/last names, counted the number of "students" created, etc, and then I had to create a class that tested those methods.
public void setName(String newName)
{
String[] nameInput = newName.split(" ");
if(nameInput.length == 0)
{
System.out.println("Error, please enter at least two names.");
newName = null;
}
else if(nameInput.length == 1)
{
firstName = nameInput[0];
middleName = "";
lastName = nameInput[1];
newName = firstName + lastName;
}
else if(nameInput.length == 2)
{
firstName = nameInput[0];
middleName = nameInput[1];
lastName = nameInput[2];
newName = firstName + middleName + lastName;
}
else
{
System.out.println("Error! You can only enter up to three names.");
}
}
public String getName()
{
if (middleName == null)
{
return firstName + " " + lastName;
}
else
return firstName + " " + middleName + " " + lastName;
}
public String getId()
{
return identifier = generateID();
}
#Override
public String toString()
{
return getName() + "\n" + "(" + generateID() + ")";
}
private String generateID()
{
return UUID.randomUUID().toString();
}
and this is the way I am testing the code:
public static void testStudent()
{
System.out.println("Trying to create testStudent1 with a single name...");
testStudent1 = new Student("A");
System.out.println("testStudent1.toString() is " + testStudent1.toString());
System.out.println("testStudent1.getFirstName() is " + testStudent1.getFirstName());
System.out.println("testStudent1.getMiddleName() is " + testStudent1.getMiddleName());
System.out.println("testStudent1.getLastName() is " + testStudent1.getLastName());
System.out.println("Trying to create testStudent2 with two names...");
testStudent1 = new Student("A B");
System.out.println("testStudent2.toString() is " + testStudent2.toString());
System.out.println("testStudent2.getFirstName() is " + testStudent2.getFirstName());
System.out.println("testStudent2.getMiddleName() is " + testStudent2.getMiddleName());
System.out.println("testStudent2.getLastName() is " + testStudent2.getLastName());
System.out.println("Trying to create testStudent3 with three names...");
testStudent1 = new Student("A B C");
System.out.println("testStudent3.toString() is " + testStudent3.toString());
System.out.println("testStudent3.getFirstName() is " + testStudent3.getFirstName());
System.out.println("testStudent3.getMiddleName() is " + testStudent3.getMiddleName());
System.out.println("testStudent3.getLastName() is " + testStudent3.getLastName());
}
I keep running into a null pointer exceptions when it tests toString for a student with 2 names, and I have no clue why.
Edit: The issue is with the testStudent variable in the testStudent() method.
System.out.println("Trying to create testStudent1 with a single name...");
testStudent1 = new Student("A");
System.out.println("testStudent1.toString() is " + testStudent1.toString());
System.out.println("testStudent1.getFirstName() is " + testStudent1.getFirstName());
System.out.println("testStudent1.getMiddleName() is " + testStudent1.getMiddleName());
System.out.println("testStudent1.getLastName() is " + testStudent1.getLastName());
System.out.println("Trying to create testStudent2 with two names...");
Student testStudent2 = new Student("A B");
System.out.println("testStudent2.toString() is " + testStudent2.toString());
System.out.println("testStudent2.getFirstName() is " + testStudent2.getFirstName());
System.out.println("testStudent2.getMiddleName() is " + testStudent2.getMiddleName());
System.out.println("testStudent2.getLastName() is " + testStudent2.getLastName());
System.out.println("Trying to create testStudent3 with three names...");
Student testStudent3 = new Student("A B C");
System.out.println("testStudent3.toString() is " + testStudent3.toString());
System.out.println("testStudent3.getFirstName() is " + testStudent3.getFirstName());
System.out.println("testStudent3.getMiddleName() is " + testStudent3.getMiddleName());
System.out.println("testStudent3.getLastName() is " + testStudent3.getLastName());
Since you are re-using the testStudent1 variable to create a new Object of Student class and not using them to invoke getter functions, it will throw an NPE for testStudent2 and testStudent3 variables.
Answer for old issue: The issue is with your while statement. It will never stop.
You can just find out the count by doing nameInput.length for the String array.
It should be like this:
String[] nameInput = newName.split(" ");
if (nameInput.length == 1)
{
System.out.println("Error, please enter at least two names.");
newName = null;
}
else if (nameInput.length == 2)
{
...
}
else if (nameInput.length == 3)
{
...
}
else
{
...
}
You could use StringTokenizer class to help you with this.
import java.util.StringTokenizer
StringTokenizer test = new StringTokenizer("An example string");
while (test.hasMoreTokens()) {
System.out.println(test.nextToken());
}
Output:
An
example
string.
The countTokens() method can provide how many tokens a string will provide prior processing. That way you will know if you have a middle name or not.
please check trim() method
public static void getName(String newName) {
newName = newName.trim();
String fullName = null;
String[] nameInput = newName.split(" ");
switch (nameInput.length) {
case 2:
fullName = mergeName(nameInput[0], "", nameInput[1]);
break;
case 3:
fullName = mergeName(nameInput[0], nameInput[1], nameInput[2]);
break;
default:
System.out.println("Error, please enter at least two names.");
break;
}
System.out.println(fullName);
}
public static String mergeName(String firstName, String middleName,
String lastName) {
String name = firstName+" " + middleName+" " + lastName;
return name;
}

Deleting a String of data from Array List

I have been creating a program that is to add search delete bookings etc...
After hours I finally thought I was making progress but when I delete a booking my program finds the correct booking returns the correct information for that booking but deletes a different booking.
I have attached the files in a zip as if I displayed them they would take up lots of screen space. The program has been made in BlueJay.
Code for decleration and adding of objects into my array list
public Hostel(String hostelName)
{
this.hostelName = "Newcastle Hostel";
bookings = new ArrayList<Booking>();
}
public String getHostelName()
{
return hostelName;
}
public String addBooking(String roomID, String roomType, String guest)
{
if (roomID.equals(""))
return "Error Please Entre Room ID";
else if (roomType.equals(""))
return "Error Please Entre Room Type";
else if (guest.equals(""))
return "Error Please Entre Guest Name";
bookings.add(new Booking(roomID,roomType,guest));
return "Room " + roomID + " " + roomType + " Has Been Booked For " + guest;
}
This is taken from my hostel class
public String deleteBooking(String roomID)
{
int index = 0;
for ( Booking s : bookings )
{
if ( s.getRoomID().equals(roomID))
{
//return "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
String deleteMessage = "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
int response = JOptionPane.showConfirmDialog(null, deleteMessage, "Confirm Delete",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.NO_OPTION)
{
} else if (response == JOptionPane.YES_OPTION)
{
bookings.remove(index);
}
index++;
}
}
return " Cannot find room";
}
this is taken from my GUI class
else if (item.equals("Cancel Booking"))
{
newBookingButton.setEnabled(false);
cancelBookingButton.setEnabled(false);
String roomID = JOptionPane.showInputDialog(this, "Enter a room ID", "Delete a Booking", JOptionPane.QUESTION_MESSAGE);
output.setText(hostel.deleteBooking(roomID));
newBookingButton.setEnabled(true);
cancelBookingButton.setEnabled(true);
}
Any additonal code needed either ask or there is a full copy in the link above thanks
Your loop only increments the index if the room ID of the current room is equal to the ID of the room to delete. The line
index++;
should be out of the if block.
EDIT:
The other problem is that you're trying to remove elements a collection while iterating on it. This is only possible if you use an Iterator to iterate over the collection, and use the iterator's remove method to remove the current element. Note that even if it was possible, since you remove the element at the given index, the index should not be incremented since you have just removed the element at this index.
Example of using an iterator:
for (Iterator<Booking> it = bookings.iterator(); it.hasNext(); ) {
Booking b = it.next();
if (...) {
it.remove();
}
}
Basically when s.getRoomID().equals(roomID) is true your if block is executed so no matter what is the response of the user your index is incremented. So, do this:
if ( s.getRoomID().equals(roomID))
{
//your code
}
index++
I just looked into your code, and seems like you are trying to iterate over a collection and also modifying the values at the same time. With enhanced for loop, such things do give errors, so instead of using the enhanced for loop, you must use a normal for loop. So I had modified your deleteBookings Method for the respective change.
public String deleteBooking(String roomID)
{
//for ( Booking s : bookings )
for (int i = 0; i < bookings.size(); i++)
{
Booking s = bookings.get(i);
if ( s.getRoomID().equals(roomID))
{
//return "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
String deleteMessage = "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
//int r = JOptionPane.showOptionDialog,null("Are you sure you would like to delete the following \n"
//+ "deleteMessage",
//"Delete a booking",
//JOptionPane.YES_NO_OPTION,
//JOptionPane.QUESTION_MESSAGE,null,null,null);
//if (r == JOptionPane.YES_OPTION) {
// bookings.remove(index);
//}
//if (r == JOptionPane.NO_OPTION){
// return "Booking Was Not Canceled";
// }
int response = JOptionPane.showConfirmDialog(null, deleteMessage, "Confirm Delete",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.NO_OPTION)
{
} else if (response == JOptionPane.YES_OPTION)
{
//bookings.remove(index);
bookings.remove(i);
return deleteMessage + " has been DELETED."; /*I did this.*/
}
}
}
return " Cannot find room";
}
Moreover, after this
bookings.remove(i);
You forgot to return something like
return deleteMessage + " has been DELETED."; /*I did this.*/
Since you failed to return a String on successful completion, that's the reason why it returns "Cannot find room.", even after successful deletion.
Rest of the code is perfect.
Hope that might solve your query.
Regards

Categories

Resources