Say I have a .txt file that has information being split by a comma as such:
IN,Indiana,6634007
While this is a snippet which accesses that file and splits it:
for(int i=0; i < count; i++) {
line = bufferedReader2.readLine();
String space[] = line.split(",");
String abb = space[0];
String nme = space[1];
int pop = Integer.parseInt(space[2]);
states[i] = new State(abb, nme, pop);
}
The purpose of that was so that all the information in the txt file could be accessed, so for example this code would print exactly whats present on the .txt file:
System.out.println(states[0]);
would print:
IN,Indiana,6634007
My question is, how would I have it so that I can access the specific part of the array as in how would I print lets say just the name "Indiana" or the population "6634007"?
P.S I'm sorry if the title of my question did not make sense, I did not exactly know how to word it.
Somewhere, you have a class called State. states is an Array of this class. So you can add a getter to State:
public int getPop() {
return pop;
}
And call it on your Object like this:
System.out.println(states[0].getPop());
as states[0] is simply a State object.
Add more getters to access different fields.
if you just want to print every single line, you can try this like below:
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line = null;
List<String> list = new ArrayList<String>();
while((line = reader.readLine()) != null ) {
list.add(line);
}
System.out.println(list.get(0));
// TODO realease resources
}
From your question what i can realise is, you are using State class to store the information. In such case, check the state class where the first parameter value is stored. Later to print the corresponding information, access its object variable as SapuSeven mentioned.
For eg.
public class State{
public String a;
public String b;
public int c;
public State(String x, String y, int z){
a=x;
b=y;
c=z;
}
}
now u can access like
System.out.println(states[0].b);
for printing the name of city
OR
you can simply print the value using index like this
System.out.println(states[0].split(",")[2]);
Related
I am trying to store the contents from a file into an array String retval[] , copy that array to String[] fed() and pass the array into main. So far, the array stores and copies but the array method returns null in main String []feed; feed=uio.fed();.
UserIO.java
package fileio;
import classes.*;
import java.util.*;
import java.lang.*;
import java.io.*;
public class UserIO
{
public String search (String line0)
{
String line;
try
{
FileInputStream ufin = new FileInputStream("E:\\3rd sem\\OOP\\Projects\\New folder (2)\\BOOK LIBRARY\\fileio\\user.txt");
Scanner sc = new Scanner(ufin);
while (sc.hasNextLine())
{
line=sc.nextLine();
if(line.contains(line0))
{
String retval[]= line.split(" ");
feed= new String[retval.length];
for (String s: retval)
{
System.out.println("\t\t\tFrom retval:"+s);
}
for (int n=0;n<retval.length;n++)
{
feed[n]=retval[n];
System.out.println("\tFrom feed:"+feed[n]);
}
}
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
return line0;
}
public static String [] feed;
public static String[] fed()
{
String [] fd;
fd= new String[feed.length];
for (int n=0;n<feed.length;n++)
{
fd[n]=feed[n];
System.out.println("From fd:"+fd[n]);
}
return fd;
}
}
Down below is the main method
Execute.java
import java.lang.*;
import java.util.*;
import classes.*;
import fileio.*;
public class Execute
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String adminusername = "a";
String adminpassword = "p";
String readerusername = "r";
String readerpassword = "p";
String nreaderusername;
String nreaderpassword;
Library b = new Library();
UserFileReadWriteDemo ufrwd = new UserFileReadWriteDemo();
UserIO uio = new UserIO();
System.out.println("enter id ");
String id = sc.next();
uio.search(id);
try
{
String []feed;
feed=uio.fed();
//uio.fed()=feed.clone;
for(int s=0;s<feed.length;s+=5)
{
String nid00= null;
feed[0+s]= nid00;
String name00=null;
feed[1+s]= name00;
String age00= null;
feed[2+s]= age00;
String uname00= null;
feed[3+s]= uname00;
String upassword00= null;
feed[4+s]= upassword00;
Reader c00 = new Reader(nid00, name00, age00,uname00,upassword00);
b.insertReader(c00);
System.out.println(" In main"+feed[s]);
}
}
catch (NullPointerException n)
{
n.printStackTrace();
}
}
Your code is a little bit difficult to read and also has a lot of unnecessary repetitions, for example method fed has no role, why not call search and make search return an array with the found elements? You are making search return the line you are searching for which you already know when you gave search that argument in the first place, it is just returning a useless value.
Also it is difficult to understand what search actually does, from what i see it finds the last occurrence of line0 in the file, because it continues to iterate over lines and every time it finds line0 it will create new feed array in UserIO and eliminate all the previous array it found, and will return when all file has been read. If this is your intention then this is not the right way to do it as it is inefficient, because you keep creating arrays that will be discarded. If your intention is the last occurrence of line0 then you can just assign a found line to a String variable and when the iteration finishes just split and return that array as it will be the last occurrence of line0 in the file.
As i see it the only way that fed will return null is if there is no line with line0 in the file because search initializes the array if it finds line0 at least once in the file, this way feed will be an uninitialized array which will be a null pointer.
These lines has no meaning:
String nid00= null;
feed[0+s]= nid00;
String name00=null;
feed[1+s]= name00;
String age00= null;
feed[2+s]= age00;
String uname00= null;
feed[3+s]= uname00;
String upassword00= null;
feed[4+s]= upassword00;
I think you meant nid00 = feed[0+s] and so on, because the way you wrote the assignment to nid00 and the other variables will be always null which will be useless.
Also when you copy arrays try to use Arrays.copyOf methods or System.arraycopy they save you writing several lines and also they are more efficient, read about them in the documentation.
And the last thing, it is not useful to catch nullpointer exception if you wrote your code, in general you must know what your methods do and if there is a nullpointer exception in something you wrote then there is something wrong in your code, if for example a method you wrote returns null then you must know about the possibility of a null return and handle that possible return, this way it will be easier for you to read your code and use it and also for others who use your code.
The nullpointer you are getting is because you trying to get the length of an uninitialized feed inside fed method, you must be very careful.
I'm trying to explore with simple Arrays and constructors. My goal here is to read a file of text containing 7 sets of data. (As seen from code below, string, string, bool, ect.) but I'm having problems.
My expected result is to...
Read the file from the text file, and store that data in an Array (don't need a ArrayList since we know how much data it contains, 7 sets of data a line, with 17 lines of data), then print the information. I've already tried creating the Array, with the Method and constructor, as well as reading the file and assigning the correct datatypes to the Array fields, but I'm getting the error.
"Unresolved compilation problem: Type mismatch: cannot convert from Seat to String."
When I've got my second part of my constructor below, it's supposed to relate back to the constructor method at the top, whilst looking into the Array so it knows where to store the data, right? but I'm unsure why, unless I've made an error. Previously, I've built a successful ArrayList, but I'm finding it difficult to read the data, and as explained above, I don't need an elastic Array because I know the amount of data.
I've also tried changing the return type of initial constructor method (at the top) as well as changing the name(s) of the method(s) to see if it was looking at the correct thing. Arrays are really cool and useful so I'd love to know where I've gone wrong. My code is below.
import java.io.FileReader;
import java.util.Scanner;
public class seatReserveSystem2 {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
class Seat {
String seatNum;
String seatClass;
boolean isWindow;
boolean isAisle;
boolean isTable;
double seatPrice;
String eMail;
// Constructor
Seat(String seatNum, String seatClass, boolean isWindow, boolean isAisle, boolean isTable, double seatPrice, String eMail) {
this.seatNum = seatNum;
this.seatClass = seatClass;
this.isWindow = isWindow;
this.isAisle = isAisle;
this.isTable = isTable;
this.seatPrice = seatPrice;
this.eMail = eMail;
}
}
String[] reserveSeats = new String[7];
Scanner reader = new Scanner(new FileReader("seats.txt"));
Scanner scan = new Scanner (System.in);
int index = 0;
while(reader.hasNext()) {
String dataSeats = reader.nextLine();
String[] dataSplit = dataSeats.split(" ");
String seatNum = dataSplit[0];
String seatClass = dataSplit[1];
boolean isWindow = Boolean.parseBoolean(dataSplit[2]);
boolean isAisle = Boolean.parseBoolean(dataSplit[3]);
boolean isTable = Boolean.parseBoolean(dataSplit[4]);
double seatPrice = Double.parseDouble(dataSplit[5]);
String eMail = dataSplit[6];
reserveSeats[index] = new Seat(seatNum, seatClass, isWindow, isAisle, isTable, seatPrice, eMail);
index++;
}
}
}```
The reserveSeats array is of type String instead of Seat.
Simple solution is to change
String[] reserveSeats = new String[7];
to
Seat[] reserveSeats = new Seat[7];
I'm working on a program for my Java class where I'm using a file of objects (clothing items) that represents inventory for a store. Each Retail_Item has four attributes: int itemNumber, String description, int numInInventory, and double price.
What I'm trying to figure out is how to read in each line from the file and turn each line into an object. My first thought was to create a while loop with vars like currentItemNumber, currentDescription, etc. So I tried this:
while (file.hasNextLine()) {
currentItemNumber = file.nextInt();
currentDescription = file.next
} // end while
But I got stuck there because every other time I've read in a String to a Scanner, I've always used nextLine. Can't use that here though, because each line contains multiple attributes of the object, not a String within a line. Is there a way to do this in the structure I'm trying to use, or should I be doing this a different way? I know I've seen and done some things where I parsed a String into separate pieces which I've seen people refer to as "tokens." Would people recommend reading each line in and then parsing it into separate tokens, then assigning each token to its appropriate attribute? Then I guess I'd have to cast those tokens into the appropriate object, since I think reading the whole line in and then parsing it would make each piece a String.
Here's a sample of what's in the text file (which can't be changed in any way, per the professor's instructions):
1000 Pants 10 19.99
2000 Jeans 2 25.95
3000 Shirt 12 12.50
Thanks in advance for your sage wisdom if you've got it.
The following code fulfills your requirement as stated in your question, namely how to create an instance of class RetailItem from a line of text from your text file. I presume it uses things that you may not have learned yet, like class Paths and try-with-resources. This is just used to scan through your file.
First, class RetailItem contains the members you described in your question. Next, I wrote a constructor for class RetailItem that creates a new instance and initializes the instance members. Then I wrote a toString() method that displays the contents of a RetailItem object in "human readable" form. Finally a main() method that reads your text file (which I named "clothes.txt"), line by line - using a Scanner. For each line read, the code splits it using a delimiter which consists of at least one whitespace character. (I presume you haven't yet learned about regular expressions in java.) Then I convert the elements of the String array returned by method split() into appropriate data types that are required by the RetailItem constructor. Then I call the constructor, thus creating an instance of class RetailItem (as you requested) and I print the created instance.
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Scanner;
public class RetailItem {
private static final int FIELDS = 4;
private int itemNumber;
private String description;
private int numInInventory;
private double price;
public RetailItem(int itemNumber, String description, int numInInventory, double price) {
this.itemNumber = itemNumber;
this.description = description;
this.numInInventory = numInInventory;
this.price = price;
}
#Override // java.lang.Object
public String toString() {
return String.format("%4d %-5s %2d %2.2f", itemNumber, description, numInInventory, price);
}
public static void main(String[] args) {
try (Scanner file = new Scanner(Paths.get("clothes.txt"))) {
while (file.hasNextLine()) {
String record = file.nextLine();
String[] fields = record.split("\\s+");
if (fields.length == FIELDS) {
int itemNumber = Integer.parseInt(fields[0]);
String description = fields[1];
int numInInventory = Integer.parseInt(fields[2]);
double price = Double.parseDouble(fields[3]);
RetailItem item = new RetailItem(itemNumber, description, numInInventory, price);
System.out.println(item);
}
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
I think the way that I would do is, like you said, parse each line into separate strings and then assign each piece to instance variables of the object you are building.
I have done something like this before, maybe it can be helpful.
Scanner fileScan;
File babyNameFile = new File("yob2015.txt");
try {
fileScan = new Scanner(babyNameFile);
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
return;
}
String currentLine;
int numberOfGirlsNames = 0;
while (fileScan.hasNextLine()) {
String[] values;
currentLine = fileScan.nextLine();
values = currentLine.split(",");
if (values[1].equals("F")) {
numberOfGirlsNames = numberOfGirlsNames+1;
}
}
System.out.println("Number of female names was "+numberOfGirlsNames);
I have a function that reads through a file, and gathers the results into an array list.
The array list looks like this (data)
[12, adam, 1993, 1234, bob, 1992]
I then need to load these details into new objects called patients. This is the current method I have so far for putting each separate array list item into its own patient, yet it keeps bugging me with an error saying I am passing in String String Int, and it needs to be a String.
s looks like this
12, adam, 1993
And this is the code
public void loadPatients()throws Exception
{
ArrayList<String> data = IO_Support.readData("PatientData.txt");
System.out.println(data);
for(String s : data)
{
Sytem.out.println(s);
patientList.add(new Patient(s));
}
}
Is there a way to push my array list result into a string for passing into the patient object, or should I use a different way to split the string results?
Read data looks like this
public static ArrayList<String> readData(String fileName) throws Exception
{
ArrayList<String> data = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String temp = in.readLine();
while (temp != null)
{
data.add(temp);
temp = in.readLine();
}
in.close();
return data;
}
while (temp != null)
{
temp = in.readLine();
}
First thing, You are never adding your input to the ArrayList.. This while loop makes no sense.. It is just reading user input, and swallowing it on every occassion..
Plus, after seeing your exception, its sure that you are using a 1-arg constructor of Patient class which is not there.. There are only 0-arg constructor and 2-arg constructor in Patient class.. You need to use them indeed.
See this code in loadPatient method.. You need to add a 1-arg constructor in your Patient class to get it compiled..
patientList.add(**new Patient(s)**); --> Will not work
So, in your Patient class, add: -
public Patient(String s) {
this.s = s;
}
this.s is the instance variable to store s that you passed..
I imported a List of Strings from a file and put them into an arrayList. I am trying to chop of the end of these arrays, so I'm putting them into a separate String format
Here is where i set x
x = new ArrayList<BankAccounts>();
try {
Scanner reader;
reader = new Scanner( new File("F:\\myCreditUnion.txt") );
while ( reader.hasNext() )
{
String inputLine = reader.nextLine();
first = inputLine.substring(0, 3);
second = Double.parseDouble(inputLine.substring(5, inputLine.length()));
x.add(new BankAccounts(first, second));
}
reader.close();
}
and this is where i try to chop off the end
double howmuch;
for(int i = 0; i < x.size(); i++)
{
list.equals(x.get(i));
howmuch = Double.parseDouble(list.substring(5, list.length()));
}
// x is the list
I am getting a nullpointerexception. Wondering how to fix this, as I am pretty new to programming.
Document i am importing contains a combinations of # and letters such as, 101s 583.58
To assign a value to list you have use list = x.get(i); instead of list.equals(x.get(i));
Update:
equals() does not assign values it only checks if two objects are equal.
The value returned by x.get(i) will be a BankAccount so you can't assign it to list (which is a String)
You have to either turn the BankAccount into a String by using toString() or you have to get a String out of it by calling one of the BankAccount methods before assigning it to list, how this works depends on the methods provided by the BankAccount class.
If you are getting a NullPointerException in the above code, either list or x is null. Check where you are setting their value, or include that part of the code in the question.
Regarding your code: you probably have some sort of declaration similar to: String line = null; somewhere before your last piece of code pasted and you get get a NullPointerException at the list.equals(x.get(i)); line. This is because your list object is not initialized. However you don't need to do that. See below.
In order to do what you want you should use the following code:
The class definition for BankAccounts:
class BankAccounts {
public String account;
public Double value;
public BankAccounts(String account, Double value)
{
this.account = account;
this.value = value;
}
}
And rewrite your code like this:
List<BankAccounts> x = new ArrayList<BankAccounts>();
try {
Scanner reader;
reader = new Scanner( new File("F:\\myCreditUnion.txt") );
while ( reader.hasNext() )
{
String inputLine = reader.nextLine();
first = inputLine.substring(0, 3);
second = Double.parseDouble(inputLine.substring(5, inputLine.length()));
x.add(new BankAccounts(first, second));
}
reader.close();
}
It seems to me that your input files contains line of the form ABC 10.324. You are parsing this properly into BankAccounts objects (each one containing a String representing the account name and a Double representing the amount) when you are reading them from file. So there is no need to reparse that again.
The code to iterate and look at the amounts is below;
// x is the list
double howmuch = 0;
for(int i = 0; i < x.size(); i++)
{
BankAccounts accounts = x.get(i);
howmuch = accounts.amount; // there is no need to cast since unboxing will occur here.
// here howmuch will contain the amount for each account
}