I'm trying to make a 2D array using the following:
The output looks as follows:
230 234 240 245 311
334 396 398 402 415
415 415 425 445 450
450 451 462 467 488
496 513 516 521 534
548 553 560 566 567
570 571 575 579 579
591 597 611 618 620
629 630 638 648 662
where the user in this case would have entered 5 as the number of columns. They can choose any number up to a specific number! This means I can not just enter 5 as the column number, but it must be based off their input. Snippets of my code are shown here (pulled out of different packages/classes, but the only applicable code for this specific problem):
public class NumberGenerator {
private ArrayList<Integer> numbers;
private Random randomGenerator;
System.out.print("\nEnter the number of numbers (maximum 5000) you would like: ");
input = this.scan.nextLine();
int userOption = Integer.parseInt(input);
while (userOption > 5000 || userOption < 1) {
System.out.print("Enter the number of numbers (maximum 5000) you would like: ");
input = this.scan.nextLine();
userOption = Integer.parseInt(input);
} this.userNumber.generateNumbers(userOption);
System.out.print("\nEnter the number of numbers per line (maximum 12): ");
input2 = this.scan.nextLine();
int userOption2 = Integer.parseInt(input2);
while (userOption2 > 12 || userOption2 < 1) {
System.out.print("Enter the number of numbers per line (maximum 12): ");
input2 = this.scan.nextLine();
userOption2 = Integer.parseInt(input2);
} this.userColumns = (userOption2);
The rest of my coding and solutions are tested and running, so I know these are working snippets of code. Just need some help figuring out how to code a new method to call the 2D array as shown for formatting. Any help would be greatly appreciated.
I am assuming you generated the required list of numbers and you have the required column size. Then you can print the out put using the following method:
static void format(List<Integer> numberList,int columnSize){
int totalLength = numberList.size();
int index=0;
for(; (index+columnSize) <= totalLength ;index+=columnSize ){
System.out.println(String.format(getRowFormat(columnSize), numberList.subList(index, index+columnSize).toArray()));
//or use this
//System.out.printf(rowFormat.toString()+"\n", numberList.subList(i, i+columnSize).toArray());
}
if(index <= totalLength){//to handle pending values if any.
System.out.println(String.format(getRowFormat(totalLength - index), numberList.subList(index, totalLength).toArray()));
}
}
//handling format
private static String getRowFormat(int columnSize) {
StringBuilder rowFormat = new StringBuilder();
for(int j=0;j<columnSize;j++){
rowFormat.append("%10d");
}
return rowFormat.toString();
}
call this from your code as:
format(numbers,this.userColumns);
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.