print 2 dimentional array center aligned - java

Hi I am trying to print a two dimensional array that is center aligned but the numbers point to the memory cell if im correct. How would I go about getting them to print the actual numbers, Ive tried creating a display method and that didnt work. Here is my code so far. I am also going to be finding the min, max and avg after I figure this out.
import java.util.Scanner;
public class Print2DArray {
public static void main(String[] args) {
Scanner print2d = new Scanner(System.in);
System.out.println("Please enter the number of rows: ");
int rows = print2d.nextInt();
System.out.println("Please enter the number of columns: ");
int columns = print2d.nextInt();
int array[][] = new int[rows][columns];
System.out.println("\nVictor - 002017044\n");
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[x].length; y++) {
int value = (int) (Math.random() * 10000);
value = (int) (Math.round((value * 100)) / 100.0);
array[x][y] = value;
}
}
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[x].length; y++) {
printArray(array);
}
System.out.println();
}
int max = 0;
int avg = 0;
int min = 0;
System.out.println("\nMaximum: " + max + "\nAverage: " + avg
+ "\nMinimum: " + min);
}
private static void printArray(int [][] array){
int width = 6;
int leftSP = (width - array.length)/2;
int rightSP = width - array.length - leftSP;
for (int i = 0; i < leftSP; i++) {
System.out.print(" ");
}
System.out.print(array);
for (int i =0; i < rightSP; i++) {
System.out.print(" ");
}
}
}

I'm not quite sure what you mean by center aligned in this context. Centering something requires you to know how much space you are allowed to print to and then evenly distributing what you are displaying to both sides of the width/2. For example, by default, in cmd.exe you are limited to 80 characters across, but this can be changed. However, I think the core of this answer is here:
Can I find the console width with Java?
Basically, you can't center it. The best you can hope for is to left align it (or attempt to center it based on some arbitrary pre-determined width).
Based on what you wrote though, and what I see in printArray, your other issue is that you don't know how to print out a value at an index of an array. Before I address that, I must address something you wrote
but the numbers point to the memory cell if im correct
This is actually incorrect. This is the default functionality of the toString method, per the java.lang.Object#toString method:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString%28%29
Your print method should probably look like:
private static void printArray(int [][] array){
if(array == null || array.length < 1 || array[0].length < 1)
throw new IllegalArgumentException("array must be non-null, and must have a size of at least \"new int[1][1]\"");
for (int i = 0; i < array.length; i++) {
for(int j = 0; j < array[0].length; j++)
System.out.print("[" + array[i][j] + "]");
System.out.println();
}
}
EDIT:
I saw a comment you made in which you specify what you mean by center aligned. Basically you will want to record the maximum length of any int you are placing into the array, like the following:
//global max value
public static int maxLength = 0;
...
//inside of Print2DArray.main(String [] args)
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[x].length; y++) {
value = (int) (Math.round((value * 100)) / 100.0);
int numberOfDigits = String.valueOf(value).length();
if(numberOfDigits > Print2DArray.maxLength)
Print2DArray.maxLength = numberOfDigits;
array[x][y] = value;
}
}
Then you will want to adjust your printArray function's print from
System.out.print("[" + array[i][j] + "]");
to
System.out.printf("[%" + Print2DArray.maxLength + "d]", array[i][j]);

first fix bug
for (int y = 0; y < array[x].length; y++) {
printArray(array[x][y]);//chage printArray(array) to printArray(array[x][y])
}
second modify printlnArray
private static void printArray(int v){
System.out.format("%-8s",String.valueOf(v));
}
center-align
private static int[] widthes = {9,99,999,9999,99999};
private static int numberWidth(int v) {
for (int i = 0; i < widthes.length; i++) {
if(widthes[i] > v) return (i+1);
}
return -1;
}
private static void printArray(int v){
int width = 8;
int numberWidth = numberWidth(v);
int left = (width-numberWidth)/2;
int right = width - numberWidth - left;
for (int i = 0; i < left; i++) {
System.out.print(" ");
}
System.out.print(v);
for (int i = 0; i < right; i++) {
System.out.print(" ");
}
}
more reference
How to align String on console output

Related

How do I change the position of my triangle?

am trying to do this triangle using 2 arguments.
Can someone help me out and see what is wrong with my code?
I can't seems to flip it to the same as this image.
Thank you!
int width = Integer.parseInt(args[0]);
int height = Integer.parseInt(args[1]);
for (int i = 0; i < height; i++) {
int starsThisLine = (int) Math.round(width * ((i + 1) / (double) height));
int dotsBeforeStars = Math.round((width - starsThisLine));
for (int j = 0; j < width; j++) {
if (j > dotsBeforeStars) {
System.out.print(".");
} else if (j < (dotsBeforeStars + starsThisLine)) {
System.out.print("*");
} else {
System.out.println(1);
Here is one way to do it. Just create a repeat method to return the String with the proper number of characters.
int height = 10;
for (int i = 0; i < height; i++) {
System.out.println(repeat("*", height-i)+repeat(".",i));
}
public static String repeat(String a, int count) {
StringBuilder sb = new StringBuilder();
while(count-- > 0) {
sb.append(a);
}
return sb.toString();
}
Both will print
**********
*********.
********..
*******...
******....
*****.....
****......
***.......
**........
*.........
One observation. Notice the first line has all stars. But that last line does not have all dots. The same was true in your patterns too.
If you want the start and finish to look like this:
**********
..........
The loop should be as follows:
for (int i = 0; i <= height; i++) {
If you want the start and finish to look like this:
*********.
*.........
The loop should be as follows:
for (int i = 1; i < height; i++) {
Assuming that the height and width will always be the same, here is an example implementation that uses a scanner (you can change this if you want to):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int dimensions = scan.nextInt();
for(int i = 0; i < dimensions; i++){
for(int dots = 0; dots < i; dots++){
System.out.print(". ");
}
for(int stars = dimensions; stars > i; stars--){
System.out.print("* ");
}
System.out.println();
}
}
}
In this example, our outer for loop with the dimensions represents the code for each row of the triangle, in this case, if we inputted 5, 5 rows.
Then, we start with printing dots since they are on the left side. Since the number of dots goes 0 -> 1 -> 2 -> 3 -> 4, this is equivalent to what "i", or our outer loop counter is.
With the stars, the number of stars goes 5 -> 4 -> 3 -> 2 -> 1, so if we just count backwards from the number of rows to our counter variable, we can get this number.

How to display methods in the console that read from a file?

I need to be able to display the Average, ColumnTotal, Highest/Lowest in row, RowTotal. I'm not sure whether it depends on something I did in the methods themselves that has to be changed, or if I can simply that call them with the correct arguments to read from a file. The text file that it reads from basically just inputs two integers that are separated by a space on the same line, those are the arguments I would like to be able to input. I'm not entirely sure how to do this. This is just an assignment from a College text book basically amped up by my Instructor called "TwoDimArray" which I've been able to find many examples of online but none of them had the 'read from file' portion that I have to do here, they all just used a normal array input such as "int[][] array = {{22, 37, 48, 68}} for the main method. I'm going to include the entire program in order to show exactly what I need to be displayed via println. I've been thinking about how to do this for quite a few hours now and decided that I definitely need help. Any help would be greatly appreciated! Thanks ahead of time.
import javax.swing.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TwoDimArray {
private int arr[][];
public TwoDimArray() {
loadArray();
}
public void loadArray(){
/**
* loadArray() method loads user defined filename
* #return text file's contents
*/
String fileName = "";
try {
fileName = JOptionPane.showInputDialog("Enter file name: ");
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "can not open " + fileName + " to read");
return;
}
try {
Scanner in = new Scanner(new File(fileName));
int rows, cols;
rows = in.nextInt();
cols = in.nextInt();
arr = new int[rows][cols];
for(int i = 0; i < rows; ++i){
for(int j = 0; j < cols; ++j){
arr[i][j] = in.nextInt();
}
}
in.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "can not open " + fileName + " to read");
}
}
public int getArrayMaxValue(){
/**
* #return the max vale of the array
*/
int maxVal = Integer.MIN_VALUE;
for(int i = 0; i < arr.length; ++i){
for(int j = 0; j < arr.length; ++j){
if(arr[i][j] > maxVal){
maxVal = arr[i][j];
}
}
}
return maxVal;
}
public int getArrayMinValue(){
/**
* #return the minimum value of the array
*/
int minVal = Integer.MAX_VALUE;
for(int i = 0; i < arr.length; ++i){
for(int j = 0; j < arr.length; ++j){
if(arr[i][j] < minVal){
minVal = arr[i][j];
}
}
}
return minVal;
}
public static int getTotal(int[][] array) {
int total = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
total += array[row][col];
}
}
return total;
}
public static int getAverage(int[][] array) {
return getTotal(array) / getElementCount(array);
}
public static int getRowTotal(int[][] array, int row) {
int total = 0;
for (int col = 0; col < array[row].length; col++) {
total += array[row][col];
}
return total;
}
public static int getColumnTotal(int[][] array, int col) {
int total = 0;
for (int row = 0; row < array.length; row++) {
total += array[row][col];
}
return total;
}
public static int getHighestInRow(int[][] array, int row) {
int highest = array[row][0];
for (int col = 1; col < array[row].length; col++) {
if (array[row][col] > highest) {
highest = array[row][col];
}
}
return highest;
}
public static int getLowestInRow(int[][] array, int row) {
int lowest = array[row][0];
for (int col = 1; col < array[row].length; col++) {
if (array[row][col] < lowest) {
lowest = array[row][col];
}
}
return lowest;
}
public static int getElementCount(int[][] array) {
int count = 0;
for (int row = 0; row < array.length; row++) {
count += array[row].length;
}
return count;
}
public static void main(String[] args){
/**
* what to put in int[][] array to allow println of average, getrowtotal,
* etc..
*/
int[][] array = ???;
TwoDimArray twoDimArray = new TwoDimArray();
System.out.println("Max value: " + twoDimArray.getArrayMaxValue());
System.out.println("Min value: " + twoDimArray.getArrayMinValue());
System.out.println(getAverage(array));
}
}
0) Create numbers.txt in the root of your project. This is the file you will load array from. Example content as follows (2 rows, 3 columns):
2 3
1 2 3
4 5 6
1) You don't need your explicitly created int[][] array = ??? because there is already existing private int arr[][] which will be automatically loaded from file after you type it's name as intended in TwoDimArray constructor.
2) Since main method located at the same class as private int arr[][], you can access this private array without public getter/setter, and get average value like this:
// you don't need following line at all
// int[][] array = ???;
TwoDimArray twoDimArray = new TwoDimArray();
System.out.println("Max value: " + twoDimArray.getArrayMaxValue()); // Max value: 5
System.out.println("Min value: " + twoDimArray.getArrayMinValue()); // Min value: 1
// Average value
System.out.println(getAverage(twoDimArray.arr)); // 3, because 21 / 6 = 3
3) You probably got confused because getArrayMaxValue is signed as public int, and got invoked as twoDimArray.getArrayMaxValue(), whereas getAverage is public static int and must be called in different way.
I suggest marking getAverage as public int instead of public static int, and use private int arr[][] instead of int[][] array provided from arguments, so you will be able to call it the same way you do with other methods:
// Somewhere up
public int getAverage() {
return getTotal(arr) / getElementCount(arr);
}
// In your main method
System.out.println(twoDimArray.getAverage());
Basically, what you have there is a jagged array, it is not a bidimensional array. I will explain you the idea, you do the rest. That it is not a bidimensional array. This is an array of array, in each position you are pointing to a new array of int. If you never instantiated a new array on each position, then you have a position with a null value.
So going back with your question, you should read the entire line with the two integers that are on the same line. Be sure that the line in your file has in the first line 2 numbers separated by a space.
Then use the next() method to get the complete string
String line = in.next();
String[] parts = line.split(" ");
int val1 = Integer.parseInt(parts[0]);
int val2 = Integer.parseInt(parts[1]);
For this question:
what to put in int[][] array to allow println of average, getrowtotal,
int[][] array = new int[4];
array[0] = new int[] {10,20,30,40,50};
array[1] = new int[] {60,71,80,90,91};
array[2] = new int[] {1};
Hope this helps
Now, what do you think you have in array[3]? The answer is: NULL
you already read the array from file in your method loadArray...
Use it instead of trying to load the same thing again, remove static modifier from all method and use field arr instead of parameter array
private int getTotal() {
int total = 0;
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
total += arr[row][col];
}
}
return total;
}
private int getAverage() {
return getTotal() / getElementCount();
}
private int getElementCount() {
int count = 0;
for (int row = 0; row < arr.length; row++) {
count += arr[row].length;
}
return count;
}
public static void main(String[] args) {
TwoDimArray twoDimArray = new TwoDimArray();
System.out.println("Max value: " + twoDimArray.getArrayMaxValue());
System.out.println("Min value: " + twoDimArray.getArrayMinValue());
System.out.println(twoDimArray.getAverage());
}

Java set/setElementAt not setting the right value

I need to find all the permutations for a given n(user input) without backtracking.
What i tried is:
import java.util.Scanner;
import java.util.Vector;
class Main {
private static int n;
private static Vector<Vector<Integer>> permutations = new Vector<>();
private static void get_n() {
Scanner user = new Scanner(System.in);
System.out.print("n = ");
n = user.nextInt();
}
private static void display(Vector<Vector<Integer>> permutations) {
for (int i = 0; i < factorial(n) - 1; ++i) {
for (int j = 0; j < n; ++j) {
System.out.print(permutations.elementAt(i).elementAt(j) + " ");
}
System.out.println();
}
}
private static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
private static int max(Vector<Integer> permutation) {
int max = permutation.elementAt(0);
for (int i = 1; i < permutation.size(); ++i)
if (permutation.elementAt(i) > max)
max = permutation.elementAt(i);
return max;
}
// CHECKS FOR ELEMENT COUNT AND 0 - (n-1) APPARITION
public static int validate_permutation(Vector<Integer> permutation) {
// GOOD NUMBER OF ELEMENTS
if (max(permutation) != permutation.size() - 1)
return 0;
// PROPER ELEMENTS APPEAR
for (int i = 0; i < permutation.size(); ++i)
if (!permutation.contains(i))
return 0;
return 1;
}
private static Vector<Integer> next_permutation(Vector<Integer> permutation) {
int i;
do {
i = 1;
// INCREMENT LAST ELEMENT
permutation.set(permutation.size() - i, permutation.elementAt(permutation.size() - i) + 1);
// IN A P(n-1) PERMUTATION FOUND n. "OVERFLOW"
while (permutation.elementAt(permutation.size() - i) == permutation.size()) {
// RESET CURRENT POSITION
permutation.set(permutation.size() - i, 0);
// INCREMENT THE NEXT ONE
++i;
permutation.set(permutation.size() - i, permutation.elementAt(permutation.size() - i) + 1);
}
} while (validate_permutation(permutation) == 0);
// OUTPUT
System.out.print("output of next_permutation:\t\t");
for (int j = 0; j < permutation.size(); ++j)
System.out.print(permutation.elementAt(j) + " ");
System.out.println();
return permutation;
}
private static Vector<Vector<Integer>> permutations_of(int n) {
Vector<Vector<Integer>> permutations = new Vector<>();
// INITIALIZE PERMUTATION SET WITH 0
for (int i = 0; i < factorial(n); ++i) {
permutations.addElement(new Vector<>());
for(int j = 0; j < n; ++j)
permutations.elementAt(i).addElement(0);
}
for (int i = 0; i < n; ++i)
permutations.elementAt(0).set(i, i);
for (int i = 1; i < factorial(n); ++i) {
// ADD THE NEXT PERMUTATION TO THE SET
permutations.setElementAt(next_permutation(permutations.elementAt(i - 1)), i);
System.out.print("values set by permutations_of:\t");
for (int j = 0; j < permutations.elementAt(i).size(); ++j)
System.out.print(permutations.elementAt(i).elementAt(j) + " ");
System.out.println("\n");
}
System.out.print("\nFinal output of permutations_of:\n\n");
display(permutations);
return permutations;
}
public static void main(String[] args) {
get_n();
permutations.addAll(permutations_of(n));
}
}
Now, the problem is obvious when running the code. next_permutation outputs the correct permutations when called, the values are set correctly to the corresponding the vector of permutations, but the end result is a mass copy of the last permutation, which leads me to believe that every time a new permutation is outputted by next_permutation and set into the permutations vector, somehow that permutation is also copied over all of the other permutations. And I can't figure out why for the life of me.
I tried both set, setElementAt, and an implementation where I don't initialize the permutations vector fist, but add the permutations as they are outputted by next_permutation with add() and I hit the exact same problem. Is there some weird way in which Java handles memory? Or what would be the cause of this?
Thank you in advance!
permutations.setElementAt(next_permutation(permutations.elementAt(i - 1)), i);
This is literally setting the vector at permutations(i) to be the same object as permutations[i-1]. Not the same value - the exact same object. I think this the source of your problems. You instead need to copy the values in the vector.

How to print a matrix in clockwise order

There is matrix for [x][y] order. i want to print its value in clockwise order
I have tried several methods but unable to write the logic of the code. I'm trying it in java but logic is important so you can help me in any language.
When I read your post I've started to play so I'll post you my code maybe it will be halpful for you. I've did it for square if you want for rectangle one need separate stepX and stepY. SIZE would be input parameter in your case, I have it final static for test.
public class clockwise {
private static final int SIZE = 3;
public static void main(String[] args) {
// int[][] test_matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
int[][] test_matrix = {{1,2,3},{5,6,7},{9,10,11}};
int[][] direction = {{1, 0},{0, 1},{-1, 0},{0, -1}}; //{x,y}
for(int i = 0; i < SIZE; i++) {
for(int j = 0; j < SIZE; j++)
System.out.print(test_matrix[i][j] + " ");
System.out.println("");
}
int x = 0;
int y = 0;
int directionMove = 0;
int stepSize = SIZE;
boolean changeStep = true;
int stepCounter = 0;
for(int i = 0; i < SIZE*SIZE; i++) {
System.out.print(test_matrix[x][y] + " ");
stepCounter++;
if (stepCounter % stepSize == 0) {
directionMove++;
directionMove = directionMove%4;
if(changeStep) { //after first edge one need to decrees step after passing two edges
stepSize--;
changeStep = false;
} else {
changeStep = true;
}
stepCounter = 0;
}
x += direction[directionMove][0];
y += direction[directionMove][1];
}
}
}

How to organize a single array into a two-dimensional one?

I am trying to split a one dimensional array of display modes into a 2-dimensional string array, though I have encountered trouble where I got to the point of splitting the sorted array of display modes. My question: How can I split the single array, which is already sorted, into a two dimensional array? The code (Sorry about the weird variable names):
public static String[][] OrganizeDisplayModes (DisplayMode[] modes) {
int iter = 0;
int deltaIter = 0;
int rows = 0;
int columns = 0;
String[][] tobe;
//bubble sorting
for (int a = 0; a < modes.length - 1; a++) {
for(int i = 0; i < modes.length - 1; i++) {
if (modes[i].getWidth() < modes[i+1].getWidth()) {
DisplayMode change = modes[i];
modes[i] = modes[i+1];
modes[i+1] = change;
}
}
}
for(int i = 0; i < modes.length - 1; i++) {
if ((modes[i].getWidth() == modes[i+1].getWidth()) && (modes[i].getBitsPerPixel() < modes[i+1].getBitsPerPixel())) {
DisplayMode change = modes[i];
modes[i] = modes[i+1];
modes[i+1] = change;
}
}
for(int i = 0; i < modes.length - 1; i++) {
if ((modes[i].getWidth() == modes[i+1].getWidth()) && (modes[i].getFrequency() < modes[i+1].getFrequency())) {
DisplayMode change = modes[i];
modes[i] = modes[i+1];
modes[i+1] = change;
}
}
for(int i = 0; i < modes.length; i++) {
DisplayMode current = modes[i];
System.out.println(i + ". " + current.getWidth() + "x" + current.getHeight() + "x" +
current.getBitsPerPixel() + " " + current.getFrequency() + "Hz");
}
//fit into string array
for (int i = 0; i < modes.length - 1; i++) {
if (!(modes[i].getWidth() == modes[i+1].getWidth())) {
rows += 1;
deltaIter = i - deltaIter;
if (deltaIter > columns)
columns = deltaIter;
}
}
//split the displaymode array into the two-dimensional string one here
tobe = new String[rows][columns];
for (int i = 0; i < rows; i++) {
for (int a = 0; a < columns; a++) {
if((modes[iter].getWidth() == modes[iter+1].getWidth())) {
tobe[i][a] = iter + ". " + modes[iter].toString() + " ";
}
else
break;
if (!(iter >= 68))
iter += 1;
}
if (iter >= 68)
break;
}
tobe[rows-1][columns-1] = (iter + 1) + ". " + modes[iter].toString() + " ";
//test to see that it works
for (int i = 0; i < rows; i++) {
for (int a = 0; a < columns; a++) {
if(tobe[i][a] != null)
System.out.print(tobe[i][a]);
else
break;
}
System.out.println("");
}
System.exit(0);
return null;
}
The output looks like this:
0. 1440x900x32 75Hz
1. 1440x900x16 75Hz
2. 1440x900x32 60Hz
3. 1440x900x16 60Hz
with all of the different possible resolutions. Basically, what I'm trying to do is make a readable list of the different resolutions, so a user can select their desired one. Thank you.
How about storing the information in a different manner? When I made the transition from C to Java I used to use multi-dimensional arrays quite a bit, but it's a pain.
public class ScreenType implements Comparable {
int width;
int height;
int color; // not sure what this one was for, assuming 32/16 bit color
int hertz;
public ScreenType(int w, int h, int c, int h) {
width = w;
height = h;
color = t;
hertz = h;
}
// remember to maintain transitive property,
// see JDK documentation for Comparable
#Override
public int compareTo(Tuple other) {
}
// getters and setters and whatnot
#Override
public String toString() {
return width + "X" + height + "X" + color+ " " + hertz + "hz";
}
}
Then store your screen data like this and use an ArrayList of ScreenTypes which, if I remember right, will sort based on your overriding of compareTo()

Categories