Reputation: 380
I'd like get some help to solve the issue with having a new line after every fifth number. I put random numbers between 1 and 90 into an array list and then write it into a file. (Later I'd like to sort the list and everything like that hence I'm using an ArrayList instead of writing the numbers immediately into the file.)
public class Lotto {
static ArrayList<Integer> list = new ArrayList();
public static void main(String[] args) throws IOException {
randomNumber();
fileReader();
}
public static void printHeader() {
System.out.println("Week"
+ "|Numbers "
+ "\n"
+ "----+"
+ "-----------------------+");
}
public static void randomNumber() {
int num;
int n = 5;
// String str = String.valueOf(num);
list = new ArrayList<>();
try {
FileWriter writer = new FileWriter("/Users/xyz/desktop/lotto2010.txt");
BufferedWriter bw = new BufferedWriter(writer);
for (int i = 1; i <= 260; i++) {
double number = Math.random() * 90;
num = (int) number;
list.add(num);
if((i % n) == 0) bw.newLine();
}
bw.write(list.toString());
bw.close();
} catch (IOException ex) {
System.out.println("Couldn't write the file or directory doesn't exist" + ex.getMessage());
}
}
public static void fileReader() throws IOException {
FileReader fileReader = new FileReader("/Users/xyz/desktop/lotto2010.txt");
String allText;
try (PrintWriter writer = new PrintWriter("/Users/xyz/desktop/lotto2011.txt")) {
BufferedReader br = new BufferedReader(fileReader);
allText = br.readLine();
writer.print(allText);
}
System.out.println(allText);
}
}
Upvotes: 0
Views: 1338
Reputation: 21
PsuedoCode :
for (int i = 0; i < array.size(); i++{
println(array(i));
if(i % 5 == 0){
println();
}
}
Upvotes: 1
Reputation: 1478
This will do the needful, what you are doing is that, while generating numbers you are adding it to the list and writing a newline at the same time after every 5 numbers. Though you should do it while iterating through the array. Before iteration, you can modify your array using sorting or anything
FileWriter writer = new FileWriter("/Users/xyz/desktop/lotto2010.txt");
BufferedWriter bw = new BufferedWriter(writer);
for (int i = 1; i <= 260; i++) {
double number = Math.random() * 90;
num = (int) number;
list.add(num);
}
// optional step like sorting, as per your question
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
bw.write(list.get(i).toString());
if(i!=0 && i % n == 0) {
bw.newLine();
} else {
bw.write(", ");
}
}
bw.close();
getting output like this -
9, 10, 10, 10, 11
11, 11, 12, 12, 13
13, 13, 13, 13, 13
14, 14, 14, 14, 15
16, 16, 17, 17, 17
18, 18, 19, 19, 19
19, 20, 21, 21, 21
22, 23, 23, 23, 23
23, 24, 24, 24, 25
26, 26, 26, 26, 26
.............
Upvotes: 0