For this code I am supposed to read in a file and make it into an ArrayList. I keep getting half of my ArrayList, and the other half comes up as what I declared the variable to be.
The code is supposed to be running through another class, which is extended.
public static void inputDoctorRecords(ArrayList<Person> doc) throws FileNotFoundException {
//opening file
Scanner console = new Scanner(new File("Doctor.dat"));
Doctor dr;
String lastName = null;
String firstName = null;
String Street = null;
String City = null;
String State = null;
String Zip = null;
int Ident = 0;
String loc = null;
double sal = 0.0;
String Spec = null;
boolean done = true;
boolean fin = true;
String sys = null;
while(console.hasNext() ){
String names = console.next();
dr = new Doctor(lastName, firstName, Street,State, City, Zip, Ident, loc, sal, Spec);
if (names.equals("LName")){
lastName = console.next();
}
if(names.equals("FName")){
firstName = console.next();
}
if (names.equals("Street")){
Street = console.nextLine();
}
if (names.equals("City")){
City = console.nextLine();
}
if (names.equals("State")){
State = console.next();
}
if (names.equals("Zip")){
Zip = console.next();
}
if (names.equals("Ident")){
Ident = console.nextInt();
}
if (names.equals("Loc")){ //returns null
loc = console.next();
}
if (names.equals("Salary")){ // returns 0.0
sal = console.nextDouble();
}
if (names.equals("Spec")){ // returns null
Spec = console.next();
}
if (names.equals("next")){ // goes to the next person in file
doc.remove(dr);
doc.add(dr);
}
}
dr = new Doctor(lastName, firstName, Street,State, City, Zip, Ident, loc, sal, Spec);
doc.remove(dr);
doc.add( dr);
System.out.println( doc);
}
// here is the input file
LName Builder
FName Robert
DOByy 1985
DOBmm 12
DOBdd 31
Ident 123456
Loc Seattle
Spec Cardiology
Salary 100000.0
Street 123 Mockingjay
City Sector 12
State WA
Zip 98058
next
LName Builder
FName Roberta
DOByy 1988
DOBmm 11
DOBdd 22
Ident 234567
Loc Fife
Spec Oncology
Salary 120000.0
Street 123 Mockingjay
City Sector 12
State WA
Zip 98058
next
LName Klein
DOByy 1974
DOBdd 06
Loc Tacoma
Street 59 West Rodeo Drive
Ident 345678
City Hollywood
DOBmm 05
State CA
FName Calvin
Zip 90210
Spec Dermatology
Salary 150000.0
eof
Try with this
public static void inputDoctorRecords(ArrayList<Person> doc) throws FileNotFoundException {
//opening file
Scanner console = new Scanner(new File("Doctor.dat"));
Doctor dr;
String lastName = null;
String firstName = null;
String Street = null;
String City = null;
String State = null;
String Zip = null;
int Ident = 0;
String loc = null;
double sal = 0.0;
String Spec = null;
boolean done = true;
boolean fin = true;
String sys = null;
while(console.hasNext() ) {
String names = console.next();
if (names.equals("LName")) {
lastName = console.next();
}
else if(names.equals("FName")) {
firstName = console.next();
}
else if (names.equals("Street")) {
Street = console.nextLine();
}
else if (names.equals("City")) {
City = console.nextLine();
}
else if (names.equals("State")) {
State = console.next();
}
else if (names.equals("Zip")) {
Zip = console.next();
}
else if (names.equals("Ident")) {
Ident = console.nextInt();
}
else if (names.equals("Loc")) {
loc = console.next();
}
else if (names.equals("Salary")) {
sal = console.nextDouble();
}
else if (names.equals("Spec")) {
Spec = console.next();
}
else if (names.equals("next")) { // goes to the next person in file
dr = new Doctor(lastName, firstName, Street,State, City, Zip, Ident, loc, sal, Spec);
doc.add(dr);
}
else {
console.nextLine(); // ignore the line because it is unknown
}
}
// Last Line
dr = new Doctor(lastName, firstName, Street,State, City, Zip, Ident, loc, sal, Spec);
doc.add(dr);
System.out.println(doc);
}
Hope this helps
The Scanner reads from InputStreams line by line, when you say for example Zip = console.next();, it discards everything it got from the current line. I recommend splitting the String using String#split().
EDIT: Scanner#next() consumes the string. Thats the word I was looking for.
Related
i've been trying to search how do I separate the variable name and content in the txt file and store each in the variable of the object but I can't seem to find one. The code below works only if I don't add the variable names so I'm wondering how can I split it so that I can assign the content of the file to the object.
subjects.txt
id=1 name=biology instructor=John Smith room=2
Java file
public class Subject {
Integer id;
String name;
String instructor;
Integer room;
public void importSubject() throws IOException{
//gets data from file and places it into variable
File list = new File("subjects.txt");
Scanner reader = new Scanner(list);
while (reader.hasNextLine()) {
String [] data = reader.newLine.split("=");
this.id = Integer.parseInt(data[0]);
this.name = data[1];
this.instructor = data[2];
this.room = Integer.parseInt(data[3]);
}
}
}
Assuming the contents of the file always go in the order of "id", "name", "instructor", "room", one way to do this is to use a custom delimiter for the scanner:
Scanner reader = new Scanner(list);
reader.useDelimiter("\\s*(id|name|instructor|room)=");
id=, name=, instructor= and room= (including leading spaces) all match the delimiter pattern \s*(id|name|instructor|room)=, so the scanner will only give us the tokens in between those delimiters, which are:
1
biology
John Smith
2
exactly the things you want.
So you would do:
if (reader.hasNextLine()) {
this.id = reader.nextInt();
this.name = reader.next();
this.instructor = reader.next();
this.room = reader.nextInt();
}
I'm not sure why you are using a loop - you only have one set of fields to initialise. If there are multiple lines in the file and you want to create a Subject for each line, you'd create a ArrayList<Subject>:
public static List<Subject> readSubjects() throws IOException {
File list = new File("subjects.txt");
Scanner reader = new Scanner(list);
ArrayList<Subject> list = new ArrayList<>();
while (reader.hasNextLine()) {
Subject newSubject = new Subject();
newSubject.id = reader.nextInt();
newSubject.name = reader.next();
newSubject.instructor = reader.next();
newSubject.room = reader.nextInt();
list.add(newSubject);
}
return list;
}
The idea is that after you after split by = you get a part. And you have to split that part by " ", the last part is the key of the next = part, and before that is the value of the previous = split part.
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) throws Exception {
Subject subject = new Subject();
subject.importSubject();
System.out.println(subject);
}
}
class Subject {
Integer id;
String name;
String instructor;
Integer room;
public void importSubject() throws IOException {
//gets data from file and places it into variable
File list = new File("subjects.txt");
Scanner reader = new Scanner(list);
while (reader.hasNextLine()) {
// biology instructor --- John Smith room
String[] stringBetweenEqualsSign = reader.nextLine().split("=");
String[] afterId = stringBetweenEqualsSign[1].split(" ");
this.id = Integer.parseInt(String.join(" ", Arrays.copyOf(afterId, afterId.length - 1)));
String[] afterName = stringBetweenEqualsSign[2].split(" ");
this.name = String.join(" ", Arrays.copyOf(afterName, afterName.length - 1));
String[] afterInstructor = stringBetweenEqualsSign[3].split(" ");
this.instructor = String.join(" ", Arrays.copyOf(afterInstructor, afterInstructor.length - 1));
this.room = Integer.parseInt(stringBetweenEqualsSign[4]);
}
}
#Override
public String toString() {
return "Subject{" +
"id=" + id +
", name='" + name + '\'' +
", instructor='" + instructor + '\'' +
", room=" + room +
'}';
}
}
I have a text file called UserDetails.txt that I am trying to read from.
Each line of the text file is as follows:
John : Doe : Seattle : jd3 : 1234
Jane : Doe : Olympia : jd4 : 5678
In which the last two variables are the username and password that I am trying to search for.
My code:
public class LoginFrame extends javax.swing.JFrame
{
private static Scanner keyboard = new
Scanner(System.in);
String username;
String password;
String filePath = "UserDetails.txt";
public LoginFrame() {
initComponents();
}
private void jButtonLoginActionPerformed(java.awt.event.ActionEvent evt) {
username = jTextFieldUsername.getText();
password = jTextFieldPassword.getText();
verifyLogin(username,password,filePath);
}
public static void verifyLogin(String username,
String password, String filepath)
{
boolean match = false;
String tempUserName = "";
String tempPassword = "";
try
{
keyboard = new Scanner(new
File(filepath));
keyboard.useDelimiter("[:\n]");
while(keyboard.hasNext() && !match)
{
tempUserName = keyboard.next();
tempPassword = keyboard.next();
if(tempUserName.trim().equals(username.trim()) && tempPassword.trim().equals(password.trim()))
{
match = true;
}
}
keyboard.close();
System.out.print(match);
}
catch (Exception e)
{
System.out.print("Error");
}
}
The problem that I am encountering is that I am unsure as to how I can separate the username and password from the user's first and last name. The use of the delimiter is only able to find these two specific values when the username and password are the only two variables in the text file(with the first and last names removed).
read the entire line and then you can use
String str = "John : Doe : Seattle : jd3 : 1234"; // input line that you read from file
String[] arr = str.split(" : ");
String username = arr[3]; // as index starts from 0;
String password = arr[4]; // similarly you can get other values
to convert it in a array of String that will have the username at index 3
and password at index 4
I'm writing an adres directly from my code to a file with filewriter and those values are stored on one line in the file example(street 264, Washington). Now I want to write that adres to a new Arraylist with a constructor that asks for three input values(street, number, city)
I have accomplished it this way but when I input a street like "Park Avenue" it gives an error as Park avenue is two words... also wondering if there is a faster "better" way:
#Override
public List<Adres> query(ISpecification specification) {
File adresConnection = new File(fsConnection.getAdresConnection());
if (specification instanceof FileSpecification) {
if (((FileSpecification) specification).toFileQuery().equals("ALL")) {
ArrayList<Adres> adressen = new ArrayList<>();
try (
Scanner input = new Scanner(adresConnection)) {
System.out.println("Adressen laden wordt uitgevoerd");
while (input.hasNext()) {
String straat = input.next();
String huisNrMetKomma = input.next();
int huisNummer = Integer.parseInt(huisNrMetKomma.substring(0, huisNrMetKomma.length() - 1));
String plaats = input.next();
adressen.add(new Adres(straat, huisNummer, plaats));
}
nextLine reads multiple words so try using nextLine(); instead of next();
while (input.hasNext()) {
String straat = input.nextLine();
String huisNrMetKomma = input.nextLine();
int huisNummer = Integer.parseInt(huisNrMetKomma.substring(0, huisNrMetKomma.length() - 1));
String plaats = input.nextLine();
adressen.add(new Adres(straat, huisNummer, plaats));
}
So essentially what I need to do is make this while loop run through the txt file and store it in an array to be stored inside the instance variables
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* <insert class description here>
*
* #author Chris Crosby
*
*/
public class TrackInput
{
private Scanner keyboard = new Scanner(System.in);
public int readTrackData(Railroad[] Reservations) {
final String FILE_NAME = "TrackData.txt";
int size =0;
Scanner input = null;
try {
input= new Scanner(new File(FILE_NAME));
}
catch(FileNotFoundException e) {
System.out.println("Unable to open file " + FILE_NAME + ".");
}
String passengerName="";
String routeNumber="";
String departureDate="";
String departureTrack="";
String arrivalTrack="";
String departureTime="";
String arrivalTime="";
String seat="";
String returnRouteNumber="";
String ReturnDate="";
while (input.hasNext()&& size<Reservations.length) {
}
return size;
}
}
here's the txt file that the loop is reading through
Carl Foreman
1234
UA1235
06/23/2014
ORD
LGA
4:00 PM
7:15 PM
23A
UA673
07/12/2014
LGA
ORD
10:00 AM
11:25 AM
8A
Jennifer Foreman
1235
UA1235
06/23/2014
ORD
LGA
4:00 PM
7:15 PM
23B
UA673
07/12/2014
LGA
ORD
10:00 AM
11:25 AM
8B
Jane Anderson
4577
UA317
08/04/2014
ORD
SFO
8:10 AM
10:45 AM
11C
UA728
08/14/2014
SFO
ORD
12:52 PM
7:03 PM
10D
Jason Anderson
4578
TrackData.txt format
passenger name – include first and last name in one variable
reservation number
departure route number
departure date
departure track
arrival track
departure time
arrival time
seat
return route number
return date
departure track
arrival track
departure time
arrival time
seat
here's a similar method I had to write for a previous assignment
public int readInventory(Automobile[] inventory)
{
final String FILENAME = "inventory.csv";
int size = 0;
Scanner input = null;
try
{
input = new Scanner(new File(FILENAME));
}
catch (FileNotFoundException e)
{
System.out.println("Unable to open file " + FILENAME + ".");
}
// read header line and discard first line
String line = input.nextLine();
// create vars
int year = 0;
String make = "";
String model = "";
double price = 0.0;
String condition = "";
int rating = 0;
String status = "";
String vin = "";
// Customer vars
String firstName = "";
String lastName = "";
String streetAddress = "";
String city = "";
String state = "";
String zip = "";
String email = "";
String phone = "";
while (input.hasNext() && size < inventory.length)
{
line = input.nextLine();
String[] record = line.split(",");
year = Integer.parseInt(record[0]);
make = record[1];
model = record[2];
// If use this version, comment out the following if statements
if (!(record[3].equals("")))
{
price = Double.parseDouble(record[3]);
}
else
{
price = 0;
}
condition = record[4];
if (!(record[5].equals("")))
{
rating = Integer.parseInt(record[5]);
}
else
{
rating = 0;
}
status = record[6];
vin = record[7];
// this is where the records differ
// they either don't have buyer information or some do
if (record.length > 8)
{
if (!(record[8].equals("")))
firstName = record[8];
else
firstName = "";
if (!(record[9].equals("")))
lastName = record[9];
else
lastName = "";
if (!(record[10].equals("")))
streetAddress = record[10];
else
streetAddress = "";
if (!(record[11].equals("")))
city = record[11];
else
city = "";
if (!(record[12].equals("")))
state = record[12];
else
state = "";
if (!(record[13].equals("")))
zip = record[13];
else
zip = "";
if (!(record[14].equals("")))
email = record[14];
else
email = "";
if (!(record[15].equals("")))
phone = record[15];
else
phone = "";
}
// changes to integrate Customer class go below
Customer tempCustomer = new Customer(firstName,lastName, city, state, email, phone,zip,streetAddress);
Automobile tempAutomobile = new Automobile( year, make, model, price,
condition, rating, status, vin, tempCustomer);
inventory[size] = tempAutomobile;
size++;
} // end of while loop
input.close();
return size;
}
not sure how to make it work for this program since this is multilined and the previous was a single line separated by commas hence the line.split
Hmmm... I am not sure i should answer this since it is not that hard and i am sure you can solve it yourself. Sadly i dont have enough reputation to just comment (that is why i am here in the first place).
I will just drop some hints to help you:
1) You know how to read line by line. You can choose when to start, stop and even skip lines. Sadly you can only move forward but that is enough for this problem.
2) The data file follows a constant pattern. This means this is the easy to handle data.
3) You know the pattern beforehand. Pst, it is the OP!
I think that is it. Now you should just pay attention and wait for the AHA! moment.
package edu.ilstu;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* <insert class description here>
*
* #author Chris Crosby
*
*/
public class TrackInput
{
public final String TRANSACTION_FILE = "Transactions.txt";
public final String DATA_FILE = "RailroadData.txt";
public TrackInput() {
}
Scanner transaction = null;
public Scanner readTransactions() {
try {
transaction= new Scanner(new File(TRANSACTION_FILE));
}
catch(FileNotFoundException e){
System.out.println("Unable to open file" + TRANSACTION_FILE);
System.exit(1);
}
return transaction;
}
public char readTransactionCode() {
char choice = transaction.nextLine().charAt(0);
return choice;
}
public int readRailroadData(Reservation [] reservations) {
Scanner data;
int count = 0;
try {
data = new Scanner(new File(DATA_FILE));
while(data.hasNext()) {
Reservation reservation = readReservationData(data);
reservations [count] = reservation;
count++;
}
}
catch(FileNotFoundException e){
System.out.println("Unable to open file" + DATA_FILE);
System.exit(1);
}
return count;
}
public Reservation readReservationData(Scanner input) {
String name = input.nextLine();
String departureReservationNumber=input.nextLine();
String departureRouteNumber = input.nextLine();
String departureRouteDate = input.nextLine();
String departureTrack = input.nextLine();
String departureArrivalTrack = input.nextLine();
String departureTime = input.nextLine();
String departureArrivalTime = input.nextLine();
String departureSeatAssignment = input.nextLine();
String returnRoute = input.nextLine();
String returnDate = input.nextLine();
String returnDepartureTrack = input.nextLine();
String returnArrivalTrack = input.nextLine();
String returnDepartureTime = input.nextLine();
String returnArrivalTime = input.nextLine();
String returnSeatAssignment = input.nextLine();
Route departureRoute = new Route(departureRouteNumber, departureRouteDate, departureTrack, departureArrivalTrack,departureTime, departureArrivalTime, departureSeatAssignment);
Route arrivalRoute= new Route(returnRoute, returnDate, returnDepartureTrack, returnArrivalTrack,returnDepartureTime,returnArrivalTime,returnSeatAssignment);
Reservation reservation = new Reservation(name,departureReservationNumber, departureRoute, arrivalRoute);
return reservation;
}
public int addReservationToList(Reservation[] reservationList,Reservation reservation, int size) {
reservationList[size] = reservation;
size++;
return size;
}
}
I recieve a file each day that:
is stab delimited
has 5 or more columns
has 3 common columns - lastName, firstName, address
Problem: the column order of the file changes regularly
Goal: print column data for lastName, firstName, address regardless of column order
I have been using the following code and manually changing the datavalues to match the columns.
testfile1.txt
1st day file format
ID lastName address phone firstName
45 Gates 111 some lane 777-888-9999 Bill
2nd day file format
address ID phone firstName lastName
111 some lane 81 444-555-1111 John Doe
-
import java.io.BufferedReader;
import java.io.FileReader;
public class test2 {
public static void main(String args[]) throws Exception {
String dataFileName = "C:/testfiles/testfile1.txt";
String line;
int lineNumber = 0;
BufferedReader bReader = new BufferedReader(new FileReader(dataFileName));
bReader.readLine();
while ((line = bReader.readLine()) != null) {
lineNumber++;
String datavalue[] = line.split("\t");
String lastName = datavalue[1];
String firstName = datavalue[5];
String address = datavalue[3];
System.out.println(lastName + "'" + firstName + "," + address);
}
}
}
This is a first approach. I would try it somehow like this:
int colLastName, colFirstName, colAddress;
line = bReader.readLine();
String columnOrder []= line.split("\t");
for (int i=0; i< columnOrder.length; i++){
if (columnOrder[i].equals("lastName")){
colLastName = i;
}
else if (columnOrder[i].equals("firstName"){
colFirstName = i;
}
else if (columnOrder[i].equals("address"){
colAddress = i;
}
}
while ((line = bReader.readLine()) != null) {
lineNumber++;
String datavalue[] = line.split("\t");
String lastName = datavalue[colLastName];
String firstName = datavalue[colFirstName];
String address = datavalue[colAddress];
System.out.println(lastName + "'" + firstName + "," + address);
}
I think you can try something like below -
import java.io.BufferedReader;
import java.io.FileReader;
public class test2 {
public static void main(String args[]) throws Exception {
String dataFileName = "C:/testfiles/testfile1.txt";
String line;
boolean isFirstColumn = true;
BufferedReader bReader = new BufferedReader(new FileReader(dataFileName));
int[] order_Fname_Lname_Address = new int[3];
while ((line = bReader.readLine()) != null) {
String datavalue[] = line.split("\t");
if(isFirstColumn) {
for (int i = 0; i < datavalue.length; i++) {
switch (datavalue[i]) {
case "firstName":
order_Fname_Lname_Address[0] = i;
break;
case "lastName":
order_Fname_Lname_Address[1] = i;
break;
case "address":
order_Fname_Lname_Address[2] = i;
break;
}
}
isFirstColumn = false;
continue;
}
String firstName = datavalue[order_Fname_Lname_Address[0]];
String lastName = datavalue[order_Fname_Lname_Address[1]];
String address = datavalue[order_Fname_Lname_Address[2]];
System.out.println(lastName + " " + firstName + "," + address);
}
bReader.close();
}
}