printing arrays - java

Okay, I'm trying to get file scanner to return the array itemList.
However, I don't understand why everytime I get to return itemList and try with a println form.
It returns:
[Ljava.lang.String;#3d3b5a3a
[Ljava.lang.String;#10cb42cf
[Ljava.lang.String;#482d59a3
[Ljava.lang.String;#18f42160
When the file I'm reading it contains stuff like
apples 10
fish 20
import java.io.*;
import java.util.*;
class loadInventory{ /*This class is used for loading the inventory */
private String[] itemList; /*The lines of the inventory are stored in this array */
private int numItems; /* The number of items is stored in this variable */
public loadInventory(String fileName){ /*We can do everything in the constructor. It gets the fileName from the superMarket
object */
itemList = new String[100]; /*We assume there are not more than 100 items in the inventory */
numItems=0; /*initialize numItems to 0*/
/*Read the file using the try-catch block below. We are not specifically catching any exception.
We will not cover reading or writing of files and exceptions in this unit. So you
don't need to understand this piece of code. */
try{
BufferedReader reader = new BufferedReader(new FileReader(fileName)); /*standard code for reading a file */
String line = reader.readLine(); /*read the next line from the file and store in line */
while (line != null){ /*as long as there are lines */
itemList[numItems]= line; /*store the line in the current location of the array */
numItems++; /*increment the number of items */
line = reader.readLine(); /*read the next line */
}
reader.close(); /*close the reader */
} catch (IOException e){ /*we don't catch any exception */
}
System.out.println(itemList);
}
public String[] getItemList() {
return itemList;
}
}

Print the array of instances like this:
System.out.println(Arrays.toString(itemList));

An array itself uses the default toString() from Object, so it does not print its contents. You will need to use java.util.Arrays.toString(Object[]) to print out the content of the array (or loop over it yourself).

int length = itemList.length;
int count =0;
while(count<length)
{
System.out.println(itemList[count]);
count++;
}
thats a simplest way to iterate the list.

Because you are trying to print the whole array object while doing:
System.out.println(itemList);
Instead you need to print the single String elements stored inside the array:
System.out.println(Arrays.toString(itemList));

Don't print the String[] value directly. use like this,
for (int i = 0; i < itemList.length; i++) {
System.out.println("Value::> " +itemList[i]);
}

Pay attention on this code
while (line != null)
{
itemList[numItems]= line;
numItems++;
line = (String)reader.readLine();
}
Try this.

Related

How to retrieve array values and assign to String variable in 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.

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

How can I parse lines of data from file to populate objects for each?

I have a text file with the list inside, every line has data that I need insert in the new objects. So data looks like somename=3000 or another type with the slash data another type = 6000.
I have particular class "Item" that has String and int variable. Data need to be inserted into them. Every new object has to be added to the ArrayList<Item>.
// Calculate the lines for next for each loop
int lineCount = 0;
while (sc.hasNextLine()) {
lineCount++;
sc.nextLine();
}
for (int i = 0; i < lineCount; i++) {
// creating the object
Item item = new Item();
// add item object to items ArrayList
items.add(item);
// add line to String variable lineToString,
while (scaner.hasNextLine()) {
String lineToString = scaner.nextLine();
sc.nextLine();
}
So, I figured out that to do this, I need to
copy the whole line and put into some string variable;
split it for integer and string variable;
insert string parts to the String variable and numbers to the int variable in particular object that was created in iteration time of "for loop".
add the object with a data inside to the ArrayList.
I used Scanner to read a text file. When I try to insert the scaner.nextLine to the String it's doesn't work; I mean it's executing but variable String lineToString doesn't have the line from a text file.
Could somebody help with an idea of how better to proceed with this problem? Maybe there is some simpler way to insert the 2 different type of data from the text file line in the object and put it into the ArrayList? Every line in the text file has different data and has to be in different objects.
You didn't mention clearly the line format from the text file. I assume so far you have text file in which each line is like
someone=140000
And you are trying to read those lines of the text and parse each of them to an object of Item which contains a String property (I assume you name it name) and an int property (I assume you name it number)
If this is it, you fisrt need to read your text file line by line and process it further. There are several ways to read a text file line by line.
BufferReader
This is a very common and so far most appropriate way to read a text file in consider of performance.
List<Item> particulatItems = new ArrayList<>();
// using try-with-resource that will help closing BufferedReader by own
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
particularItems.add(processLine(line));
}
}
Scanner
You could use Scanner too.
try (Scanner scanner = new Scanner(new File(fileName))) {
while (scanner.hasNext()) {
particularItems.add(processLine(line));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
You should extract the line processing logic to a independent function. This is good practice of clean coding.
public static Item processLine(Strinng line) {
String[] tokens = line.split("=");
Item item = new Item(tokens[0], tokens[1]);
}
Assuming you have that particular object defined as Item and you are populating a List of this type
public class Item {
String name;
int number;
public Item(String name, String numtxt) {
this.name = name;
this.number = Integer.parseInt(numtxt);
}
// setter getter
}
More reading:
How to read a large text file line by line using Java?
Different ways of Reading a text file in Java
Difference between Scanner vs BufferReader
Try-with-resources in Java 7
Looks like you have already scanned full file in below code snippet:
while (sc.hasNextLine()) {
lineCount++;
sc.nextLine();
}
After this, you are again iterating in for-loop but with same scanner, which has read last line
So the following may return false:
while (scaner.hasNextLine())
I it may never enter while loop
You should reset scanner before iterating lines again .. or may be use something else than scanner to count lines
Apart from what #Ashish Mishra mentioned, you are doing the second while loop in a for loop, why? Isn't one loop sufficient?
int lineCount = 0;
while (sc.hasNextLine()) {
lineCount++;
String lineToString = sc.nextLine();
Item item = new Item();
//convert lineToString to item
items.add(item);
}

Reading from Array and using Recursive method to check for Palindromes

I've been tasked with creating an array by reading from a text file created by myself. The program in concept, is supposed to read the words i entered, and store them in an array. Following, I am to create a recursive method to check and see if each line is a palindrome and print the result. Currently, I'm getting a stack overflow error. Sorry if the code is not commented on too much.
package palindrome;
import java.util.*;
import java.io.*;
/**
*
* #author alexanderrivera
*/
public class Palindrome {
// Static variables can be used in ALL instances of a class
public static String [] Palindromes;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// Establishes a value to Palindromes
Palindromes = new String[10];
int i=0;
// calls the readFile method to read the file
readFile("Palindrome.txt");
FindPalindrome(Palindromes[i]);
}// end of main method
// begining of the readFile method
public static void readFile(String fileName)
{
// sets the int variable to zero
int i = 0;
// establishes the java input for reading the file
java.io.File inputFile = new java.io.File(fileName);
// being try catch block
try{
// establishes instance of the scanner to read the file
Scanner fileReader = new Scanner(inputFile);
// being while statement
while(fileReader.hasNextLine())
{
Palindromes[i] = fileReader.nextLine();
i++;
}// end while statement
// closes the file reader
fileReader.close();
// print the index to see if it was read
}catch (FileNotFoundException e){
System.out.println("Sorry, cannot find the file");
}// end error message
} // end the method
public static void FindPalindrome(String FoundPalindrome) {
int i=0;
{
if (Palindromes[i].length() == 0 || Palindromes[i].length() == 1) {
System.out.println(Palindromes[i] + " This is a Palindrome\n");
}
if (Palindromes[i].charAt(0) == Palindromes[i].charAt(Palindromes[i].length() - 1)) {
FindPalindrome(Palindromes[i].substring(1, Palindromes[i].length() - 1));
}
// otherwise
System.out.println("This is not a Palindrome \n");
}
}
}
In recursive calls to your FindPalindrome method, you're passing strings which you never use, since the FindPalindrome method looks at the first entry in the original array of strings and ignores its parameter. So it just repeatedly calls itself with the same argument until it overflows the stack.
Everywhere in FindPalindrome that you reference Palindromes[i], you should likely be referencing instead the parameter FoundPalindrome, and then it might actually work.

Coordinating reading lines from a file and using obtained data

Here is my code for reading lines from a CSV file :
private void input()throws IOException
{
//FILE READER FIELDS
StringTokenizer st=null;
BufferedReader b=new BufferedReader(new FileReader(csvfile));
String line=null;
int count=0;
while((line=b.readLine())!=null)
{
count+=1;
if(count==1)
{
continue;
}
else
{
String[] arr=new String[19];
st=new StringTokenizer(line,",");
int i=0;
while(st.hasMoreTokens())
{
arr[i]=st.nextToken();
i++;
}
for(int j=2;j<arr.length;j++)
{
if(j==11)
{
calib_g=Double.parseDouble(arr[j]);
}
if(j==12)
{
coolant_temp=Double.parseDouble(arr[j]);
}
if(j==13)
{
engineRPM=Double.parseDouble(arr[j]);
}
}
}
}
}
As can be inferred from the code, the objective of the above input method is to read the file starting from the second line store the tokens obtained from the perused line in an array whose length is predetermined. Then, select elements from the array are used to update the static variables calib_g ,engineRPM and coolant_temp.
These variables are then used by the below method which updates COSM(previously pachube now xively) with these values :
private void update(int feedid) throws PachubeException, IOException
{
Feed f = this.pachube.getFeed(feedid);
System.out.println("XML is :" + f.toXML());
input();
flag=false;
System.out.println("updating ...");
f.updateDatastream(8345, calib_g);
f.updateDatastream(6274, coolant_temp);
f.updateDatastream(1044, engineRPM);
System.out.println("updated");
}
Problem :
When the input method is called from within the update method, while((line=b.readLine())!=null) iterates over the entire loop and returns the values only from the last line.
Objective :
I want to upload data from a single line when the upload method calls the input method.Thus the flow of the program should be like this
update method is called every 5 seconds using a Timer in the main method.
The update method calls the input method.
The compiler executes the while loop.While loop reads one line from
the csv file.The line is tokenized and stored in the array.Selected
elements of the array are used to update the static variables.
The update method updates XIVELY with the aforementioned static
variables.
Go to step 1 .The update method is called again.
The input method is subsequently called again . This time the next
line of the csv file is used to update the static variables

Categories