-2

Hello, i am making a alarm program and i am having trouble with gathering data from the db.txt file i tried to do System.out.println(array[]); but it didn't do anything i was wondering if it is possible to create an int lets call it number and use it to choose an array to print like this System.out.println(array[number]); anyways thats what i was trying to do and it still returned null. Here is my java cod:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import javax.swing.*;

public class alarm {
public static JFrame window;
public JPanel p;
public RandomAccessFile rw;
    alarm() throws IOException {
        window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);
        window.setSize(600, 600);
        p = new JPanel();
        p.setLayout(null);
        try {
            rw = new RandomAccessFile("db.txt", "rw");
            int loop = 0;
            int insertNumber = 0;
            int[] numberArray = new int[1000000];
            String[] name = new String[1000000];
            String[] desc = new String[1000000];
            String[] date = new String[1000000];
            String row = null;
            while(loop == 0) {
                 row = rw.readLine();
                 if(row == "/") {
                    insertNumber = insertNumber + 1;
                    insertNumber = numberArray[insertNumber];
                    name[insertNumber] = rw.readLine();
                    desc[insertNumber] = rw.readLine();
                    date[insertNumber] = rw.readLine();
                }
               if(row == null) {
                    insertNumber = 0;
                    loop = 1;   
                }
        }
        System.out.println("Arrays loaded");
            while(loop == 1) {
            insertNumber = insertNumber + 1;
            if(name[insertNumber] == null) {
                loop = 2;
            }
            System.out.println(name[insertNumber]);
        } 
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) throws IOException {
    new alarm();
    window.setVisible(true);
}

}

user207421
  • 289,834
  • 37
  • 266
  • 440
Marcus Mardis
  • 83
  • 1
  • 1
  • 8

1 Answers1

1

You increment index insertNumber to the next value, which is null in the array, then you print it.

while(loop == 1) {
     insertNumber = insertNumber + 1; // insertNumber is incr. before index 0 is printed
     if(name[insertNumber] == null) {  // Always true if size < 2 elements
        loop = 2;
     }
     System.out.println(name[insertNumber]); //prints null is size < 2
}     

Try instead:

for(String element : name) {
     System.out.println(element + " ");
}

Additionally, this line is incorrect:

insertNumber = numberArray[insertNumber];
Don Scott
  • 2,608
  • 1
  • 22
  • 39