I'm taking a Java class and one of our labs is to create a sort of chat site. There was some starter code that the professor/ TA did for us, but then we had to create the rest of it. I am getting an ArrayIndexOutOfBounds error, but can't figure out why.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at amazbay.Website.addPerson(Website.java:28)
at amazbay.Driver.addPeopleTo(Driver.java:13)
at amazbay.Driver.main(Driver.java:83
I have spent around 10 hours trying to troubleshoot this by looking up and trying different solutions from this forum and others. I mostly program in Python, so I'm not sure if I am overlooking a syntax error or if there is something more serious wrong with this.
I have attached the code below, it is in a package so I added it the best way I could, but that is how they want us to do this lab.
Website line 28 is users[users.length] = newArray[newArray.length]; Driver line 13 is w.addPerson(TA); Driver line 83 is addPeopleTo(w);
Thanks for any advice!
package amazbay;
import java.util.Scanner;
public class Driver
{
public static void addPeopleTo(Website w)
{
// Add one person to the Website. You will likely have to change this
// if you update the Person constructor.
Person TA = new Person(1001, "255", "TA");
//Person TA = new Person(1001);
w.addPerson(TA);
// Add several other people to the website.
w.addPerson(new Person(1002, "Smith", "John"));
w.addPerson(new Person(1003, "1", "Student"));
w.addPerson(new Person(1004, "2", "Student"));
}
public static void handlePrintMessages(Website w, int firstUID, int secondUID)
{
// Using w.getMessagesFor(), prints the messaging history between
// the Person with firstUID and the Person with secondUID, in the order
// those messages were sent.
Person a = w.getPersonByUID(firstUID);
if (a == null)
{
System.out.println("Person with uid "+firstUID+" not found, can't print message history");
}
Person b = w.getPersonByUID(secondUID);
if (b == null)
{
System.out.println("Person with uid "+secondUID+" not found, can't print message history");
}
System.out.println("Showing chat history between ["+a.getFirstName()+"] and ["+b.getFirstName()+"]");
boolean any = false;
Message[] messages = w.getMessagesFor(firstUID);
for(int i = 0; i < messages.length; i+=1)
{
// TODO - once you have implemented the code in Message.java, uncomment
// this - it will not compile until then. You may need to change
// some of the method names used here.
if (messages[i].getsender().getUID() != secondUID &&
messages[i].getreceiver().getUID() != secondUID)
{
continue;
}
any = true;
System.out.println("At (" + messages[i].getPrettyWhenSent()+"), "+
messages[i].getsender()+" said: \"" +
messages[i].getmessage() + "\"");
}
if (!any)
{
System.out.println("NO MESSAGE HISTORY FOUND FOR THESE TWO USERS.");
}
}
public static void printChatHistory(Scanner s, Website w)
{
System.out.print("Enter the first person's UID: ");
int firstUID = s.nextInt();
s.nextLine(); // clear the carriage return
System.out.print("Enter the second person's UID: ");
int secondUID = s.nextInt();
s.nextLine(); // clear the carriage return
handlePrintMessages(w, firstUID, secondUID);
}
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
Website w = new Website();
addPeopleTo(w);
while(true)
{
// First: support for typing something to end the program naturally,
// instead of looping forever.
System.out.print("Type 'quit' to exit, anything else to keep going: ");
if ("quit".equals(s.nextLine()))
{
break;
}
// Main Prompt and input handling.
System.out.print("Enter the sender's UID, or -1 to view chat history: ");
int uid = s.nextInt();
s.nextLine(); // clear the carriage return
if (uid == -1)
{
printChatHistory(s, w);
continue;
}
Person sender = w.getPersonByUID(uid);
if (sender == null)
{
System.out.println("Person with UID == " + uid + " not found.");
continue;
}
// Ask for the receiver's uid, look them up, and handle the
// case where they are not found.
System.out.print("Enter the receiver's UID: ");
uid = s.nextInt();
s.nextLine(); // clear the carriage return
Person receiver = w.getPersonByUID(uid);
if (receiver == null)
{
System.out.println("Person with UID == " + uid + " not found.");
continue;
}
// Get the message and the timestamp
System.out.print("Enter the message text being sent: ");
String message = s.nextLine();
long whenSent = System.currentTimeMillis();
sender.sendMessageTo(receiver, message, whenSent, w);
}
}
}
package amazbay;
public class Message
{
private Person sender;
private Person receiver;
private String message;
private long whenSent;
public Person getsender(){
return sender;
}
public Person getreceiver(){
return receiver;
}
public String getmessage(){
return message;
}
public long getwhensent(){
return whenSent;
}
public Message(Person sender, Person receiver, String message, long whenSent)
{
if (sender == null)
{
throw new IllegalArgumentException("sender can not be null in Message.Message()");
}
if (receiver == null)
{
throw new IllegalArgumentException("receiver can not be null in Message.Message()");
}
if (sender.getUID() == receiver.getUID())
{
throw new IllegalArgumentException("sender and receiver can not be the same person in Message.Message()");
}
this.sender = sender;
this.receiver = receiver;
this.message = message;
this.whenSent = whenSent;
}
public String getPrettyWhenSent()
{
// This is a fancy way of printing the day and time using java.time.* classes;
// We have not seen this in class.
return (java.time.LocalDateTime.ofEpochSecond(
whenSent/1000L, 0, java.time.ZoneOffset.UTC)
.format(java.time.format.DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss")));
}
}
package amazbay;
import java.util.Scanner;
public class Person
{
// TODO - add the other fields mentioned in the handout, and create
// getters and setters for each.
private int uid; // Create Private int uid
public Person(int uid, String lastName, String firstName) //Set uid, lastname, first, to the person
{
setUID(uid);
setLastName(lastName);
setFirstName(firstName);
}
public int getUID() // Get the uid
{
return uid;
}
public void setUID(int uid) // Set the uid so it can be sent to public Person
{
this.uid = uid;
}
public void sendMessageTo(Person receiver, String message, long when,
Website website) // Send a message
{
Message m = new Message(this, receiver, message, when);
website.addMessage(m);
}
// Setup First Name
private String firstName; // Create private string firstName
public String getFirstName() // Get the firstName
{
boolean correct = false;
while(correct = false){
Scanner tempScan = new Scanner(System.in);
System.out.println("Enter your first name (also known as given name): ");
String firstName = tempScan.nextLine();
Scanner correctFirstName = new Scanner(System.in);
System.out.println("Your first name is: " + firstName);
System.out.println("Is this correct? y or n");
String tempCorrect = correctFirstName.nextLine();
if (tempCorrect.equals("y")){
correct = true;
}
}
return firstName;
}
public void setFirstName(String firstName) // Set firstName
{
this.firstName = firstName;
}
// Setup Last Name
private String lastName; // Create private string lastName
public String getLastName() // Get the lastName
{
boolean correct = false;
while(correct = false){
Scanner tempScan = new Scanner(System.in);
System.out.println("Enter your last name (also known as family name): ");
String lastName = tempScan.nextLine();
Scanner correctLastName = new Scanner(System.in);
System.out.println("Your last name is: " + lastName);
System.out.println("Is this correct? y or n");
String tempCorrect = correctLastName.nextLine();
if (tempCorrect.equals("y")){
correct = true;
}
}
return lastName;
}
public void setLastName(String lastName) // Set lastName
{
this.lastName = lastName;
}
private String fullName;
public String getFullName(String firstName,String lastName)
{
String fullName = firstName + lastName;
return fullName;
}
}
package amazbay;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
public class Website
{
private Person[] users;
public Website()
{
users = new Person[0];
}
public void addPerson(Person p)
{
// We will need to create a new Person[] array that is 1 more in size
// than what `users` used to be, and copy the contents of `users`
// into it.
Person[] newArray = new Person[users.length+1];
for(int i = 0; i < users.length; i+=1)
{
newArray[i] = users[i];
}
newArray[newArray.length-1] = p;
users[users.length] = newArray[newArray.length];
}
public Person getPersonByUID(int uid)
{
for(int i=0; i < users.length; i+=1)
{
if(users[i].getUID() == uid)
{
return users[i];
}
}
return null;
}
private String messageArray[][];
public void addMessage(Message m)
{
Scanner userInputID = new Scanner(System.in);
System.out.println("What is your user ID? ");
int inputID = Integer.parseInt(userInputID.nextLine());
int i = inputID;
ArrayList<String> userMessages = new ArrayList<String>();
userMessages.add(m.getmessage());
String[] tempMessageArray = new String[userMessages.size()];
userMessages.toArray(tempMessageArray);
int x = tempMessageArray.length;
String messageArray[][] = new String[i][x];
for(String[] row: messageArray)
Arrays.fill(row, users[i]);
for(String[] column: messageArray)
Arrays.fill(column, tempMessageArray[x]);
}
public String[][] getMessageArray(){
return messageArray.clone();
}
public Message[] getMessagesFor(int uid)
{
Scanner userInputID = new Scanner(System.in);
System.out.println("User ID to check: ");
int inputID = Integer.parseInt(userInputID.nextLine());
Object[] column = new Object[messageArray[inputID].length];
for(int i=0; i<column.length; i++){
column[i] = messageArray[inputID][i];
}
System.out.println(column);
//for(int i=0; i < messageArray.length; i+=1)
return null;
//new Message[0];
}
}