How to get a text file in a one dimensional array - java

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;
}

Related

How can I declare an array in one function and use that same array in another function?

Here is my code
class Employee{
private String Animal;
private int Quantity;
Employee(String Animal, int Quantity){
this.Animal=Animal;
this.Quantity=Quantity;
public String getAnimal{
return animal;
}
public void setAnimal{
this.Animal=Animal;
}
public String getQuantity{
return Quantity;
}
public void setQuantity{
this.Quantity=Quantity;
}
public static void Input(){
Scanner sc = new Scanner(System.in);
int n = 0;
Employee[] list = new Employee[20];
list[no] = new Employee(" ", 0);
String nameOfAnimal = sc.nextLine();
list[n].setAnimal(nameOfAnimal);
String numberOfAnimal = sc.nextLine();
list[n].setQuantity(numberOfAnimal);
++n;
}
public static void Output(){
...
for(int i=0; i<n; ++i){
System.out.println(" -" + list[i].getAnimal + " - " + list[i].getQuantity);
}
}
}
In the Output method, I dot 3 points because I don't know how to get the array declared in the Input method and print its content within the Output method. It always shows an error that the first element is null when I create the same array in the Output function. Concisely, how can I keep an array that both functions can be used?

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.

array of string in java

I want to solve this problem without using arraylist.
i want to add the contact to its specific index in the array of strings. And then display all the added contacts in string format seperated by commas.
My code gives the result of only last added contract:
Contact [first=Bob, last=Moore, number=555-9756]
where is the problem in my code?
Is there any idea how to solve???
This class consist of the main method:
This is the main class:
public class ExampleApp {
public static void main(String[] args) {
PhoneBook pb = new PhoneBook("Personal book");
System.out.println( pb.getName() );
pb.add("Alice", "Green", "555-1234");
pb.add("Mary", "Smith", "555-6784");
pb.add("Bob", "Moore", "555-9756");
System.out.println( pb.toString() );// here i want to display all the contracts seperated by commas
System.out.println( pb.first() );// first contract
System.out.println( pb.get(2) );// second contract
String toBeFound = new String("Moore");
System.out.println( pb.find(toBeFound) );// display the found contract
}
}
This is the phonebook class:
public class PhoneBook {
public static final int MAX = 10;
public String name;
String[] contracts = new String[MAX]; // i created an array of strings
Contact c;
/**
* Create a new phonebook with given name
*/
public PhoneBook(String name) {
this.name = name;
}
/**
* Return the phonebook name
*/
public String getName() {
return name;
}
/**
* Insert a new contact at the end
*/
public void add(String first, String last, String number){
c=new Contact(first,last,number);
for(int i=0;i<MAX;i++){ // i added for each array index the contracts strings
contracts[i]= c.toString();
}
}
/**
* Return the first contact
*/
public String first() {
return get(1);
}
/**
* Return the i-th contact (supposing that first
* index is 1)
*/
public String get(int i) {
String s =contracts[i].toString();
return s;
}
/**
* Return a string containing the list of textual
* representation of all contacts, separated by ", ".
* List starts with "("and ends with ")"
*/
public String toString() {
String s= " ";
for(int i=1;i<MAX;i++){ // here i tried to display the string looping the array
s=contracts[i].toString();
}
return s;
}
/**
* Return the textual representation of first
* contact containing "needle"
*/
public String find(String needle) {
//TODO: to be implemented
return null;
}
}
This is the contact class :
public class Contact {
public String first;
public String last;
public String number;
public String[] contacts;
public Contact(String first, String last, String number) {
this.first=first;
this.last = last;
this.number=number;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
#Override
public String toString() {
return "Contact [first=" + first + ", last=" + last + ", number="
+ number + "]";
}
}
You can use ArrayList for it. It will help you really much and you should make your veriables private.
private String first;
private String last;
private String number;
private ArrayList<String> list = new ArrayList<String>();
for(String pointer : list){
}
or you can make contact saver ArrayList
private ArrayList<Contact> list = new ArrayList<Contact>();
public Contact(String first, String last, String number) {
this.first=first;
this.last = last;
this.number=number;
}
public void add(String first, String last, String number){
c=new Contact(first,last,number);
list.add(c);
}
and you can access all veriables like that list.get(i).first.
You can save your contact class and contracts array in arraylist and it will give you more power to access. If you want to display your ArrayList, which index is not important, you need only ++i for it.
I changed your class look this:
public class PhoneBook {
public static final int MAX = 10;
public String name;
String[] contracts = new String[MAX]; // i created an array of strings
Contact c;
private int count = 0;// saved last index of array
public PhoneBook(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void add(String first, String last, String number) {
c = new Contact(first, last, number);
contracts[count] = c.toString(); // save your String inside of last index++
count++;
}
public String first() {
return get(1);
}
public String get(int i) {
String s = contracts[i].toString();
return s;
}
public String toString() {
for (int i = 0; i < MAX; i++) {
if (contracts[i] != null)
System.out.println(contracts[i].toString());
}
return "";
}
public String find(String needle) {
return null;
}
}
public class Contact {
public String first;
public String last;
public String number;
public Contact(String first, String last, String number) {
this.first = first;
this.last = last;
this.number = number;
}
#Override
public String toString() {
return "Contact [first=" + first + ", last=" + last + ", number="
+ number + "]";
}
}
//Personal book
//Contact [first=Alice, last=Green, number=555-1234]
//Contact[first=Mary, last=Smith, number=555-6784]
//Contact [first=Bob, last=Moore, number=555-9756]
you always delete your last toString method. Your Add method is wrong. You always turn 0 and write again inside of array.
You should keep track of the last contact added to your array :
private int lastIndex = 0; // index of first available index of the array
...
/**
* Insert a new contact at the end
*/
public void add(String first, String last, String number){
c=new Contact(first,last,number);
if (lastIndex < MAX)
contracts[lastIndex++]= c.toString();
}
Some other issues with your code :
/**
* Return the first contact
*/
public String first() {
return get(1); // should be get(0)
}
Calling toString() for contracts[i] is redundant, since it's already a String. Perhaps you meant to store Contact instances instead of Strings in your array? That would make more sense.
Add an extra variable static int Last = 0; To track how many contact you have added and update the add function as .
public void add(String first, String last, String number){
if(Last>=MAX){
System.out.println("Error in adding\n");
}
else{
c=new Contact(first,last,number);
contacts[Last] = c.toString();
Last++;
}
}
Change Tostring() for loop to last. So that you will be printing only added contact .In your case you are printing upto MAX that is wrong when less no of contacts are added.
You have to pass i=0,1,2,...,MAX-1 to get(i) function . Array is Zero(0) based indexed.
So, the problem you are having is that you always retrieve the last contact, regardless of which one you try to get. This is because when you add a new contact, you are actually replacing ALL the contacts, making them all the same. You are getting the correct contact from the phonebook, but they ALL have the same value.
To fix it, do the following:
public class PhoneBook
{
int contactsAdded = 0; // Add an integer to store how many contacts you have added
Contact[] contacts = new Contact[MAX]; //Change this to Contact array, not string
//Contact c; //You can remove this line
//Rest of your code
}
public void add(String first, String last, String number)
{
//Only add if the number of contacts is less than the max
if (contactsAdded < MAX)
{
//Construct the new contact when you use it.
contacts[contactsAdded] = new Contact(first, last, number);
contactsAdded++;
}
}
Not sure if I understood all of your code right, but I think you are overwriting all other contacts in your phone book:
public void add(String first, String last, String number){
c=new Contact(first,last,number); //(1)
for(int i=0;i<MAX;i++){ //(2)
contracts[i]= c.toString();
}
}
At position (1) a new Contact object is created and assigned to c. In the next step (2), you loop through the array and assign the info contained in c (the latest contact added) to all already entries in the contracts array.
Independent from your problem, I suggest that you replace the array of a fixed size with i.e. an ArrayList of type Contact. Adding entries to this list, iterating, sorting etc is very easy.

How to read int,text and double from a file and store it into an arraylist?

What I am trying to do is read a text file which has this lines
232131231, random name, 23.3232
I only know how to read it as a String of the whole line. I don't know how to read them individually. This is my test codes.
main
public class JavaApplication9
{
int value1;
String value2;
double value3;
ArrayList<String> toBeSplit = new ArrayList();
String[] split;
ArrayList <Inventory> productList = new ArrayList<> ();
public long ReadFile(String sfile) throws IOException
{
int x = 0;
File inFile = new File(sfile);
BufferedReader reader = new BufferedReader(new FileReader(inFile));
String sline = null;
while ((sline=reader.readLine()) != null)
{
toBeSplit.add(x,sline);
x++;
}
reader.close();
return inFile.length();
}
public void splitString ()
{
int a = 0;
while (a<toBeSplit.size())
{
split = toBeSplit.get(a).split(",");
value1 = Integer.parseInt(split[0]);
value2 = split[1];
value3 = Double.parseDouble(split[2]);
productList.add(new Inventory (value1,value2,value3));
a++;
}
}
public void OutputLines ()
{
for (Inventory e : productList)
{
System.out.println (e.getBarcode() +"\t"+ e.getName()+"\t"+ e.getPrice());
}
}
public static void main(String[] args)
{
try
{
JavaApplication9 instance = new JavaApplication9 ();
instance.ReadFile("Products (1).csv");
instance.splitString();
instance.OutputLines();
}
catch (IOException e)
{
System.out.print ("Error");
}
}
}
and my Inventory class
public class Inventory
{
int barcode;
String name;
double price;
public Inventory (int bars,String pname,double prices)
{
barcode = bars;
name = pname;
price = prices;
}
public int getBarcode ()
{
return barcode;
}
public String getName ()
{
return name;
}
public double getPrice ()
{
return price;
}
}
Use split(String regex) to split the string. (See the javadocs for split())
Then you can individually parse each value in the way you want it.
Here is an example using your data:
String toBeSplit = "232131231, random name, 23.3232";
String[] split = toBeSplit.split(",");
int value1 = Integer.parseint(split[0].trim());
String value2 = split[1].trim();
double value3 = Double.parseDouble(split[2].trim());
I use trim() (See the javadocs for trim()) to get rid of the white space left behind after splitting.
Here's another way to do it without trim(): (Just add a space inside the split regex)
String toBeSplit = "232131231, random name, 23.3232";
String[] split = toBeSplit.split(", ");
int value1 = Integer.parseint(split[0]);
String value2 = split[1];
double value3 = Double.parseDouble(split[2]);
You can use split(String regex) for this.
Consider this simple example :
String mystr = "232131231, random name, 23.3232";
List<String> list = Arrays.asList(mystr.split(", "));
for(String str : list){
System.out.println(str);
}
Output :
232131231
random name
23.3232
If you wanted to get list as ArrayList particularly, you can use ArrayList(Collection list) version of ArrayList.
ArrayList list = new ArrayList(Arrays.asList(mystr.split(", ")));

bubble sorting an array of a class

I wrote a program that is supposed to read in records from a file and enter them into an array of a Student class. I then need to sort them by name.
import java.io.*;
import java.util.Scanner;
public class StudentTest
{
public static void main(String[] args)
{
String name;
String address;
String major;
double gpa;
int classLevel;
int college;
String blank;
String idNumber;
Scanner fileIn = null;
try
{
fileIn = new Scanner (new FileInputStream("student.dat"));
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
System.exit(0);
}
Student[] aStudent = new Student[15];
int index = 0;
for (index=0; index <= 15; index++)
{
while (fileIn.hasNext())
{
name = fileIn.nextLine();
address = fileIn.nextLine();
major = fileIn.nextLine();
gpa = fileIn.nextDouble();
classLevel = fileIn.nextInt();
college = fileIn.nextInt();
fileIn.nextLine();
idNumber = fileIn.nextLine();
aStudent[index] = new Student(name, address, major, gpa, classLevel, college, idNumber);
aStudent[index].Display();
}
}
Student temp = null;
for (int pass = 0; pass < (index-1); pass++)
{
for (int c = 0; c < (index - 1); c++)
{
if (aStudent[].getName() > aStudent[c+1].getName())
{
temp = aStudent[];
aStudent[]=aStudent[+1];
aStudent[+1]=temp;
}
}
}
}
}
import java.util.Scanner;
public class Student
{
private String name;
private String address;
private String major;
private double gpa;
private int classLevel;
private int college;
private String idNumber;
Scanner keyboard = new Scanner(System.in);
public Student(String name, String address, String major, double gpa, int classLevel, int coll, String idNum)
{
this.name = name;
this.address = address;
this.gpa = gpa;
this.major = major;
this.classLevel = classLevel;
this.college = coll;
this.idNumber = idNum;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public String getMajor()
{
return major;
}
public double getGPA()
{
return gpa;
}
public int getClassLevel()
{
return classLevel;
}
public int getCollege()
{
return college;
}
public String getID()
{
return idNumber;
}
public void setAddress(String address)
{
}
public void setMajor(String maj)
{
}
public void setCollege(int coll)
{
}
public void Display()
{
System.out.println("Name: "+getName());
System.out.println("Address: "+getAddress());
System.out.println("Major: " + getMajor());
System.out.println("GPA: "+getGPA()+" Class Level: "+getClassLevel()+" College: "+getCollege());
System.out.println("ID: "+getID());
System.out.println("===============================");
}
}
I wrote the sort the way my proffessor described it in class, but I am still getting errors that "the > operator is undefined for the argument type(s) java.laungage.String"
Any help would be greatly appreciated.
thanks
Edit:
I used Ashan's suggestion and now it looks like this.
for (int pass = 0; pass < (index-1); pass++)
{
for (int c = 0; c < (index - 1); c++)
{
if (aStudent[c].getName().compareTo(aStudent[c+1].getName()) > 0)
{
temp = aStudent[c];
aStudent[c]=aStudent[+1];
aStudent[+1]=temp;
That cleared up that error. However, I am now getting a NullPointerException.
You cannot compare strings using operator such as < , > . To compare strings there is a methodd provided in String class called compareTo. This method compares two strings lexicographically.
compareTo returns
0 incase both the strings are lexicographically equal
-1 if the calling string is lexicographically smaller than the input string
1 if the calling string is lexicographically larger than the input stirng
You can replace the following condition
if (aStudent[].getName() > aStudent[c+1].getName())
using compareTo method as:
if (aStudent[].getName().compareTo(aStudent[c+1].getName()) > 0)
I think error is because you cannot compare how big is the name or how small it is. Making a bubble search to sort names by alphabetical order, you need to check their first characters ASCII. Which is a pretty easy thing to do. I am not good at Java, but C++. So algorithms are same ;) Good luck ;)
You may want to use compareTo() of String. > and < are used for int, float numbers, characters and etc., not for objects like strings. If objects support compare operations, it must implement the Comparable interface, in which you will define the compareTo() method.
This method will return -1 if it is less than the other, 0 if they are equal and 1 if it is greater than the other object.

Categories

Resources