My get method will not display arraylist value - java

I am new to java and stackOverflow so please be patient if I don't post all the necessary information about my question. Basically, I am trying to read lines from a .txt file and store them in a Stack. I also need to access this Stack in a different class. So I created a get method but it always returns null. Please help!
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.Stack;
public class Hints {
private Stack stack;
private File f;
private String line;
private Scanner scanner;
public Hints(){
f = new File("hints.txt");
stack = new Stack();
}
public void getList() throws FileNotFoundException, IOException {
scanner = new Scanner(f);
while(scanner.hasNextLine()) {
line = scanner.nextLine();
stack.add(line);
}
scanner.close();
}
public Stack getStack(){
return stack;
}
}
When I try to print the stack with a simple System.out.print, it will come out as null. Where is my issue(s)?
Thank you.

Your code works fine. I think you are not calling the getList() method before you call the getStack() method.
try {
Hints hints = new Hints();
hints.getList(); // adds to the stack
Stack s = hints.getStack(); // return the stack
int stackSize = s.size();
for (int i = 0; i < stackSize; i++) {
System.out.println(s.pop()); // pop from the stack
}
} catch (IOException ex) {
Logger.getLogger(JavaApplication18.class.getName()).log(Level.SEVERE, null, ex);
}
You must call the getList() method first before you call the getStack() method. Because getList() method adds values that are read from the txt file. Then only you can call the getStack() method. Otherwise you don't have any values in the stack.

The code you presented looks fine so far. You initialize your stack by iterating through your textfile. So if the textfile contains lines, the stack will be filled with the data. So you might probably have a problem while printing your result.
Since java.util.Stack is derived from Vector, you can use the get(int) Method to access the data inside your stack. Therefore, you simply need a printing method that accesses the stack like this:
Hints h = new Hints();
h.getList();
Stack theStack = h.getStack();
for (int i = 0; i < theStack.size(); i++) {
System.out.println(theStack.get(i));
}
Now your stack should be printed correctly to the console.
And remember calling the getList() method before trying to access your stack. You should consider initializing the stack within the constructor. Maybe this is the thing you are missing.

This is my hint
public Hints() throws FileNotFoundException, IOException{
f = new File("hints.txt");
stack = new Stack();
getList(); // call get list in constructor.
}
When you create the hint its populate the stack.

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.

Do empty stacks automatically have a null value?

I'm quite new to java. So I've got some code that is supposed to add files to a stack and compare the stack contents with an existing reference. Here's the class that should create the stack:
public class ArrayStack<T> implements ArrayStackADT<T> {
private T[] stack;
private int top;
// constructor, passes default capacity
public ArrayStack() {
top = -1;
stack = (T[]) new Object[14];
}
// constructor, initializes capacity to stack and top
public ArrayStack(int initialCapacity) {
top = -1;
stack = (T[])new Object[initialCapacity];
}
}
and here is the code that calls the stack:
public static void main(String[] args){
StartSearch path = new StartSearch(args[0]);
int distance = Integer.parseInt(args[1]);
ArrayStack stack = new ArrayStack(); // creates empty stack
MapCell cell = path.targetMap.getStart(); // gets starting cell
stack.push(cell); // pushes starting cell to stack
}
Not sure if I showed enough code, so please let me know if I didn't. I had some push and pop methods to insert and remove stack items, and for each push/pop they'd print "push" + the value:
if (dataItem instanceof MapCell) {
sequence += "push" + ((MapCell)dataItem).getIdentifier();
}
else {
sequence += "push" + dataItem.toString();
}
For some reason though, when I go to print sequence later, it outputs this:
nullpush0push2push3
Instead of what I need it to output:
push0push2push3
Do empty stacks automatically have a null value or something? how do I get rid of the null value at the beginning?
It hasn’t got anything to do with your stack class. It’s how you initialize your String variable. Or perhaps forgot to initialize it? To demonstrate:
String sequence = null;
sequence += "push1";
System.out.println(sequence);
Output is:
nullpush1
Instead initialize sequence to the empty string:
String sequence = "";
push1
Or use a StringBuffer or StringBuilder:
StringBuilder sequence = new StringBuilder();
sequence.append("push1");
System.out.println(sequence);
Output is identical:
push1

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

Read from text file, and return into arraylist in private method

I have try many things, and I am so stuck in this problem.
I have to read from a text file, and throw it inside an arraylist in a private method.
And then make a new method that will print the arraylist out.
This is what I have tried so far.
I get this error:
fileHandling.java:11: readArray(java.util.ArrayList<java.lang.String>) in fileHandling cannot be applied to ()
readArray();
^
1 error
My code:
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class fileHandling {
private ArrayList<String> Person;
public static void main(String[] args)throws Exception {
readArray();
}
private ArrayList readFile() throws Exception {
File file = new File("person.rtf");
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()) {
String str = scanner.nextLine();
Person.add(str);
}
return Person;
}
public void readArray(ArrayList<String> Person) {
for(int i =0; i < Person.size(); i++) {
System.out.println(Person.get(i));
}
}
}
I think the error is when I called my method, what is going inside the brackets?
You have a few issues (that I see).
1) You aren't instantiating an instance of your class.
2) You aren't reading the file.
3) You aren't calling readArray with the List.
4) You have no List instance.
5) ArrayList<String> readFile()
I think you want something like this,
private ArrayList<String> Person = new ArrayList<String>();
public static void main(String[] args) throws Exception
{
// readArray();
fileHandling fh = new fileHandling();
fh.readArray(fh.readFile()); // <-- something like this
}
You should use a bufferedInputStream to read your file...
variables should not be capitalized and your array should also be called persons and not Person.
Don't forget to initialize your
ArrayList persons = new ArrayList();
Your main method should call the read method first.
If you use Java 7, it is as easy as:
// returns a List<String> with all lines in the file
Files.readAllLines(thePath, StandardCharsets.UTF_8);
First you won't be able to access readArray() from your main since readArray() is not static. In your current context you'd need to create an instance of fileHandling in your main and call readArray() on it.
Second, your readArray() method is declared with an ArrayList Person as a parameter, but you're calling it without the parameter in your main method.
Third, it won't help with the compilation, but rule of thumb in Java is to capitalize the first letter of a class (Should be FileHandling) and to not capitalize the first letter of a declaration (ArrayList Person should really be ArrayList person).

Populating stack causes error

I'm populating a stack instance variable with elements of the array el, but in the line below it's giving me an error although I specified that it's a stack of Integers.
Error:
Incompatible types - found java.util.Stack but expected java.lang.Integer...
Code:
import java.util.Stack;
public class SortedStack
{
private Stack<Integer> stack = new Stack<Integer>();
public SortedStack(Integer[] el)
{
for(int i = 0; i < el.length; i++)
{
el[i] = stack; /** THIS LINE*/
}
}
}
To add an item to the top of the stack, use the push method.
Example:
public SortedStack(Integer[] el)
{
for(int i = 0; i < el.length; i++)
{
stack.push(el[i]);
}
}
This will push elements from the el array into the stack.
I think you want to add elements of el into stack . You were trying to assign stack object to el[i] which is not possible. Its obvious that you got error.
So your code should be like following :
public class SortedStack
{
private Stack<Integer> stack = new Stack<Integer>();
public SortedStack(Integer[] el)
{
for(int i = 0; i < el.length; i++)
{
stack.push(el[i];
}
}
}
I'm not a Java developer but I'm guessing if you want to put a value on the stack you'll need something like:
stack.push(el[i]);
The reason for your error is your trying to assign the i-th Element in an Integer array, to be a Stack. This is failing because it can't cast a Stack to an integer.
Use Stack.push() method.
stack.push(el[i]);
To use a stack, you want to push() your item on top of it, and pop() it from the stack when you're ready to use it again. In your case, it seems more appropriate to inherit the stack, than to wrap it.
import java.util.Stack;
public class SortedStack extends Stack<Integer>
{
public SortedStack(Integer[] el) // Why "Sorted"? You're not sorting here...
{
for(int i = 0; i < el.length; i++)
{
this.push(el[i]); /** THE ERROR IS THIS LINE */
}
}
}
Doing this, you can use your SortedStack just like any regular stack, with the addition of adding a whole range of elements in the constructor. You might also want to implement a PushRange() method, that can be called after the object is instantiated.

Categories