Creating object from scanner input - java

import java.util.Scanner;
public class PhoneBook {
private Address[] addresses;
private String[] phoneNumbers;
private Person[] people;
public static void startMenu() {
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner intScan = new Scanner(System.in);
String menu = ("Please Make A selection Below: \n1 - Add new Record"
+ " \n2 - Delete Record "
+ "\n3 - Find Record By Telephone Number "
+ "\n4 - Find Record By First Name "
+ "\n5 - Find Record By Last Name"
+ "\n6 - Update a Record"
+ "\n7 - Exit");
int selection;
String inputString;
do {
System.out.println(menu);
selection = intScan.nextInt();
Entry[] entry5 = new Entry[0];
Entry tempEntry = null;
switch (selection) {
case 1:
System.out.println("Please enter a new record as John Michael West Doe, 574 Pole ave, St. Peter, MO, 63303, 3142752000");
inputString = input.nextLine();
// creating a new obj ref variable
tempEntry = new Entry(inputString);
// calling the method on the obj ref variable
tempEntry.addEntry(inputString);
System.out.println(tempEntry.toString());
System.out.println(menu);
break;
case 2:
// method to remove record
break;
case 3:
// method
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
}
} while (selection != 11);
}
}
I'm trying to figure out why my object is not creating when I set the object reference variable equal a new Entry. I also call the .addEntry method for the tempEntry object reference variable and pass in the scanner input with no success. I just get 'null null null' printed to the console. It won't let me put in parameters though.
tempEntry = new Entry();
tempEntry.addEntry(inputString);
I'm also trying to add 1 to the Entry[] array as new records are passed in, but can't seem to find a way around that either.
I'm not sure where I'm supposed to put the:
tempEntry = new Entry(inputString);
and
Entry[] entry5 = new Entry[0];
But, I've been moving them around and running the code quite a bit. Any thoughts? Here is my add entry method in my Entry Class:
import java.util.Scanner;
public class Entry {
private Name newName;
private Address address;
private Phone phone;
public String string;
public Entry(Name newName, Address address, Phone phone) {
this.newName = newName;
this.address = address;
this.phone = phone;
}
public Entry(String string) {
this.string = string;
}
public Entry() {
}
public Name getName() {
return this.newName;
}
public Address getAddress() {
return this.address;
}
public Phone getPhone() {
return this.phone;
}
public void setName(Name newName) {
this.newName = newName;
}
public void setAddress(Address address) {
this.address = address;
}
public void setPhone(Phone phone) {
this.phone = phone;
}
**// add entry method
public Entry addEntry(String input) {
String name, street, city, state, zipCode, phoneNumber;
name = "";
street = "";
city = "";
state = "";
zipCode = "";
phoneNumber = "";
String[] arr = input.split(",");
name = arr[0];
street = arr[1].trim();
city = arr[2].trim();
state = arr[3].trim();
zipCode = arr[4].trim();
phoneNumber = arr[5].trim();
Name fullName = splitName(name);
Address address = makeAddress(street, city, state, zipCode);
Phone phoneNum = makePhone(phoneNumber);
Entry entry1 = new Entry(fullName, address, phoneNum);
return entry1;
}**
// split name method
public static Name splitName(String name) {
String fName, mName, lName;
fName = "";
mName = "";
mName = "";
String [] names = name.split(" ");
fName = names[0];
for (int i = 1; i < names.length - 1; i++) {
mName += names[i];
if (i != names.length - 1) {
mName += " ";
}
}
lName = names[names.length - 1];
Name name1 = new Name(fName, mName, lName);
return name1;
}
// Address method
public static Address makeAddress(String street, String city, String state, String zipCode) {
Address address1 = new Address(street, city, state, zipCode);
return address1;
}
// Phone method
public static Phone makePhone(String phoneNumber) {
String area, prefix, line;
area = phoneNumber.substring(0, 3);
prefix = phoneNumber.substring(3, 6);
line = phoneNumber.substring(6);
Phone phone1 = new Phone(area, prefix, line);
return phone1;
}
#Override
public String toString() {
return this.newName + " " + this.address + " " + this.phone;
}
}

You can remove the addEntry() function and take all the code that is in that function and move it to the Entry(String string) constructor. Except the last 2 lines. Just delete those.
public Entry(String input)
{
String[] arr = input.split(",");
if (arr.length < 6) {
throw new IllegalArgumentException();
}
newName = splitName(arr[0]);
address = makeAddress(arr[1].trim(), arr[2].trim(), arr[3].trim(), arr[4].trim());
phone = makePhone(arr[5].trim());
}
Then in the main code:
case 1:
System.out.println("Please enter a new record as John Michael West Doe, 574 Pole ave, St. Peter, MO, 63303, 3142752000");
inputString = input.nextLine();
tempEntry = new Entry(inputString);
System.out.println(tempEntry.toString());
System.out.println(menu);
break;
Note that this does not add anything to the array. If you want to do that first you must declare the array correctly and set the correct index:
//Entry[] entry5 = new Entry[0]; <- creates a zero-length array
Entry[] entry5 = new Entry[5]; // creates array with room for 5 items
int index = 0; // Where to add the next item
....
case 1:
System.out.println("Please enter a new record as John Michael West Doe, 574 Pole ave, St. Peter, MO, 63303, 3142752000");
inputString = input.nextLine();
entry5[index] = new Entry(inputString);
System.out.println(entry5[index].toString());
index += 1;

Related

How to get a text file in a one dimensional array

I need to figure out how to get a text file of passengers in a one dimensional array, and split it up by name, street address, city, state, weight, and seat number. I have tried using a while loop and a for loop to do this and I cannot get anything going. This is what I have so far.
This is my main method
import java.util.Scanner;
import java.io.*;
public class Trip_Jarrad
{
public static void main(String[]args) throws FileNotFoundException
{
Scanner file = new Scanner(new File("PassengerList.txt"));
Passengers[] passengers = new Passengers[16];
}
}
This is my object class
public class Passengers {
String fullName;
String streetAddress;
String city;
String state;
double weight;
String seatNum;
public Passengers(String n, String s, String c, String st, double w, String seat) {
fullName = n;
streetAddress = s;
city = c;
state = s;
weight = w;
seatNum = seat;
}
public String getName() {
return fullName;
}
public String getAddress() {
return streetAddress;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
public double getWeight() {
return weight;
}
public String getSeat() {
return seatNum;
}
public String toString() {
return " " +fullName+ "" +streetAddress+ "" +city+ "" +state+ "" +weight+ "" + seatNum;
}
And this is the text file that I am trying to get read.
Jarrad/Self/9 Ely Trail/Yodaloo, Ga/231.2/
Paul/Murray/123 Chenango Street/Montrose, Pa/212.3/
Allison/Lewis/1884 Vestal Parkway/Vestal, Ny/108.2/
Theresa/Grabowski/296 Oak Street/Goshen, Ny/121.1/
David/Parker/133 Pennsylvania Ave/Springfield, Ma/189.7/
Stephen/Post/722 Newark Valley Road/Owego, Ny/245.0/
Emily/Post/722 Newark Valley Road/Owego, Ny/174.9/
Deborah/George/143 Alpine Road/Las Vegas, Nv/145.2/
Allen/George/143 Alpine Road/Las Vegas, Nv/312.7/
Judy/Hellman/18801 Jefferson Ave/Brentwood, Ca/134.4/
Joel/Aylesworth/56 Washington Street/Akron, Oh/322.2/
Marci/Podder/1884A San Clemente Ave/Apple Valley, Ca/113.1/
Allen/Parker/129 Trenton Street/Springfield, Ma/134.3/
Trisha/Johnson/2978 Utica Avenue/Syracuse, Ny/167.2/
Mike/Squier/546 Owego Avenue/Maine, Ny/113.4/
Meg/Merwin/123 Appleton Lane/Endicott, Ny/114.8
To split a string in Java, use String.split() method:
String s = "Jarrad/Self/9 Ely Trail/Yodaloo, Ga/231.2/";
String[] array_split = s.split("/");
// the array is {"Jarrad", "Self", "9 Ely Trail", "Yodaloo", "Ga", "231.2"}
Using the NIO files API, you can easily convert your lines into a list of Passenger objects:
List<Passengers> passengers = java.nio.file.Files
.lines(java.nio.file.Paths.get( "PassengerList.txt"))
.map(line -> line.trim().split("/"))
.map(arr -> new Passengers(arr[0], arr[1], arr[2], arr[3], Double.parseDouble(arr[4]), arr[5]))
.collect(java.util.stream.Collectors.toList());
First we call sc.nextLine() to get a whole line from the File.
Then we use String[] split(String regex) to split the term into its separate values and pass them to the constructor
Scanner sc;
Passenger[] passengers = new Passenger[16];
for (int i = 0; i < passengers.length; i++) {
String[] values = sc.nextLine().split("/");
String fullName = values[0] + values[1];
// todo: init remaining values
Passenger passenger; // todo: initialise
passengers[i] = passenger;
}

Phone Book (Java) Task: Print all matches if only last name is entered

I'm creating a phone book for an assignment and I'm stuck on this part. I need to print every match if the user didn't enter the first name. Currently, my program only print the first match.
Part of the instruction: If the user enters just the last name, the program goes through the entire array, printing out every match. If the user enters both first and last names, the program will print out the first match, then stop.
This is my search method in my PhoneBook class:
// use linear search to find the targetName.
// Return a reference to the matching PhoneEntry
// or null if none is found
public PhoneEntry search(String fName, String lName) {
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName)) {
if (phoneBook[j].firstName.equals(fName) || fName.equals("")) {
return phoneBook[j];
}
}
}
return null;
}
And this is my loop for prompting the user and printing the information in my Tester
do {
// Prompt the user to enter the name
System.out.print("Pleast enter the last name to search: ");
lastName = input.nextLine();
System.out.print("Please enter the first name to search: ");
firstName = input.nextLine();
// search for the person
entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());
// if found, print out the entry
if (entry != null) {
System.out.println(entry.firstName + " " + entry.lastName + ": " + entry.phone);
}
// if user enter quit, then say good bye
else if ("quit".equals(lastName)) {
System.out.println("Good Bye!");
}
// if not found, tell the user
else {
System.out.println("Name not found.");
}
} while (!"quit".equals(lastName));
I just need to get the program to print all of the matches if only last name is entered. I'm new to arrays and I only know Java.
Thank you in advance! :)
Update
Thanks to #TyeolRik, I was able to do "something" about it. His way was using the cases way and sorry but I do not know how to do cases. I implemented his way into mine, but I do not know how to connect them between classes. I tried to put "return resultList" on the search method, but it didn't allowed me to because it is a PhoneEntry[] instead of PhoneEntry, and that is true, but I can't search it using "entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());" if it is an array type. I need help! Thank you guys.
This is my complete current code (I have 3 classes):
PhoneBook (ignore the add method because that is for something else that I'm doing for another instruction):
public class PhoneBook {
PhoneEntry[] phoneBook;
PhoneEntry[] resultList = new PhoneEntry[10];
// constructor
public PhoneBook() {
phoneBook = new PhoneEntry[10];
// load the phone book with data
phoneBook[0] = new PhoneEntry("James", "Barclay", "(418) 665-1223");
phoneBook[1] = new PhoneEntry("Grace", "Dunbar", "(860) 399-3044");
phoneBook[2] = new PhoneEntry("Paul", "Kratides", "(815) 439-9271");
phoneBook[3] = new PhoneEntry("Violet", "Smith", "(312) 223-1937");
phoneBook[4] = new PhoneEntry("John", "Wood", "(913) 883-2874");
phoneBook[5] = new PhoneEntry("John", "Smith", "(407) 123-4555");
}
// use linear search to find the targetName.
// Return a reference to the matching PhoneEntry
// or null if none is found
public PhoneEntry search(String fName, String lName) {
int i = 0;
if (fName.equals("")) {
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName)) {
resultList[i] = phoneBook[j];
i++;
}
}
}
else {
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName) && phoneBook[j].firstName.equals(fName)) {
resultList[i] = phoneBook[j];
i++;
}
}
}
return null;
}
public void add(String fName, String lName, String phone) {
for (int i = 0; i < phoneBook.length; i++) {
if (phoneBook[i] == null) {
phoneBook[i] = new PhoneEntry(fName, lName, phone);
}
else {
System.out.println("No room in phone book.");
}
}
}
}
Tester:
import java.util.*;
public class PhoneBookTester {
public static void main(String[] args) {
PhoneBook pb = new PhoneBook();
PhoneEntry entry;
// Create a new scanner object
Scanner input = new Scanner(System.in);
String lastName;
String firstName;
do {
// Prompt the user to enter the name
System.out.print("Pleast enter the last name to search: ");
lastName = input.nextLine();
System.out.print("Please enter the first name to search: ");
firstName = input.nextLine();
// search for the person
entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());
// if found, print out the entry
if (entry != null) {
//for(Phonebook eachEntry : pb.search(firstName.toUpperCase(), lastName.toUpperCase())) {
System.out.println(entry.firstName + " " + entry.lastName + ": " + entry.phone);
}
// if user enter quit, then say good bye
else if ("quit".equals(lastName)) {
System.out.println("Good Bye!");
}
// if not found, tell the user
else {
System.out.println("Name not found.");
}
} while (!"quit".equals(lastName));
}
}
PhoneEntry:
public class PhoneEntry {
String firstName; // first name of a person
String lastName; // first name of a person
String phone; // phone number of a person
// constructor
public PhoneEntry(String fName, String lName, String p) {
firstName = fName.toUpperCase();
lastName = lName.toUpperCase();
phone = p;
}
}
Solution
public PhoneEntry search(String fName, String lName) {
// There could be 2 cases.
// 1. There is only LastName == There is no First name
// 2. There are First and Last name; == There is First name
// That means, you can easily handle this problem with checking whether there is first name
int caseNumber = 0; // Default number 0 will return null
if(fName.equals("")) { // if there is no first name
caseNumber = 1;
} else {
caseNumber = 2;
}
PhoneBook[] searchResultList = new PhoneBook[]; // This will be result phonebook
switch(caseNumber) {
case 1:
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName)) {
searchResultList.add(phoneBook[j]);
}
}
return searchResultList;
case 2:
for (int j = 0; j < phoneBook.length; j++) {
if (phoneBook[j].lastName.equals(lName) && phoneBook[j].firstname.equals(fName)) {
searchResultList.add(phoneBook[j]); // This could be mutiple. (There is possible situation that there is two person whose name is same and different phone number)
}
}
return searchResultList;
default:
return null;
}
}
And you can print the answer
for(Phonebook eachBook : pb.search(inputFName, inputLName)) {
System.out.println(eachBook .firstName + " " + eachBook .lastName + ": " + eachBook .phone);
}
I don't know what exactly PhoneBook class is. So, I assume PhoneBook class has 3 variable, firstName, lastName, phone. So, please modify this answer that this codes fit your codes.
=========== Edit :: Add solution ===========
main() class
public static void main(String[] args) {
// Create a new scanner object
Scanner input = new Scanner(System.in);
String lastName;
String firstName;
int variableForCountArray;
do {
PhoneBook pb = new PhoneBook();
PhoneEntry[] entry;
entry = null;
variableForCountArray = 0;
// Prompt the user to enter the name
System.out.print("Pleast enter the last name to search: ");
lastName = input.nextLine();
System.out.print("Please enter the first name to search: ");
firstName = input.nextLine();
// search for the person
entry = pb.search(firstName.toUpperCase(), lastName.toUpperCase());
// if found, print out the entry
if (entry != null) {
for(int i = 0; i < entry.length; i++) {
if(entry[i] != null) { // Could get NullPointerException
variableForCountArray++;
}
}
for(int index = 0; index < variableForCountArray; index++) {
System.out.println(entry[index].firstName + " " + entry[index].lastName + ": " + entry[index].phone);
}
}
// if user enter quit, then say good bye
else if ("quit".equals(lastName)) {
System.out.println("Good Bye!");
}
// if not found, tell the user
else {
System.out.println("Name not found.");
}
} while (!"quit".equals(lastName));
}
PhoneEntry.java // No change
public class PhoneEntry {
String firstName; // first name of a person
String lastName; // last name of a person
String phone; // phone number of a person
// constructor
public PhoneEntry(String fName, String lName, String p) {
firstName = fName.toUpperCase();
lastName = lName.toUpperCase();
phone = p;
}
}
PhoneBook.java
public class PhoneBook {
PhoneEntry[] phoneBook;
PhoneEntry[] resultList = new PhoneEntry[10];
// constructor
public PhoneBook() {
phoneBook = new PhoneEntry[10];
// load the phone book with data
phoneBook[0] = new PhoneEntry("James", "Barclay", "(418) 665-1223");
phoneBook[1] = new PhoneEntry("Grace", "Dunbar", "(860) 399-3044");
phoneBook[2] = new PhoneEntry("Paul", "Kratides", "(815) 439-9271");
phoneBook[3] = new PhoneEntry("Violet", "Smith", "(312) 223-1937");
phoneBook[4] = new PhoneEntry("John", "Wood", "(913) 883-2874");
phoneBook[5] = new PhoneEntry("John", "Smith", "(407) 123-4555");
}
// use linear search to find the targetName.
// Return a reference to the matching PhoneEntry
// or null if none is found
public PhoneEntry[] search(String fName, String lName) {
int i = 0;
if (fName.equals("")) {
for (int j = 0; j < phoneBook.length; j++) {
if(phoneBook[j] != null) {
if (phoneBook[j].lastName.equals(lName)) {
resultList[i] = phoneBook[j];
i++;
}
}
}
} else {
for (int j = 0; j < phoneBook.length; j++) {
if(phoneBook[j] != null) {
if (phoneBook[j].lastName.equals(lName) && phoneBook[j].firstName.equals(fName)) {
resultList[i] = phoneBook[j];
i++;
}
}
}
}
if(i == 0) {
return null;
} else {
return resultList;
}
}
public void add(String fName, String lName, String phone) {
for (int i = 0; i < phoneBook.length; i++) {
if (phoneBook[i] == null) {
phoneBook[i] = new PhoneEntry(fName, lName, phone);
}
else {
System.out.println("No room in phone book.");
}
}
}
}
Print test result
Pleast enter the last name to search: smith
Please enter the first name to search:
VIOLET SMITH: (312) 223-1937
JOHN SMITH: (407) 123-4555
Pleast enter the last name to search: smith
Please enter the first name to search: john
JOHN SMITH: (407) 123-4555
Pleast enter the last name to search: hello
Please enter the first name to search:
Name not found.
Pleast enter the last name to search: quit
Please enter the first name to search:
Good Bye!
Java8 approach.
PhoneEntry class:
public class PhoneEntry {
final String firstName;
final String lastName;
final String phone;
public PhoneEntry(String firstName, String lastName, String phone){
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
}
}
PhoneBook class:
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class PhoneBook {
List<PhoneEntry> contancts = new ArrayList<PhoneEntry>();
public List<PhoneEntry> search(String lastName) {
return contancts.stream()
.filter(phoneEntry ->
phoneEntry.firstName.toLowerCase().equals(lastName.toLowerCase())
|| phoneEntry.lastName.toLowerCase().equals(lastName.toLowerCase()))
.collect(Collectors.toList());
}
public Optional<PhoneEntry> search(String firsName, String lastName){
return contancts.stream()
.filter(phoneEntry ->
phoneEntry.firstName.toLowerCase().equals(firsName.toLowerCase())
&& phoneEntry.lastName.toLowerCase().equals(lastName.toLowerCase()))
.findFirst();
}
}
Test class:
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
PhoneBook phoneBook = new PhoneBook();
phoneBook.contancts.add(new PhoneEntry("John","Xavier","(992)-30421-323"));
phoneBook.contancts.add(new PhoneEntry("Mary","Doser","(992)-30421-353"));
phoneBook.contancts.add(new PhoneEntry("George","Sesame","(990)-30421-353"));
phoneBook.contancts.add(new PhoneEntry("Liam","Xavier","(990)-30211-353"));
Scanner input = new Scanner(System.in);
String lastName;
String firstName;
do {
// Prompt the user to enter the name
System.out.print("Pleast enter the last name to search: ");
lastName = input.nextLine();
System.out.print("Please enter the first name to search: ");
firstName = input.nextLine();
// search for the person
Optional<PhoneEntry> entry = phoneBook.search(firstName, lastName);
List<PhoneEntry> entries = phoneBook.search(lastName);
// if found, print out the entry
if (entry.isPresent() && firstName.length() !=0) {
System.out.println(entry.get().firstName + " " + entry.get().lastName + ": " + entry.get().phone);
}else if(firstName.length() == 0 && entries.size() !=0 ){
entries.forEach(e -> System.out.println(e.firstName + " " + e.lastName + ": " + e.phone));
}
// if user enter quit, then say good bye
else if ("quit".equals(lastName)) {
System.out.println("Good Bye!");
}
// if not found, tell the user
else {
System.out.println("Name not found.");
}
} while (!"quit".equals(lastName));
}
}

ArrayList not returning expected data

I don't know what I'm doing and would appreciate any help.
I'm reading a text file with the following code:
7
10 416-555-6667 Burgess Smith 15
15 905-777-8888 Thomas Patel 10
20 905-111-2222 Morris J. Stevenson 5
25 416-222-3333 Spencer Larson 30
30 416-333-4444 Adams Doe 18
35 905-122-5454 Price Hanks 15
40 905-343-5151 Clement L. Webster 8
private static void fileReader() throws FileNotFoundException
{
int eId = 0;
String nme = "";
String phne = "";
int yrs = 0;
String line ="";
Employee emp = new Employee(eId, nme, phne, yrs);
File inputfile = new File("Emp.txt");
Scanner in = new Scanner(inputfile);
n = in.nextInt() - 1;
in.nextLine();
in.useDelimiter("");
for (int i=0;i<=n;i++)
{
int l = 0;
int m = 0;
int n = 0;
line = in.nextLine();
while (Character.isDigit(line.charAt(l)))
{
l++;
}
m = l + 1;
while (!Character.isLetter(line.charAt(m)) && !Character.isWhitespace(line.charAt(m)))
{
m++;
}
n = m + 1;
while (!Character.isDigit(line.charAt(n)))
{
n++;
}
eId = Integer.parseInt(line.substring(0, l));
emp.setEmpId(eId);
phne = line.substring(l + 1, m - 1);
emp.setTelephone(phne);
nme = line.substring(m + 1, n - 1);
emp.setName(nme);
yrs = Integer.parseInt(line.substring(n));
emp.setYears(yrs);
empArr.add(i, emp);
}
in.close();
}
class for set and get methods:
public class Employee
{
private int empId;
private String telephone;
private String name;
private int yearsOfWork;
public Employee(int id, String name, String telephone, int yearsOfWork)
{
empId = id;
this.telephone = telephone;
this.name = name;
this.yearsOfWork = yearsOfWork;
}
public void setEmpId(int id)
{
empId = id;
}
public void setName(String name)
{
this.name = name;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public void setYears(int years)
{
yearsOfWork = years;
}
public int getEmpId()
{
return empId;
}
public String getName()
{
return name;
}
public String getTelephone()
{
return telephone;
}
public int getYears()
{
return yearsOfWork;
}
public String toString()
{
return "ID:" + empId + ", name: " + name + ", phone: " + telephone + ", years of work: " + yearsOfWork + "\n";
}
}
When I call the get method of my ArrayList outside of its for loop, the text at each index is overwritten by the text at the last index.
I think I'm missing some fundamental concept of constructors and objects here.
Any help is appreciated. Thanks.
Your hunch is correct, you are missing the emp object creation. You have to move the emp object creation into the loop.
Your Employee class and getter/setter methods are correctly written.
Rewrite your fileReader() method similar to given below : -
String line ="";
//Declare an Arraylist for an Employee
List<Employee> employee = new ArrayList<Employee>();
//Read a file
File inputfile = new File("Emp.txt file path");
Scanner in = new Scanner(inputfile);
//Reading a number from a first sentence
int n = Integer.parseInt(in.nextLine());
for (int i=0;i<n;i++) {
// Reading each sentence
line = in.nextLine();
//Parse an Emp id
int eId = Integer.parseInt(line.substring(0, 2));
//Parse a phone number
String phone = line.substring(3, 14);
//Parse a name
String name = line.split("\\d+")[4];
//Parse years
int years = Integer.parseInt(line.split("\\D+")[4]);
//Now create an object by putting all above values in a constructor
Employee emp1 = new Employee(eId, name, phone, years);
//Add that object in an arraylist
employee.add(emp1);
}
//As you have overridden toString method, print an arraylist
System.out.println(emp.toString());
//Closing the scanner
in.close();
}
Hope this helps.

I don't know where my String index out of range: 0 error is coming from

I'm trying to take data out of a txt file and create comparable objects out of the data and add them to an array. After that array is created, I want to make a 2d array that stores a 1 in a slot if two options meet the requirements. I keep getting a String index out of range: 0 error though and I do not know where it comes from.
import java.util.*;
import java.io.*;
public class CourseScheduler
{
public int numberOfCourses;
public int[][] adjacent;
public Course[] courses;
public CourseScheduler(String filename)
{
File file = new File(filename);
try{
Scanner scan = new Scanner(file);
numberOfCourses = scan.nextInt();
courses = new Course[numberOfCourses];
adjacent = new int[numberOfCourses][numberOfCourses];
scan.useDelimiter(",|\\n");
for(int i = 0; i < numberOfCourses;i ++){
if(scan.hasNext()){
String dept = scan.next();
String num = scan.next();
String building = scan.next();
String room = scan.next();
String instruct = scan.next();
courses[i] = new Course(dept, num, building, room, instruct);
}
}
}
catch(FileNotFoundException ex){
System.out.println("File was not found");
}
for(int x = 0;x<numberOfCourses;x++){
for(int y = 0;y<numberOfCourses;y++){
adjacent[x][y] = (courses[x].compare(courses[y]));
}
}
}
This is the code for the main class
public class Course{
String department;
String courseNum;
String buildingCode;
String roomCode;
String instructorName;
public Course(String dept, String number, String building, String room, String instructor){
department = dept;
courseNum = number;
buildingCode = building;
roomCode = room;
instructorName = instructor;
}
public String getDept(){
return department;
}
public String getCourse(){
return courseNum;
}
public String getBuilding(){
return buildingCode;
}
public String getRoom(){
return roomCode;
}
public String getInstructor(){
return instructorName;
}
public String toString(){
return department + ";" + courseNum + ";" + buildingCode + ";" + roomCode + ";" + instructorName;
}
public int compare(Course comp){
int ans = 1;
String compNum = comp.getCourse();
if(instructorName == comp.getInstructor())
ans = 0;
if(buildingCode == comp.getBuilding()){
if(roomCode == comp.getRoom())
ans = 0;
}
if(department == comp.getDept()){
if(courseNum.charAt(0) == compNum.charAt(0))
ans = 0;
}
return ans;
}
}
this is the code for the course class
Educated guess: Most likely your error is coming from this line:
if(courseNum.charAt(0) == compNum.charAt(0))
ans = 0;
Either courseNum or compNum are empty.
I did not try to compile and run it but its seems that the exception comes from this line
if(courseNum.charAt(0) == compNum.charAt(0))
If a string is empty, charAt(0) will throw exactly the given exception.
Tip: if you don't know how to use a debugger, use the old fashioned System.out.println(). Put println() here and there in your code to understand how it works.

BST program error

The following code should produce a program that allows one to search for people in an address book, but I'm having some issues with the following lines of code marked. I don't think I'm missing a class...This is odd.
I'm fairly new in java so I apologize if this is basic.
Apparently BinarySearchTree can't be resolved to a type
import java.util.Scanner;
import java.io.*;
public class useBinarySearchTree
{
public static void main (String[] args)
{
BinarySearchTee<AddrEntry> addrbook = new BinarySearchTree<AddrEntry>();// error exists here
AddrEntry inentry, tentry;
String nameLook;
Scanner keybd = new Scanner(System.in);
String again;
final int INORDER = 1;
int numentries;
int i;
int ok;
// create address book from input file
buildAddrBook(addrbook);
do
{
// prompt user for name to look up
System.out.println("Address/Phone Lookup:\n" + "Enter name: ");
nameLook = keybd.nextLine();
inentry = new AddrEntry(nameLook, null, null, null);
tentry = addrbook.get(inentry);
if (tentry != null)
{
// print the address book entry
System.out.println("\nAddress Book Entry\n");
System.out.println("__________________\n");
System.out.println(tentry);
System.out.println();
}
else
{
// if the person is not in the book, see if they should be added
System.out.println("\n" + nameLook + " not found in address book\n");
System.out.println("\nWould you like to add this person? [y or n] => ");
again = keybd.nextLine();
System.out.println(again);
if (again.equals("Y") || again.equals("y"))
addEntry(addrbook, keybd);
}
System.out.println("\nAnother Lookup? [y or n] => ");
again = keybd.nextLine();
}
while (again.equals("Y") || again.equals("y"));
// prompt the user to see if they want to see the entire address book before exiting
System.out.println("\nPrint the address book? [y or n] => ");
again = keybd.nextLine();
if (again.equals("Y") || again.equals("y"))
{
System.out.println();
numentries = addrbook.reset(INORDER);
for (i = 1; i <= numentries; i++)
{
tentry = addrbook.getNext(INORDER);
System.out.println(tentry);
}
}
}
// read entries from file and insert them into the address book
public static void buildAddrBook (BinarySearchTree<AddrEntry> addrbook)// here as well {
AddrEntry hold;
String name;
String street;
String town;
String phone;
int ok = 1;
try
{
FileReader freader = new FileReader("addrbook.dat");
BufferedReader addresses = new BufferedReader(freader);
name = addresses.readLine();
while (name != null)
{
street = addresses.readLine();
town = addresses.readLine();
phone = addresses.readLine();
hold = new AddrEntry(name, street, town, phone);
addrbook.add(hold);
name = addresses.readLine();
}
}
catch(
Exception e
)
{
}
}
// add a new entry to the address book
public static void addEntry (BinarySearchTree<AddrEntry> addrbook, Scanner keybd)//also here {
int ok;
AddrEntry hold;
String name;
String street;
String town;
String phone;
System.out.println("\nEnter name: ");
name=keybd.nextLine();
System.out.println("Enter street address: ");
street=keybd.nextLine();
System.out.println("Enter town, state, and zip: ");
town=keybd.nextLine();
System.out.println("Enter phone number: ");
phone=keybd.nextLine();
hold=new
AddrEntry (name, street, town, phone);
addrbook.add(hold);
}
AddrEntry class
public class AddrEntry implements Comparable<AddrEntry> {
private String name;
private String street;
private String town;
private String phone;
public AddrEntry() {}
public AddrEntry(String nn, String st, String tt, String ph) {
name = nn;
street = st;
town = tt;
phone = ph;
}
public void setEntry(String nn, String st, String tt, String ph) {
name = nn;
street = st;
town = tt;
phone = ph;
}
public String toString() {
return name + "\n" + street + "\n" + town + "\n" + phone;
}
public boolean equals(Object ptest) {
if (ptest == null || !(ptest instanceof AddrEntry))
return false;
return this.name.equals(((AddrEntry)ptest).name) &&
this.street.equals(((AddrEntry)ptest).street) &&
this.town.equals(((AddrEntry)ptest).town) &&
this.phone.equals(((AddrEntry)ptest).phone);
}
public int compareTo(AddrEntry ent) {
return name.compareTo(ent.name);
}
}

Categories

Resources