简体   繁体   中英

How do you initialize an array inside a while loop and define it outside?

I need to be able to assign an array to a .txt file so I need to reference the variable "s" outside the while loop. Even after I define and initialize the variable I still get an error when I initialize in the while loop. What am I doing wrong?

 package vp.sga_form_generator;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;


public class GUI extends JFrame{
    public GUI() throws FileNotFoundException {

        super("SGA Form Creator - Viper Productions");
            setSize(1000,800);
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setLayout(new GridLayout(30, 2));

            //Opens File
            Scanner names = new Scanner(new File("names.txt"));

    //      String name1 = names.next();
            String[] s;
            while(names.hasNext()){
                s = {names.next()};
            }

            JComboBox names1 = new JComboBox(s);
            JComboBox names2 = new JComboBox(s);

            add(names1);
            add(names2);


    }

}
  1. {names.next()}; is only allowed when you initialize a String[] so you can say something like String[] s = {"bla","bli","blu"}
  2. The problem is that String[] is not initialized
  3. You can not init the String with the appropriate size sinze you dont know it. So String[] is not the structure of choice
  4. If you need to use String[] then you must do generate a second String[] and copy back and forth each time you add one element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM