I am new to java and I am struggling immensely! I've written the following code but keep getting errors. All I am trying to do at the moment is fill a 5x5 matrix with the letter A. Here's what I have so far, I am not sure if I need to post the errors as well? Any help would be really greatly appreciated.
public class Encryption {
private String Unencoded, FiveLetterKeyword, EncryptedMessage;
//constructor method
public Encryption(String U, String F, String E)
{
Unencoded = U;
FiveLetterKeyword = F;
EncryptedMessage = E;
}
//create 2D string array 5 by 5
String Encrypt [][] = new String[5][5];
//create string filled with all letters of the alphabet
String String = new String
("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z");
//method for loop to print out the matrix
public static void matrix()
//for loop to create matrix rows and columns
{
for (int row = 1; row < Encrypt.length; row++)
{
for (int column = 1; column < Encrypt[row].length; column++)
System.out.print(Encrypt[row][column] + " ");
}
}
//filling the array with the letter A
public char Encrypt(char Encrypt[][])
{
//char[] alpha = alphabets.toCharArray;
//declaring variable to fill array with A
char aChar = "A";
for (int row = 1; row < Encrypt.length; row++)
{
for (int column = 1; column < Encrypt.length; column++)
return Encrypt;
}
}
}
Arrays in Java are zero-based, which means they start at index zero, and range until index array.length-1.
Your code starts the row and column at 1—which means you're skipping the initialization of row/column 0. That's probably where at least some of the problems are coming from, since you're using your 5x5 array (rows/columns 0,1,2,3,4) as a 4x4 array (rows/columns 1,2,3,4).
There's also the fact that your Encrypt method doesn't actually make any assignments to the array. You probably want to initialize it like this:
// NOTE: changed return type to void -- this is a side-effect-only method!
public void Encrypt(char Encrypt[][])
{
// NOTE: use single-quotes for chars. double-quotes are for strings.
char aChar = 'A';
// NOTE: changed the starting loop values from `1` to `0`
for (int row = 0; row < Encrypt.length; row++)
{
// NOTE: technically Encrypt.length works here since it's a square
// 2D array, but you should really loop until Encrypt[row].length
for (int column = 0; column < Encrypt[row].length; column++)
{
// NOTE: set each entry to the desired char value
Encrypt[row][column] = aChar;
}
}
}
There are several issues with your original code. Look at the NOTE entries in the comments for individual explanations.
You are missing the most crucial part of what you are trying to accomplish.
Where are you setting your matrix to the letter A?
Change your Encrypt function to the following:
//filling the array with the letter A
public void Encrypt(char arr[][])
{
//char[] alpha = alphabets.toCharArray;
//declaring variable to fill array with A
char aChar = 'A';
for (int row = 0; row < arr.length; row++)
{
for (int column = 0; column < arr[row].length; column++)
{
arr[row][column] = aChar;
}
}
}
Related
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.
I'm not sure what to use in order to locate characters at a certain position in my two dimensional array. What I am trying to do is to have the user input the row and column number and fetch the value correspondant to those two variables in the two dimensional array, retrieve it and subsequently set it to 0 in the array
import java.util.*;
public class twoDimension {
public static void printRow(int[] row) {
for (int i : row) {
System.out.print(i);
System.out.print("\t");
}
System.out.println();
}
public static void main(String[] args) {
int twoDm[][]= new int[3][4];
for (int i = 0; i < twoDm.length; i++) {
for (int j = 0; j < twoDm[i].length; j++) {
twoDm[i][j] = (int)(Math.random()*10); // we decided to randomise the numbers in the array.
}
}
for(int[] row : twoDm) {
printRow(row);
}
System.out.println("Enter a number with the format 'xy'. x is the row number and y the column number. Whenever you want to quit out, input 'quit'.");
String xy;
while (!xy.equalsIgnoreCase("quit")) {
Scanner scanner = new Scanner(System.in);
String xy = scanner.nextLine();
char x = xy.charAt(0);
char y = xy.charAt(1);
// fetching the character in the array and displaying it
// setting it to 0
// displaying the array again
}
}
}
PS : I managed to find how I can display the array without commas or brackets, but am unsure about removing the spaces in the display.
If you turn the x and y coordinates to integers:
int xCoor = Character.getNumericValue(x);
int yCoor = Character.getNumericValue(y);
then you can access and/or modify the array by using those coordinates:
twoDm[xCoor][yCoor] = 0;
I am trying to populate a two dimensional array in Java by using a user-inputted string. I have already got the string and I have figured out how to create the array. I am just having trouble figuring out how to get the values into the array. In case you are wondering, yes I have to use an array. Here is what I have so far:
private static int[][] parseTwoDimension(String strInput)
{
int rows = 0; //number of rows in the string
for (int i = 0; i < strInput.length(); i++)
{
if (strInput.charAt(i) == '!') //the ! is an indicator of a new row
{
rows++;
}
}
int[][] arr = new int[rows][]; //create an array with an unknown number of columns
int elementCounter = 0; //keep track of number of elements
int arrayIndexCounter = 0; //keep track of array index
for (int i = 0; i < strInput.length(); i++)
{
if (strInput.charAt(i) != '!') //while not the end of the row
{
elementCounter++; //increase the element count by one
}
else //reached the end of the row
{
arr[arrayIndexCounter] = new int[elementCounter]; //create a new column at the specified row
elementCounter = 0; //reset the element counter for the next row
arrayIndexCounter++; //increase the array index by one
}
}
/*
This is where I need the help to populate the array
*/
char c; //each character in the string
int stringIndex = -1; //keep track of the index in the string
int num; //the number to add to the array
for (int i = 0; i < arr.length; i++)
{
for (int j = 0; j < arr[i].length; j++)
{
stringIndex++; //increment string index for next element
c = strInput.charAt(stringIndex); //the character at stringIndex
if (c == '!') //if it is the end of the row, do nothing
{
}
else //if it is not the end of the row...
{
String s = Character.toString(c); //convert character to String
num = Integer.parseInt(s); //convert String to Integer
arr[i][j] = num; //add Integer to array
}
}
}
return arr; //return a two dimensional array the user defined
}
Any help is greatly appreciated :)
I've edited your code and posted it below. This is a general outline of how to solve it:
Use string.split("!") to separate your String by the delimiter '!'. This returns an array
Then, use string.split("") to separate the String into individual characters
Code posted below:
private static int[][] parseTwoDimension(String strInput)
{
String[] rows = strInput.split("!");
int[][] arr = new int[rows.length()][];
for(int i = 0; i < rows.length; i++)
{
String[] elements = rows[i].split("");
int[] intElements = new int[elements.length];
for(int j = 0; j < elements.length; j++)
{
intElements[j] = Integer.parseInt(elements[j]);
}
arr[i] = intElements;
}
}
Let me know if this works. The string.split() function is really useful when parsing Strings into arrays
i am trying to calculate the sum of elements after the diagonal in 2D array but the problem is that the sum is always equal ZERO it do not change the answer.
where is the mistake in my code and how to fix it ?
i tried to use nested for loop and o tried to use one for loop but in both cases th eanswer still 0.
this is my code:
package test8;
import java.util.Scanner;
public class Question2 {
private int row = 4;
private int col = 4;
private int[][] matrix;
public Question2(int trow, int tcol) {
this.row = trow;
this.col = tcol;
}
public Question2(int trow, int tcol, int[][] m) {
this.row = trow;
this.col = tcol;
this.matrix = m;
}
public int[][] fill() {
int[][] data = new int[row][col];
Scanner in = new Scanner(System.in);
for (int row = 0; row < data.length; row++) {
for (int col = 0; col < data[row].length; col++) {
System.out.println("enter the elementss for the Matrix");
data[row][col] = in.nextInt();
}
System.out.println();
}
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < data[row].length; col++) {
System.out.print(data[row][col] + " ");
}
System.out.println();
}
return data;
}
public int calculate(int[][] num) {
int sum = 0;
for (int row = 0; row < num.length; row++) {
//for (int col = row + 1; col < num[row].length; col++) {
// if(row == col){
System.out.println(row);
sum += num[row][row];
// }
//}
}
System.out.println("the sum is: " + sum);
return sum;
}
public static void main(String[] args) {
Question2 q2 = new Question2(3, 3);
int[][] ma = q2.fill();
q2.calculate(ma);
}
}
this is the output:
1 2 3
4 5 6
7 8 9
0
1
2
the sum is: 15
Problem is that in your fill method you are creating local data array, which is filled with values and returned as result, but in your main method you are not storing this array anywhere. Instead in calculate you are using int[][] ma = new int[3][3]; which is filled with 0.
So maybe change your code to something like
Question2 q2 = new Question2(3, 3);// you don't even need to pass array here if you
// plan to generate new one, so consider removing
// array from argument list in this constructor
int[][] ma = q2.fill();//store array with elements in `ma` reference
q2.calculate(ma); //now `ma` has elements so we can do some calculations
Anyway your code seems strange. It looks like you want your class to store some array, but you are not using this array anywhere (except in fill method where you are using its length properties to fill data array - which seems wrong since data can have different size than matrix).
Maybe in fill method you shouldn't be creating new data array, but instead you should fill matrix array? Also in that case you don't need to pass this array as argument in constructor, but just create new array based on row and col values.
This way you will not even need calculate method to get any array from outside, just use matrix field.
In other words your code can look more like
// remove entirely this constructor, you will not need it
public Question2(int trow, int tcol, int[][] m) {
this.row = trow;
this.col = tcol;
this.matrix = m;
}
// but use only this one
public Question2(int trow, int tcol) {
this.row = trow;
this.col = tcol;
this.matrix = new int[trow,tcol];// just make sure it will initialize `matrix`
}
Now you can simply use new Question2(3,3) and be sure that it will also have empty array with correct sizes.
Time for fill method. Don't create local int[][] data array, just use matrix instead, so change
data[row][col] = in.nextInt();
to
matrix[row][col] = in.nextInt();
Last thing is calculate method. You don't need it to actually take any array from user, because you already have matrix array inside your class so you can simply reuse it. So instead of calculate(int[][] num) make it calculate() and instead of num use matrix.
So now your code can look like
Question2 q2 = new Question2(3, 3);
q2.fill();
q2.calculate();
You have multiple structure problem but, responding your question, replace this line:
q2.fill();
by:
ma = q2.fill();
I am trying to convert a string to a matrix of 4x4 size. The matrix should contain the elements same as that of the string.
For eg.
String="1234567890111213141516";
I need to convert this to a 4x4 matrix in java.
a[0][0]=1;
a[0][1]=2;
and so on.
Can anyone suggest me the code for the same?
For reading a String s = "1234567890abcdefghij", you can add below code snippet :
char[][] a = new char[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
a[i][j] = s.charAt(4 * i + j);
}
}
this will help you. This will work for only one digit character only.
Here is a hint:
a[i][j] = Integer.valueOf(str.charAt(4 * i + j));
Figuring out how to use this to populate the entire matrix is left as an exercise for the reader.
P.S. This will work for a 16-character abcdefghijklmnop string as in your title; if the string is longer, as in the question, there is no unambiguous way to parse it into a 4x4 matrix.
P.P.S. If all you need to do is set the elements to the consecutive numbers from 1 to 16, you don't need the string at all.
Indeed your question is an easy one, so I answer your question with some additional points that I think help you more than the answer itself:
First, this is the code:
int N = 4;
String delim = ",";
String s = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16";
String[] c = s.split(delim);
int[][] mat = new int[4][4];
int l = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++,l++)
mat[i][j] = Integer.valueOf(c[l]);
Notes:
Please
1 - don't a simple problem a real hard one!
if it's a hw you can convince the tutor about defining the string delimited with something like "," (if he/she insists) or whatever, and if this is a real project convince the customer, you don't want to torture yourself!
String s = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16";
2 - you said you want to split the string into a 4 x 4 matrix, what if you want a 5x5 matrix? So take advantage of constants, and the same for the delimiter
int N = 4;
String delim = ",";
Hope these help.
You should run two for loops through your string and fill up the matrix.
(This can be done with one array too, but let's keep it simple.)
String str ="1234567890111213141516";
final int rowSize = 4;
final int columnSize = 4;
String[][] a = new String[rowSize][columnSize];
// iterate
for (int row = 0; row < rowSize; row++) {
for (int column = 0; column < columnSize; column++) {
a[row][column] = String.valueOf(str.charAt(rowSize * row + column));
}
}
// test
for (int row = 0; row < rowSize; row++) {
for (int column = 0; column < columnSize; column++) {
System.out.print(a[row][column] + " ");
}
System.out.println();
}