Random Line reading in text file

I am trying to read a random line in a text file but every time i read it it reads first line of the file any one can help me what is the problem in the code is or provide me with a new code.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
               File file = new File("word.txt");
               if(!file.exists())
                    System.out.println("File does not exist.");
                    System.exit(0);
               try{
                    //Open the file for reading
                    RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(file.length());     //Seek to end of file
                    System.out.println("Read full line: " + raf.readLine());
//str2 is a String
                    str2 = str2 + raf.readLine();
                    System.out.println(""+str2);
                    raf.close();
                    System.out.println("Successfully");
               catch(IOException ioe)
                    System.out.println(ioe.getMessage());
my text file look like in this format
mind
hate
Abhor
Bigot
narrow
prejudiced
person
Counterfeit
fake
false
give
voting
rights
Hamper
hinder
obstruct
Kindle
to
start
fire
harmful
poisonous
lethal

Next time when posting code, please use code tags: http://forum.java.sun.com/help.jspa?sec=formatting
A RandomAccessFile has nothing to do with getting a (pseudo) random line number from a file.
You should also split things up in separate methods:
- a method for counting the number of lines in a file;
- a method to get the N-th line from a file.
In your main method, you call the method which counts the number of lines N in a file and then generate a (pseudo) random number between 1 and N. Use the java.util.Random class for this.
When you have generated that number, call the other method to get that specific line number.
Here's a small start:
import java.io.*;
import java.util.*;
public class Main {
    public static String getLineNumber(int number) throws FileNotFoundException {
        // your code here
    public static int countLines(String fileName) throws FileNotFoundException {
        // your code here
    public static void main(String[] args) throws Exception {
        int numberLines = countLines("word.txt");
        Random generator = new Random();
        int randomNumber = generator.nextInt(numberLines)+1;
        String randomLine = getLineNumber(randomNumber);
        System.out.println("Line "+randomNumber+" = '"+randomLine+"'");
}In both methods, you can use the java.util.Scanner class to read lines from the file.
Have a look at the API docs of the Scanner class:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html (including code samples!)
Good luck.

Similar Messages

  • Reading a Random Line from a Text File

    Hello,
    I have a program that reads from a text file words. I currently have a text file around 800KB of words. The problem is, if I try to load this into an arraylist so I can use it in my application, it takes wayy long to load. I was wondering if there was a way to just read a random line from the text file.
    Here is my code, and the text file that the program reads from is called 'wordFile'
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class WordColor extends JFrame{
         public WordColor(){
              super("WordColor");
              setSize(1000,500);
              setVisible(true);
              add(new WordPanel());
         public static void main(String[]r){
              JFrame f = new WordColor();
    class WordPanel extends JPanel implements KeyListener{
         private Graphics2D pane;
         private Image img;
         private char[]characterList;
         private CharacterPosition[]positions;
         private int charcounter = 0;
         private String initialWord;
         private File wordFile = new File("C:\\Documents and Settings\\My Documents\\Java\\projects\\WordColorWords.txt");
         private FontMetrics fm;
         private javax.swing.Timer timer;
         public final static int START = 20;
         public final static int delay = 10;
         public final static int BOTTOMLINE = 375;
         public final static int buffer = 15;
         public final static int distance = 4;
         public final static Color[] colors = new Color[]{Color.red,Color.blue,Color.green,Color.yellow,Color.cyan,
                                                                          Color.magenta,Color.orange,Color.pink};
         public static String[] words;
         public static int descent;
         public static int YAXIS = 75;
         public static int SIZE = 72;
         public WordPanel(){
              words = readWords();
              setLayout(new BorderLayout());
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              setFocusable(true);
              addKeyListener(this);
              timer = new javax.swing.Timer(delay,new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        YAXIS += 1;
                        drawWords();
                        if (YAXIS + descent - buffer >= BOTTOMLINE) lose();
                        if (allColorsOn()) win();
         public void paintComponent(Graphics g){
              super.paintComponent(g);
              if (img == null){
                   img = createImage(getWidth(),getHeight());
                   pane = (Graphics2D)img.getGraphics();
                   pane.setColor(Color.white);
                   pane.fillRect(0,0,getWidth(),getHeight());
                   pane.setFont(new Font("Arial",Font.BOLD,SIZE));
                   pane.setColor(Color.black);
                   drawThickLine(pane,getWidth(),5);
                   fm = g.getFontMetrics(new Font("Arial",Font.BOLD,SIZE));
                   descent = fm.getDescent();
                   distributePositions();
                   drawWords();
                   timer.start();
              g.drawImage(img,0,0,this);
         private void distributePositions(){
              int xaxis = START;
              positions = new CharacterPosition[characterList.length];
              int counter = 0;
              for (char c: characterList){
                   CharacterPosition cp = new CharacterPosition(c,xaxis, Color.black);
                   positions[counter] = cp;
                   counter++;
                   xaxis += fm.charWidth(c)+distance;
         private void drawThickLine(Graphics2D pane, int width, int thickness){
              pane.setColor(Color.black);
              for (int j = BOTTOMLINE;j<BOTTOMLINE+1+thickness;j++){
                   pane.drawLine(0,j,width,j);
         private void drawWords(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              drawThickLine(pane,getWidth(),5);
              for (CharacterPosition cp: positions){
                   int x = cp.getX();
                   char print = cp.getChar();
                   pane.setColor(cp.getColor());
                   pane.drawString(""+print,x,YAXIS);
              repaint();
         private boolean allColorsOn(){
              for (CharacterPosition cp: positions){
                   if (cp.getColor() == Color.black) return false;
              return true;
         private Color randomColor(){
              int rand = (int)(Math.random()*colors.length);
              return colors[rand];
         private void restart(){
              charcounter = 0;
              for (CharacterPosition cp: positions){
                   cp.setColor(Color.black);
         private void win(){
              timer.stop();
              newWord();
         private void newWord(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              repaint();
              drawThickLine(pane,getWidth(),5);
              YAXIS = 75;
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              distributePositions();
              charcounter = 0;
              drawWords();
              timer.start();
         private void lose(){
              timer.stop();
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              pane.setColor(Color.red);
              pane.drawString("Sorry, You Lose!",50,150);
              repaint();
              removeKeyListener(this);
              final JPanel p1 = new JPanel();
              JButton again = new JButton("Play Again?");
              p1.add(again);
              add(p1,"South");
              p1.setBackground(Color.white);
              validate();
              again.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        remove(p1);
                        addKeyListener(WordPanel.this);
                        newWord();
         private String getWord(){
              int rand = (int)(Math.random()*words.length);
              return words[rand];
         private String[] readWords(){
              ArrayList<String> arr = new ArrayList<String>();
              try{
                   BufferedReader buff = new BufferedReader(new FileReader(wordFile));
                   try{
                        String line = null;
                        while (( line = buff.readLine()) != null){
                             line = line.toUpperCase();
                             arr.add(line);
                   finally{
                        buff.close();
              catch(Exception e){e.printStackTrace();}
              Object[] objects = arr.toArray();
              String[] words = new String[objects.length];
              int count = 0;
              for (Object o: objects){
                   words[count] = (String)o;
                   count++;
              return words;
         public void keyPressed(KeyEvent evt){
              char tempchar = evt.getKeyChar();
              String character = ""+tempchar;
              if (character.equalsIgnoreCase(""+positions[charcounter].getChar())){
                   positions[charcounter].setColor(randomColor());
                   charcounter++;
              else if (evt.isShiftDown()){
                   evt.consume();
              else{
                   restart();
              drawWords();
         public void keyTyped(KeyEvent evt){}
         public void keyReleased(KeyEvent evt){}
    class CharacterPosition{
         private int xaxis;
         private char character;
         private Color color;
         public CharacterPosition(char c, int x, Color col){
              xaxis = x;
              character = c;
              color = col;
         public int getX(){
              return xaxis;
         public char getChar(){
              return character;
         public Color getColor(){
              return color;
         public void setColor(Color c){
              color = c;
    }

    I thought that maybe serializing the ArrayList might be faster than creating the ArrayList by iterating over each line in the text file. But alas, I was wrong. Here's my code anyway:
    class WordList extends ArrayList<String>{
      long updated;
    WordList readWordList(File file) throws Exception{
      WordList list = new WordList();
      BufferedReader in = new BufferedReader(new FileReader(file));
      String line = null;
      while ((line = in.readLine()) != null){
        list.add(line);
      in.close();
      list.updated = file.lastModified();
      return list;
    WordList wordList;
    File datFile = new File("words.dat");
    File txtFile = new File("input.txt");
    if (datFile.exists()){
      ObjectInputStream input = new ObjectInputStream(new FileInputStream(datFile));
      wordList = (WordList)input.readObject();
      if (wordList.updated < txtFile.lastModified()){
        //if the text file has been updated, re-read it
        wordList = readWordList(txtFile);
        ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
        output.writeObject(wordList);
        output.close();
    } else {
      //serialized list does not exist--create it
      wordList = readWordList(txtFile);
      ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
      output.writeObject(wordList);
      output.close();
    }The text file contained one random sequence of letters per line. For example:
    hwnuu
    nhpgaucah
    zfbylzt
    hwnc
    gicgwkhStats:
    Text file size: 892K
    Serialized file size: 1.1MB
    Time to read from text file: 795ms
    Time to read from serialized file: 1216ms

  • Convert a line read from text file into string

    how to convert a line from text file into string?
    i know how to convert to numbers,
    private int  parseLine1(String line) {
              StringTokenizer tokenizer = new StringTokenizer(line);
                  value1 = Integer.valueOf(tokenizer.nextToken()).intValue();
                  value2 = Integer.valueOf(tokenizer.nextToken()).intValue();
                 return value1;
                     }but what about charactrs?

    ok, here is my problem, i have a file with a bunch of Xs in it but position function doesn't return a correct value, what's going wrong?
    private int positioni(){
           int i=0;
           int j=0;
           int b=0;
           String line="";
            while(line!= null){
                for(int a=0; a<line.length(); a++){
                    if(line.charAt(a)=='X'){
                        i=a;}
                b++;
                j=b;
                t=line.length();
                line=read(gridFileN);
           return i;
    private String read(String ggridFileN){
             TextStreamReader ggridFile = new TextStreamReader(ggridFileN);
             return ggridFile.readLine();

  • Reading one line from a text file into an array

    i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
    public static void readAndProcessData(FileInputStream stream){
         InputStreamReader iStrReader = new InputStreamReader (stream);
         BufferedReader reader = new BufferedReader (iStrReader);
         String line = "";          
         try{
         int i = 0;
              while (line != null){                 
                   names[i] = reader.readLine();
                   score[i] = reader.readLine();
                   line = reader.readLine();
                   i++;                
              }catch (IOException e){
              System.out.println("Error in file access");
    this section calls it:
    try{                         
         FileInputStream stream = new FileInputStream("ISU.txt");
              HighScore.readAndProcessData(stream);
              stream.close();
              names = HighScore.getNames();
              scores = HighScore.getScores();
         }catch(IOException e){
              System.out.println("Error in accessing file." + e.toString());
    it gives me an array index out of bounds error

    oh wait I see it when I looked at the original quote.
    They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens.

  • How to read every line from a text file???

    How can i read every line from my text file ("eka.txt")
    now it only reads the first line and prints it out.
    What is wrong with this?
    import java.io.*;
    import java.util.*;
    class Testi{
         public static void main(String []args)throws IOException {
         BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
    File inputFile = new File ("eka.txt");
    FileReader fis =new FileReader(inputFile);
    BufferedReader bis = new BufferedReader(fis);
    String test=bis.readLine();
    String tmp= "";
    while((bis.readLine().trim() != null)) {
    int spacefound=0;
    int l=test.indexOf(" ");
         for(int i=0;i<test.length();i++){
         char c=test.charAt(i);
         if(c!=' ') tmp+=""+c;
         if(c==' ' && (spacefound<1) && !(tmp.equals(""))){
         tmp+=""+c;
         spacefound++;
         if(tmp.length()==l) {
         System.out.println(tmp);
         tmp="";
         spacefound=0;
         if(tmp.length()<l){
         for(int i=0;i<=(l-tmp.length());i++)
         tmp+=""+' ';
         System.out.println(tmp);

    Try this code, Hope it servers your purpose.
    import java.io.*;
    import java.util.*;
    class Testi {
         public static void main(String []args)throws IOException {
              BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
              File inputFile = new File ("Eka.txt");
              FileReader fis =new FileReader(inputFile);
              BufferedReader bis = new BufferedReader(fis);
              String test=bis.readLine();
              while(test != null) {
                   StringTokenizer st = new StringTokenizer(test," ");
                   while(st.hasMoreTokens())
                        System.out.println(st.nextToken());
                   test = bis.readLine();
    }Sudha

  • How to read some lines from a text file using java.

    hi,
    i m new to java and i want to read some lines from a text file based on some string occurrence in the file. This file to be read in steps.
    we only want to read the file upto the first Occurrence of "TEXT" string.
    How to do it ,,,
    Kinldy give the code
    Regards,
    Sagar
    this is the text file
    dfgjdjj
    sfjhjkd
    ghjkdg
    hjkdgh TEXT
    ikeyt
    ujt
    jk
    tyk TEXT
    rukl
    r

    Hendawy wrote:
    Since the word "TEXT" is formed of 4 letters, you would read the text file 4 bytes by four bytes. Wrong on two counts. First, the file may not be encoded 1 byte per character. It could be utf-16 in which case it would be two byte per character. Second, even if it were 1 byte per character, the string "Text" may not start on a 4 byte boundary.
    Consider a FileInputStream object "fis" that points to your text file. use fis.read(byte[] array, int offset, int len) to read every four bytes. Convert the "TEXT" String into a byte array "TEXT".getBytes(), and yous the Arrays class to compare the equality of the read bytes with your "TEXT".getBytes()Wrong since it relies on my second point and will fail when fis.read(byte[] array, int offset, int len) does not read 4 bytes (as is no guaranteed to). Check the Javadoc. Also, the file may not be encoded with the default character encoding.
    The problem is easily solved by reading a line at a time using a BufferedReader wrapping an InputStreamReader wrapping a FileInputStream and specifying the correct character encoding.
    Edited by: sabre150 on Apr 29, 2009 2:13 PM

  • Read the first word of each line in a text file

    i need to read the first word of each line of a text file.
    i know of line.split() but not actually sure how i would go about using it
    Any help most appreciated
    Many Thanks
    Ben

    Hi thanks for the reply!
    this is what i tried... and it still doesn't get me the first word of each line!
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.io.*;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import java.util.Calendar;
    import java.util.Scanner;
    import java.util.Vector;
    import java.text.SimpleDateFormat;
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    import java.io.BufferedReader;
    public class testing {
         Vector progs=new Vector();
         Vector rand=new Vector();
         String[] tmp = new String [2];
         String str;
         String str2="ewerwer";
         String str3;
         public void programTest()
                   try
                             BufferedReader in = new BufferedReader(new FileReader("progList.log"));
                             while ((str = in.readLine()) != null)
                                  progs.add(str);
                        catch(IOException e)
                             System.out.println("cannot read file");
         //////THE ISSUES IS HERE....I WANT TO GET THE FIRST WORD FROM EACH LINE OF THE FILE!!!     
              try
                             BufferedReader in2 = new BufferedReader(new FileReader("eventLog.log"));
                             while ((str = in2.readLine()) != null)
                                  tmp = str.split(" ");
                                  System.out.println(tmp[0]);
                        catch(IOException e)
                             System.out.println("cannot read file");
    public static void main(String[] args)
                 testing B = new testing();
                 B.programTest();
               //  B.fileToVector();
                 //B.LoginWindow();
               //B.anomDetect();
    }//end class

  • Program to read only specific words in each Line in a text file

    Hi
    I have a question
    I need to write a program where the program must read only specific words in each line
    I will give you an example...
    PSAPPSRV.21201      1-42 13.35.54 238.360 Cur#1.HDEV RC=0 Dur=0.000 COM Stmt=SELECT VERSION FROM PSVERSION WHERE OBJECTTYPENAME = 'SYS'
    PSAPPSRV.21201      1-43 13.35.54 0.040 Cur#2.HDEV RC=0 Dur=0.000 COM Stmt=SELECT STYLESHEETNAME FROM PSOPTIONS
    These are two lines in my text file...now I need to read only the SQL statements present that is both SELECT statements.. Can you please suggest a method.......

    My first reaction to the question is why would you want such thing, but may be I am unknown :)
    Assuming you have the text as string, I mean
    String str = "PSAPPSRV.21201 1-42 13.35.54 238.360 Cur#1.HDEV RC=0 Dur=0.000 COM Stmt=SELECT VERSION FROM PSVERSION WHERE OBJECTTYPENAME = \'SYS\'";you can obtain the sql statement using substring method like
    String result = str.substring(str.indexOf("SELECT")); Again I assume there is no word SELECT preceding and the word SELECT is all caps.

  • How do i read complete line from a text file in j2me?????

    how do i read complete line from a text file in j2me????? I wanna read file line by line not char by char..Even i tried with readUTF of datainputstream to read word by word but i got UTFDataFormatException.. Please solve my problem.. Thanks in advance..

    That is not my problem . i already read it char by char.. i am getting complete line..But this process is taking to much time..So thats why i directly wanna read complete line or word to save time..

  • Read every 5th (or so) line from a text file.

    How to create software in LabView 6.1 that can do the following:
    1. Read a text file. The date (time stamp, and four numbers – separated by “,”) are stored in lines.
    2. Read every 5th (or so) line. How to read EOF caracter?
    3. Write data (lines) in a new file.

    Quick answer : if your file is not too large, load it in memory as a 1D array of strings, then use the "Decimate array" function, convert back the string array into a spreadsheet string and save.
    See the attached jpeg
    CC
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    Decimate Text file.jpg ‏17 KB

  • Read specified line from a text file

    Hi,
    I am trying to read a specific line from a text file. I don't want to read all of it but just this specific line... say line number 2. Is there a method built-in in java or should I code this myself?
    Thanks and regards,
    Krt_Malta

    Krt_malta wrote:
    I am trying to read a specific line from a text file. I don't want to read all of it but just this specific line... say line number 2. Is there a method built-in in java or should I code this myself?Is there anything in your use case that precludes using the offset of the start of the line rather than the line number?

  • How to only read the last line in the text file by using BufferedReader ?

    Dear all,
    Hello, I am new to Java. Do anybody know how to read the last line (this is the last record) in the text file.The method I am now using is reading from the first line until I reach the last line in the text file. Thank you!!
    BufferedReader br = new BufferedReader(new FileReader("c:\\sdk1.4.1\\bin\\dbExport.txt"));
    DataInputStream in = new DataInputStream(new FileInputStream("c:\\sdk1.4.1\\bin\\dbExport.txt"));
    String input;
    String firstinput;
    String secondinput;
    int count=90;
    int year=1955;
    while ((input = br.readLine()) != null) {
    firstinput = input.substring(0, 10);
    secondinput = input.substring(10);
    String insertStore1 = ("INSERT INTO AUTHORS " +
    "VALUES ('" + count + "', '" + firstinput + "', '" + secondinput + "', 1955)");
    System.out.println(insertStore1);
    int result = stmt.executeUpdate(insertStore1);

    I suppose you could use a java.io.RandomAccessFile.

  • How to scan/ read a text file, pick up only lines you wanted.

    I'm new to Labview, I trying to wire a VI which can read a text file
    example below:
    Example: My Text File:
    1 abcd
    2 efgh
    8 aaaa
    1 uuuu
    and pick out only any line which start with number 1 (i.e 1 abcd)
    then output these 2 lines out to a a new text file?
    Thanks,
    Palmtree

    Hi,
    How do you creat your text files? Depending on the programm, there is added characters in the beginning and at the and of the file. So here you will find a VI to creat "raw" text files.
    To debug your VIs, use the probs and breakpoints, so you can solve the problem by your self or give an more accurate description of it.
    There is also the VI that read a integer and two strings  (%d %s %s)
    Attachments:
    creat text file.vi ‏9 KB
    read_from_file.vi ‏14 KB

  • Reading a text file line by line and splitting each line into an array

    I have a text file that I want to read in line by line and within each line, I want to do some processing. I have a file like the following:
    apples||oranges||bananas||grapes
    cars||trucks||planes||boats
    And I want to end up with an array such that
    First...
    item(0) = apples
    item(1) = oranges
    item(2) = bananas
    item(3) = grapes
    Then move onto the next line with item getting cleared each time. Can anyone offer any ideas on how do to this? I am unclear on reading line by line and then also splitting into an array as I am new to this.
    Thanks.

    For reading a text file in line by line, you want to use a FileReader (java.io.FileReader)
    If you wrap it in a Buffered reader, you can call readLine() and get the file one line at a time.
      File file = new File("C:\myFile.txt");
      BufferedReader in = new BufferedReader(new FileReader(file));
      String s = in.readLine();
      while (s != null){
        // string handling here
        s = in.readLine();
      }For the second part, you probably want to look at the method String.split() which should split your string up into an array for you. Check out the API for java.lang.String
    Check out the

  • Using ArrayList to store Lines in a text File

    Hey Guys,
    I have the following program that I am using to read a text file and store each word in each line in an ArrayList. But I am getting the following error;
    Exception in thread "main" java.util.ConcurrentModificationException
         at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
         at java.util.AbstractList$Itr.next(AbstractList.java:420)
         at bus.OrderReader.parseLine(OrderReader.java:50)
         at bus.OrderReader.main(OrderReader.java:32) The code is as follows;
    package bus;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.util.Scanner;
    import java.util.Collection;
    import java.util.ArrayList;
    import java.util.Iterator;
    public class OrderReader {
        static Collection bread = new ArrayList();
        static Collection filling = new ArrayList();
        static Iterator iter1 = filling.iterator();
        static Iterator iter2 = bread.iterator();
         private static int counter;
    public static void main(String args[]){
        Scanner s = null;
        try {
            s = new Scanner(new BufferedReader(new FileReader("/Users/admin/Documents/workspace2/OBS/WebContent/WriteMe.txt")));
            s.useDelimiter("\r");
            while(s.hasNext()) {
                parseLine(s.next());
                counter++;
            s.close();
        catch(FileNotFoundException e) {
            System.out.println("cannot find the file");
            //ignore for now
        public static void parseLine(String line) {
            Scanner lineScanner = new Scanner(line);
            lineScanner.useDelimiter("#");
                bread.add(lineScanner.next());
                filling.add(lineScanner.next());
                System.out.println(iter1.next());
                System.out.println(iter2.next());
    }I do not understand why this does not work. Can someone please point me in the right direction?
    Thank You
    Jaz

    Instead of doing this:
    bread.add(lineScanner.next());
    filling.add(lineScanner.next());
    System.out.println(iter1.next());
    System.out.println(iter2.next());where presumably you're just printing what you just
    barely added, do this:
    Object breadObject = lineScanner.next();
    Object fillingObject = lineScanner.next();
    bread.add(breadObject);
    filling.add(fillingObject);
    System.out.println(breadObject);
    System.out.println(fillingObject);
    And get rid of the now unused iterators.Im not sure I understand quiet what is happening here. Are you creating a primitive data type of type Object and then storing all the values in that variable?
    why would I do this when this only allows me to view the very last element that was added to the list? I want to view the entire list.
    Thanks
    Jaz
    Message was edited by:
    DontKnowJack

Maybe you are looking for

  • I had to install a new hard drive. How do I get Lion to reinstall w/o paying $29.95 again?

    I had to install a new hard drive. How do I get Lion to reinstall w/o paying $29.95 again?

  • How to-- update adobe to watch videos

    http://www.adobe.com/misc/unsupported_device.html How in the world do I know my phone is smart and yet it is acting incapable of the most basic smartphone function? Glitch of the day right? This has been unsupported for a couple months. I'm not going

  • Keep filter in adf richtable after refreshing

    Hi, i use jdeveloper 11g (11.1.1.0.1) with toplink (no ADF BC) and have the following Problem: I have a table with enabled builtin filtering. If i filter the data and make a refresh the filter is gone. The refresh is achieved by a call to the Execute

  • Connecting  external device (scanner & fax ) to my SAP system

    HI , My external device system is not connecting with my sap system .... pls suggest what configuration is required. 1. I have installed scanner software on my computer..... 2. the scanner is transfering the scanned image to my system 3. But it could

  • NLS_COMP and comparison

    Hello everyone, Can someone explain me the impact of setting NLS_COMP to ANSI or LINGUISTIC on comparisons in SQL Statements? In the documentation it is writen that: "Comparisons for all SQL operations in the WHERE clause and in PL/SQL blocks should