How can I read a textfile of numbers and store it in arraylist of double? The file has multiple lines of numbers. Also how can I retrieve a random number from the arraylist?
I can store it in a file of string. But when I read the file and display it, it shows the full line of numbers instead of just one number.
public static void main(String[] args) throws IOException
{
ArrayList<String> list = new ArrayList<>();
// New BufferedReader.
BufferedReader reader = new BufferedReader(new FileReader(
"filename.txt"));
// Add all lines from file to ArrayList.
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
list.add(line);
}
// Close it.
reader.close();
// Print size of ArrayList.
System.out.println("Lines: " + list.size());
// Print each line.
for (String line : list) {
System.out.println(line);
}
Random rand = new Random();
String randomElement = list.get(rand.nextInt(list.size()));
System.out.println(randomElement);
}
I expect the output of 0.48. But the actual output is 0.48 0.66 0.32 0.55 0.21
Break the line by spaces as follow: line.split("\\s+"), so you will have array of String which contains number (0.48)
List<Double> list = new ArrayList<>();
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
String[] stringDoubles = line.split("\\s+");
for(int i=0;i<stringDoubles.length;i++){
list .add(Double.parseDouble(stringDoubles[i]))
}
}
Updated the program as per your needs.
public class Main {
public static void main(String[] args) throws IOException
{
try {
List<Double> list = new ArrayList<>();
// New BufferedReader.
BufferedReader reader = new BufferedReader(new FileReader(
"filename.txt"));
// Add all lines from file to ArrayList.
String line = null;
while ((line = reader.readLine()) != null) {
list.addAll(Arrays.asList(line.split("\\s+")).stream().map(p -> Double.parseDouble(p.trim())).collect(Collectors.toList()));
}
// Close it.
reader.close();
Random rand = new Random();
Double randomElement = list.get(rand.nextInt(list.size()));
System.out.println(randomElement);
}catch (IOException e){
System.out.println(e);
}
}
}
I would try something like this. Assuming you don't need the strings at all and you have a working file without letters ore somthing else equaly distribing.
List<Double> list = new ArrayList<>();
String line = rader.readLine();
while (line != null) {
list.add(Double.valueOf(line));
line = reader.readLine();
};
If you want to retrive an random member i would do it whith:
list.get((int)(Math.random(list.size()));
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.