Store characters in a 2 dimensional array instead of ASCII values - java

I created a method to store '-' as a blank space into a 2 dimensional array but after compiling it stores the number 45, which is the ASCII value of '-' character. Can somebody please tell me how I can actually store the character and not the ASCII value?
private int[][] array;
public final char BLANK = '-';
public BlankArray(int gridSize)
{
array = new int[gridSize][gridSize];
for(int row = 0; row < gridSize; row++) {
for(int col = 0; col < gridSize; col++) {
array[row][col] = BLANK;
}
}
}

You have declared a two dimensional array of type integer. The blank character is being implicitly cast to type integer. If you wish to store the character in your array, declare your array as type char rather than int.

You can print the stored ASCII value "45" as "-" by using :
System.out.print(" "+ (char)array[row][col]);
Consider this Example program :
class fun {
public int[][] array;
public final char BLANK = '-';
public void BlankArray(int gridSize) {
array = new int[gridSize][gridSize];
for (int row = 0; row < gridSize; row++) {
for (int col = 0; col < gridSize; col++) {
array[row][col] = BLANK;
}
}
}
public void printArray(int gridSize) {
for (int row = 0; row < gridSize; row++) {
for (int col = 0; col < gridSize; col++) {
// System.out.print("array ["+row+"] ["+col+" ]" +
// array[row][col]);
System.out.print(" " + (char) array[row][col]); // casting ASCII
// value to char
// at the time
// of printing
}
System.out.println();
}
}
}
public class int_array_char {
public static void main(String args[]) {
fun obj = new fun();
obj.BlankArray(4); // passing 4 as gridSize
obj.printArray(4);
}
}
Note: just type cast at the time of printing.

Related

Java code to dynamically change a 2D array based off of String input

The code should know what the length of the input is, which is a string.
For example, if "apple" is put in, it displays
EDIT NEW ANSWER
row 1: APPL
row 2: E***
EDIT row 3: (***) should not be here
If Water Melon
Row 1: Wate
Row 2: r Me
Row 3: lon*
EDIT
(Row 4: ****) should not be here
It finds the minimum 1 by 1, 2 by 2, 3 by 3 and so forth length possible.
Spaces are included, and extra spaces are replaced with asterisks
The code below runs perfectly if there is an assigned length for the 2D array. I need a way for the array to dynamically change based on the string input
public A(String input) {
// Array = new String[4][4];
int i = 0;
// Increment through the rows
for (int row = 0; row < Array.length; row++) {
// Increment through the columns
for (int col = 0; col < Array[0].length; col++) {
if (i < input.length() && (row * col) <= input.length()) {
Array[row][col] = input.substring(i, i + 1);
i++;
} else
Array[row][col] = " ";
}
}
}
A test = new A("Apple");
System.out.println(test);
A test2 = new A("Water Melon");
System.out.println(test2);
You need to calculate the dimenssion of your resulting 2D-Array first. This can be simply done by ceiling the square root of the input length. Then you just need to fill the resulting array with each char of input and add an asteriks if the input is to short.
public static void main(String args[]) {
String a = "Water Melon";
for(String[] row : fill2DArray(a)){
System.out.println(Arrays.toString(row));
}
}
static int getDim(String input){
return (int) Math.ceil(Math.sqrt(input.length()));
}
static String[][] fill2DArray(String input){
int dim = getDim(input);
String[][] result = new String[dim][dim];
for(int i = 0; i < dim * dim; i++){
if(i < input.length()){
result[i/dim][i%dim] = String.valueOf(input.charAt(i));
}
else{
result[i/dim][i%dim] = "*";
}
}
return result;
}
The above method fill2DArray can be shortend using ternary operator like :
static String[][] fill2DArrayTernary(String input){
int dim = getDim(input);
String[][] result = new String[dim][dim];
for(int i = 0; i < dim * dim; i++){
result[i/dim][i%dim] = i < input.length() ? String.valueOf(input.charAt(i)) : "*";
}
return result;
}
You can do the task also using regex after appending the required asteriks to the input and spliting the string first at each nth (dim) char and then again at each char. Example:
static String[][] fill2DArrayRegex(String input){
int dim = getDim(input);
String inputWithAsteriks = input + "*".repeat(dim * dim - input.length());
String[] rows = inputWithAsteriks.split("(?<=\\G.{" + dim +"})");
String[][] result = new String[dim][dim];
for(int i = 0; i < rows.length ; i++){
result[i] = rows[i].split("");
}
return result;
}
Also streams can be used here if needed:
static String[][] fill2DArrayStreams(String input){
int dim = getDim(input);
String inputWithAsteriks = input + "*".repeat(dim * dim - input.length());
return Pattern.compile("(?<=\\G.{" + dim +"})")
.splitAsStream(inputWithAsteriks)
.map(str -> str.split(""))
.toArray(String[][]::new);
}
UPDATE
If your original code works (i haven't tested it) and the only thing you need is to calculate the column count of your array dynamicaly depending on input:
public A(String input) {
int columns = (int)Math.ceil(input.length()/4.0);
Array = new String[4][columns];
for (int i = 0; i < 4 * columns; i++) {
if (i < input.length()) {
Array[i / columns][i % columns] = String.valueOf(input.charAt(i));
} else {
Array[i / columns][i % columns] = "*";
}
}
}
Here is a possible solution:
// the import is for testing purposes only
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
// the following code is for testing purposes only
Test test = new Test();
System.out.println(Arrays.deepToString(test.squareArray("Apple")));
System.out.println(Arrays.deepToString(test.squareArray("Water Melon")));
}
public String[][] squareArray(String input){
int size = 1;
// find the smallest size for your array
while(input.length() > (size * size))
size++;
// fill in the input up to the required size with asterik
int length = size * size;
input = input + "*".repeat(length - input.length());
// create the array
String[][] result = new String[size][size];
// fill in all characters of the input into the array
for(int i = 0; i < input.length(); i++)
result[i / size][i % size] = String.valueOf(input.charAt(i));
// return the created array
return result;
}
}
I hope that meets your question.

Why wont my 2d array variable take input?

Noob to programming... I need to create a function that receives a 2d array and requests user input to fill both the rows and the columns. The error that shows me is "empty statement" / "not a statement" on the last line.
public static void fillMatrix(int [][] pmatrix) throws IOException {
int [][] matrix = new int [pmatrix.length][pmatrix.length];
int i, k; //loop variables
int rows, columns;
for(i = 0; i < pmatrix.length; i++){
print.println("set the value of the row " + (i + 1));
rows = Integer.parseInt(read.readLine());
}
for(k = 0; k < pmatrix.length; k++){
print.println("set the value of the column " + (k + 1));
colums = Integer.parseInt(read.readLine());
}
matrix = {{rows}, {columns}};
}
First, what you do here is reassigning the variables rows and columns in each iteration. So at the end, you will have one single value per row in your matrix.
Second, you're reassigning the local variable matrix to be a Matrix, that has two rows and one column. And since it doesn't have anything to do with the parameter pmatrix, nothing will happen to it after the method returns.
I assume you want to call that method on an empty 2D-Array and fill it with values from the console. To iterate through a 2D-Array, you will need a nested for-loop and access each index in your matrix individually:
public static void fillMatrix(int [][] pmatrix) throws IOException {
for(i = 0; i < pmatrix.length; i++){
for(int j = 0; j < pmatrix[i].length; i++ {
print.println("set the value of row " + (i + 1) + " in column " + (j + 1));
pmatrix[i][j] = Integer.parseInt(read.readLine());
}
}
}
It is easier to understand in the full context.
The following code has a main method that creates a matrix of size 3x3, you can change this if you like.
Next, it calls the fillMatrix method and then the printMatrix method.
fillMatrix goes through each row and for each row, it goes through each column. For an entry in the matrix, it reads an integer using Scanner instead of BufferedReader because it is easier to use.
printMatrix runs through all the entries and prints them as a table.
Running the program and giving 1 2 3 4 5 6 7 8 9 prints
1 2 3
4 5 6
7 8 9
The program
import java.io.IOException;
import java.util.Scanner;
public class Helper {
public static void main(final String[] args) throws IOException {
final int[][] matrix = new int[3][3];
fillMatrix(matrix);
printMatrix(matrix);
}
public static void fillMatrix(final int[][] matrix) throws IOException {
final Scanner scanner = new Scanner(System.in);
for (int i = 0; i < matrix.length; i++) {
final int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
final int userInput = scanner.nextInt();
row[j] = userInput;
}
}
}
private static void printMatrix(final int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
final int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
System.out.print(row[j] + " ");
}
System.out.println();
}
}
}

Print out a string of characters from a 2D array into a certain number of rows

I'm trying to make a keypad in Java that takes letters input by the user, as well as a desired number of characters per row. It should then print the characters in the desired number of rows, so if "abcdefgh" is input and the desired row number is 4 it should print:
abcd
efgh
but I'm stuck on how to get it to work.
public class Keypad {
char [][] letters;
public Keypad(String chars, int rowLength) {
int counter = 0;
for (int i = 0; i<chars.length(); i++){
counter++;
}
letters = new char[rowLength][counter/rowLength];
}
public String toString() {
String s = " ";
for (int row=0; row<letters.length; row=row+1) { // Over rows
for (int col=0; col<letters[row].length; col=col+1) {
s = s + letters[row][col];
}
s = s + "\n";
}
return "the keypad is" + s;
}
the logic of the toString() method looks fine, but you didn't populate the letters array in the constructor. So you need to add something like this in the constructor:
public Keypad(String chars, int rowLength) {
// you don't need to count the length with a loop
int nRow = chars.length()/rowLength;
if(chars.length()%rowLength!=0) nRow++;
letters = new char[nRow][rowLength];
for(int i = 0, n = 0 ; i < letters.length ; i++) {
for(int j = 0 ; n < chars.length() && j < letters[i].length ; j++, n++) {
letters[i][j] = chars.charAt(n);
}
}
}

Adding Java 2d Arrays

I need to create a method within my class to add two 2d arrays together. One is implemented as a parameter in the method, while the other is a class object. I need to make sure the arrays are the same size, and if so, add them together. I keep getting an Array Out of Bounds error. Whats wrong with my code?
// method to add matrices
public int[][] add(int[][] matrix) {
int addedMatrices[][] = new int[row][column];
if (userArray[row][column] == matrix[row][column]) {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
System.out.println(addedMatrices[i][j]);
}
}
}
return addedMatrices;
}
if (userArray[row][column] == matrix[row][column]) is the problem.
Remember that arrays are zero-indexed so the elements are numbered from zero to row - 1. Trying to access row row is guaranteed to throw an ArrayIndexOutOfBoundsException because the last row is at index row - 1.
I'm not sure why you even have this line. If you change row to row - 1 and column to column - 1 then this line checks if the bottom-right values in the two matrices are the same. If they're not then the matrices will not be summed. Is that what you intended to do?
I think this is what you are trying to do :
public class Test {
static int row =3;
static int column =2;
static int[][] userArray = new int[][] {{1,1},{2,2},{3,3}};
public static void main(String[] args) {
add(new int[][] {{4,4},{5,5},{6,6}});
}
// method to add matrices
public static int[][] add(int[][] matrix) {
int addedMatrices[][] = new int[row][column];
//check arrays are of the same size
if ((userArray.length == matrix.length) && (userArray[0].length == matrix[0].length) ) {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
//printout
if(j == (column -1)) {
for(int col = 0; col < column; col++) {
System.out.print(addedMatrices[i][col]+ " ");
}
}
System.out.println();
}
}
}
return addedMatrices;
}
}
or better:
public class Test {
static int[][] userArray = new int[][] {{1,1},{2,2},{3,3}, {4,4}};
public static void main(String[] args) {
add(new int[][] {{5,5},{6,6},{7,7},{8,8}});
}
// method to add matrices
public static int[][] add(int[][] matrix) {
//check arrays are of the same size
if ((userArray.length != matrix.length) || (userArray[0].length != matrix[0].length) ) {
System.out.println("Error: arrays are not of the same size");
return null;
}
int rows = userArray.length;
int cols = userArray[0].length;
int addedMatrices[][] = new int[rows][cols];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
//printout
if(j == (cols -1)) {
for(int col = 0; col < cols; col++) {
System.out.print(addedMatrices[i][col]+ " ");
}
}
System.out.println();
}
}
return addedMatrices;
}
}
to make the print out more elegant you could change the for loop to :
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
}
System.out.println(Arrays.toString(addedMatrices[i]));
}
The line if (userArray[row][column] == matrix[row][column]) { should be replaced by a line to check if the dimensions of both matrices are the same (I guess that is what's intended). Assuming they are both rectangular arrays, and non empty:
public class MatrixAdder {
static public int[][] userArray = {{1,2},{3,4},{5,6}};
static public int[][] add(int[][] matrix) {
final int nb_rows1 = matrix.length; // nb rows in matrix
final int nb_cols1 = matrix[0].length; // nb columns in matrix
final int nb_rows2 = userArray.length; // nb rows in userArray
final int nb_cols2 = userArray[0].length; // nb columns in userArray
// this assumes A[0] exists, and A[0].length == A[1].length == ...
// both for matrix and userArray
int addedMatrices[][] = new int[nb_rows1][nb_rows1];
if ((nb_rows1==nb_rows2) && (nb_cols1==nb_cols2)) {
for (int i = 0; i < nb_rows1; ++i) {
for (int j = 0; j < nb_cols1; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
System.out.println(addedMatrices[i][j]);
}
}
}
return addedMatrices;
}
static public void main(String[] args)
{
int[][] mx1 = {{10,100},{20,200},{40,400}};
int [][] mx2 = add(mx1);
}
}
To be more robust, you could check that the dimensions of all sub-arrays are the same. You could also check if the matrix has zero dimension (otherwise array[0] will give an error).
If the dimensions are not the same, the returned matrix is filled with zeroes.
If this is not exactly what you need, it should give you enough hints.
if (userArray[row][column] == matrix[row][column]) {}
This is strange to me, I honestly don't know what the intentions are (Your just comparing the last element of each array).
I would do
if(addedMatrices.length == userArray.length && addedMatrices.length == matrix.length){}.
This is ugly but I don't know anything about userArray or matrix. I am presuming userArray is global. Also do j++ and i++, it has the same end result but it is more of the norm.

2D array populating not working

I'm trying to populate a 2D array with char's from a string I've read in. I'm having a problem with actually populating this 2D array. It keeps printing a 2D array bigger than what I've given it, and the number always seems to be 6 rather than the letters from the string.
I store the string in an ArrayList called tempArray.
Input strings:
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
I instantiate a 2D array with columnlength = 11, and rowcount 3
epidemicArray = new int[rowCount][columnCount];
Array before I try to populate it:
00000000000
00000000000
00000000000
My code:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
for (int k = 0; k < rowCount; k++){
for (int l = 0; l < columnCount; l++){
epidemicArray[k][l] = charz[j];
}
}
}
}
}
Output: Which I didn't expect
6666666666666666666666
6666666666666666666666
6666666666666666666666
Expected output: (2D array)
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
Thanks, this is really bugging me.
Change your code to this:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
epidemicArray[i][j] = charz[j];
}
}
}
This edit should work since the number of columns is the length of one of the string (same length for the 3 of them).
Here is my output
[EDIT]. #magna_nz, I used the following methods to print the array
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
updateArray();
for (int i = 0; i < 3; i++) {
printRow(i);
}
}
This will print the numbers, but if you want to print characters you can change the above printRow method to something like:
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( (char)epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
And this will give you the following result:
You're overwriting your entire epidemicArray with the last value that charz[j] gets. Which is apparently 66. Actually you're overwriting that entire array with every value from charz and the last one won.

Categories

Resources