How to retrieve array values and assign to String variable in java - java

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.

Related

Type Mismatch: Cannot convert from Seat to String

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

How do I access an array within an array?

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]);

Variable Scope - JAVA Class/Method

I am reading in data from a text file into an ArrayList and then trying to search for a particular string in that ArrayList (the second method).
I believe that I am correctly reading in the data however am struggling to write methods to implement on the ArrayList once it has been filled. For instance, in the checking method below, it is returning a false when I am certain the input String is in the data structure.
I recognize this is likely a problem with my variable scope or how my methods are interacting with each other (i.e, the arraylist is not actually filled with the data when I am checking it).
Any help would be much appreciated - thanks
import java.util.*;
import java.io.*;
public class Word {
ArrayList<String> diclist = new ArrayList<String>();
private void readIn() throws FileNotFoundException {
File file = new File("filepath");
Scanner s = new Scanner(file);
s.useDelimiter("\n");
while (s.hasNextLine()) {
diclist.add(s.nextLine());
}
s.close();
}
public boolean checkIn(String z) {//Check if input string z is in diclist
for (int i = 0; i < diclist.size(); i++) {
if (diclist.get(i).equals(z)) {return true;}
}
return false;
}
}
There are no obvious problems in the code you posted so far. After calling readIn, if the file exists, readable and not empty, the list should get populated. I suggest running it through a debugger.
Note that the checkIn method can be vastly simplified to this:
return diclist.contains(z);

Parse CSV file in java, and delaing with empty values

I am parsing a CSV file into my program, spliting the values at the , element, and it's working fine, except for when I have lines that have missing values.
The parser is working like this:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class CsvReader
{
private static final String DELIMITER = ",";
private final BufferedReader br;
private final String path;
public CsvReader(final String path) throws IOException
{
this.path = path;
this.br = new BufferedReader(new FileReader(path));
}
public String[] nextLine() throws IOException
{
final String line = br.readLine();
return (line == null) ? new String[0] : line.split(DELIMITER);
}
}
The lines of data look like this (one line as an example):
J1024205,5028197000004,1,,00,20150603,,Accessories,Factory Test Article (m),ENG,010,110,5,T1,99,99,,,99,99,99,ZZ,ZZ,,5028197242053,30,35028197242054,6,,,OPZ848,3013607800239,OPZ848,,,,50,,
Most of the lines in the file complete with this: 50,85028197242127,8640
But on some lines, the data is missing, so it ends like this: 50,,
When the file is being processed, these lines are causing a java.lang.ArrayIndexOutOfBoundsException.
How can I best deal with this, if I know that the numbers of objects in the file will remain constant?
I've been told that I need to replace empty values with a null value.
From the Javadoc of String.split(regex)
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
So, in your case, when the string ends with ,,, empty strings wont be part of the resultant array.
To Fix: Use this variant of split
line.split(DELIMITER, -1);
This will include all trailing empty strings. So you won't get an exception.
This code results in array elements that are null if the column was empty.
// ... rest of OP's code
public String[] nextLine() throws IOException
{
final String line = br.readLine();
if(line == null)
{
return null;
}
String columns[] = line.split(DELIMITER, -1);
for(int i = 0; i < columns.length; i++)
{
if(columns[i].isEmpty())
{
columns[i] = null;
}
}
return columns;
}
You can this way also. Just call split method on the String returned with comma
public String replaceNullSplitLine(String line){
if(line.endsWith(",")){
line = line+"***";
}
line = line.replaceAll(",,", ",***,");
return line;
}
Check the length of the array before trying to use the last (and in that case non-existed) values
myArray.length

NullPointerException error, converting string[] to int[]

I'm running out of patience and needs this problem fixed. This program is intended to retrieve data from two text files as two string arrays, then use a mergesort algorithm to sort the results. My issue is during the conversion to an integer array. I return the array I created, and see that there is data stored. However, when running an loop and checking if any index is null, I find that the program believes them all to be null.
import java.io.IOException;
import java.nio.file.Files;
import java.io.File;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
public class MergeInventories
{
public static File inv1 = new File("H:\\Senior Year\\CompSci\\Projects\\storeOneInv.txt");
public static File inv2 = new File("H:\\Senior Year\\CompSci\\Projects\\storeTwoInv.txt");
//the two text files I'm retrieving data from
public static String[] store1; //string array in question
public static String[] store2;
public static void header()
{
System.out.println("Keenan Schmidt");
System.out.println("AP Computer Science");
System.out.println("Merge Inventories");
System.out.println("...finally...");
}
public static void main() throws FileNotFoundException
{
header();
readFiles(inv1,store1); //converts file to string array
sort(); //converts string[] to int[]
//System.out.print(readFiles(inv1,store1));
//System.out.print(readFiles(inv2,store2);
}
public static String[] readFiles(File file, String[] store)
{
try {
Scanner scanner = new Scanner(file);
int i = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
i++;
}
store = new String[i];
i = 0;
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
store[i] = line;
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return store;
}
public static int[] sort()
{
int[] items = new int[store1.length];
for(int i = 0; i < store1.length; i++)
{
if(store1[i] != null) //this is the line where the error occurs
{
try{
items[i] = Integer.parseInt(store1[i].replaceAll("[^0-9]"," "));
} catch (NumberFormatException nfe) {};
}
}
return items;
}
private void mergeSort(String[] arr1, String[] arr2)
{
}
private void merge(int low, int med, int hi)
{
}
}
As azurefrog mentions in a comment, Java arrays are pass by value (the reference to the array) so that when you reassign the store variable in the method, the original array you passed in doesn't get the new reference assignment.
Since you want to re-use this method multiple times to make different arrays, I would suggest making a new array everytime inside the method. No need to pass it in.
static String[] readFiles(File file){
String[] store =null;
//rest of method this same
}
Then in your calling code:
store1 = readFiles(inv1);
store2 = readFiles(inv2);
You are getting a NullPointerException when trying to access store1 because you never give store1 a value other than null, because Java is pass-by-value.
You create a new array, but you only assign it to store, which is a local variable in readFiles(), and that assignment has no effect on the store1 variable.
You do return that value from your method, but you neglected to assign it in the invoking code.
Replace
readFiles(inv1,store1); //converts file to string array
with
store1 = readFiles(inv1,store1); //converts file to string array and saves it in store1
so that the created array is assigned to store1.
As dkatzel points out, this means that there is no longer any point in passing store1 into the method in the first place. It would be a good idea to follow his advice on cleaning up the method.
You can use a List at first because the file could be of unknown size, then convert the List to an Array (using toArray), and then you will know the length to which you should initialize the int array and your code can proceed as expected.
either change to this: store1 = readFiles(inv1,store1);
or in readFiles() use this.store1 instead

Categories