2016-09-22 2 views
0

Как распечатать перетасованный массив ArrayList? Это то, что у меня есть до сих пор:Как распечатать перетасованный массив ArrayList?

public class RandomListSelection { 

    public static void main(String[] args) { 

     String currentDir = System.getProperty("user.dir"); 
     String fileName = currentDir + "\\src\\list.txt"; 

     // Create a BufferedReader from a FileReader. 
     BufferedReader reader = null; 
     try { 
      reader = new BufferedReader(new FileReader(
        fileName)); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     // Create ArrayList to hold line values 
     ArrayList<String> elements = new ArrayList<String>(); 

     // Loop over lines in the file and add them to an ArrayList 
     while (true) { 
      String line = null; 
      try { 
       line = reader.readLine(); 

       // Add each line to the ArrayList 
       elements.add(line); 

      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      if (line == null) { 
       break; 
      } 
     } 

     // Randomize ArrayList 
     Collections.shuffle(elements); 

     // Print out shuffled ArrayList 
     for (String shuffedList : elements) { 
      System.out.println(shuffedList); 
     } 


     // Close the BufferedReader. 
     try { 
      reader.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 
+0

Я хочу, чтобы иметь возможность добавлять строки из моего файла в ArrayList, так что я инициализируюсь его в петле. Это плохо? Я немного изменил код. – santafebound

+0

OK, теперь вы печатаете перетасованный ArrayList. В чем вопрос, опять? –

+0

Хорошо, я понял это выше. Взглянуть. – santafebound

ответ

2

Для того чтобы удалить единственное нулевое значение, вы должны только читать (и добавлять в коллекцию) до тех пор, пока существуют строки.

В вашем коде вы устанавливаете строку null, ваш читатель не может читать что-либо еще и добавляет String (который по-прежнему null) в список. После этого вы проверяете, есть ли строка String и оставьте свой цикл!

Изменить петлю на это:

// Loop over lines in the file and add them to an ArrayList 
String line=""; 
try{ 
    while ((line=reader.readLine())!=null) { 
     elements.add(line); 
    } 
}catch (IOException ioe){ 
    ioe.printStackTrace(); 
} 
1

Попробуйте это.

public static void main(String[] args) throws IOException { 
    String currentDir = System.getProperty("user.dir"); 
    Path path = Paths.get(currentDir, "\\src\\list.txt"); 
    List<String> list = Files.readAllLines(path); 
    Collections.shuffle(list); 
    System.out.println(list); 
} 
Смежные вопросы