Populating an array with bytes from a string of numbers - java

I'm trying to populate an array of bytes from a string that contains numbers(some being 2 digits) with spaces in between. I know there is an parseByte function but I'm unsure how to use that when populating an array as it seems to just take the string as one whole number.
my not-working-code:
public static void popArray(byte[][] array, String numbers)
{
int counter = 0; //counter to track position in string of data
for(int i=0; i<20; i++) //cycle rows
{
for(int y=0; y<20; y++) //cycle columns
{
array[i][y] = (byte)(Character.digit(.charAt(counter), 10));
counter++; //increase place in data string
}
}
}

Split the string at spaces, then iterate over the resulting array:
String[] parts = numbers.split("\\s+");
int counter = 0; //counter to track position in string of data
for (int i = 0; i < 20; i++) { //cycle rows
for (int y = 0; y < 20; y++) { //cycle columns
String s = parts[counter];
byte b = (byte)(Integer.parseInt())
array[i][y] = b;
counter++; //increase place in data string
}
}

Related

How to populate a 2D array in Java using user input?

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

How do I randomly add letter in this 2D array?

What code would i need to get a letter to randomly generate inside this code?
public class Array {
public static void main(String[] args) {
// Create 2-dimensional array.
int[][] values = new int[5][5];
// Loop over top-level arrays.
for (int i = 0; i < values.length; i++) {
// Loop and display sub-arrays.
int[] sub = values[i];
for (int x = 0; x < sub.length; x++) {
System.out.print(sub[x] + " ");
}
System.out.println();
}
}
}
String s = "abcdefghijklmnopqrstuvwxyz";
//loop through rows
for(int x = 0; x< values[0].length;x++)
{
//loops through columns
for(int y = 0; y< values.length;y++)
{
int x = (int)(Math.random()*26); // random int between 0-25
String letter = ""+s.charAt(x); //concatenates
values[x][y] = letter; // declares.
}
}
here is How you would get a letter to randomly generate inside the code.

Insert integers into 2d array

private void enterbtnActionPerformed(java.awt.event.ActionEvent evt) {
int [][] array = new int [4][4]; // my array
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
array[i][j]= ;// use for feeding the code
}
popfield.setText(Arrays.deepToString( array ) );
}
I want to insert integers into 2d array via 2 textfields one for columns and one for rows elements via two text fields xfield and yfield
So.. For create 2D int array:
//int 2 dimensional array
int[][] array = null;
//your fields values
final int xFieldVal = 5;
final int yFieldVal = 7;
//values to fill into array
final int minArrayVal = 50;
final int maxArrayVal = 100;
//create matrix / grid with dimensions (xFieldVal x yFieldVal)
array = new int[xFieldVal][yFieldVal];
(that creates recangle xFieldVal x yFieldVal- or Y*X..)
While you have rectangle array you can acces to all value for filling eg. like that:
//random generator
Random rnd = new Random();
for (int i = 0; i < xFieldVal; i++) {
for (int j = 0; j < yFieldVal; j++) {
//generate new int in interval
array[i][j] = minArrayVal + rnd.nextInt(maxArrayVal- minArrayVal+ 1);
}
}
While you will dont have rectangle array (you can have eg. just 1st dimension fixed, and 2nd not- I mean each "row" can have difference "columns" count), you have to use that loop:
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
//printing next line
System.out.println();
}
Eg. to find min and max value, you can use that:
//set on the max possible (every value should be less than that)
int min=Integer.MAX_VALUE;
//set on the min possible (every value should be more than that)
int max=Integer.MIN_VALUE;
//iteration through 1st index (eg. iteration through rows)
for (int i = 0; i < array.length; i++) {
//iteration through 2nd index of 1st index (eg. through all columns)
for (int j = 0; j < array[i].length; j++) {
//compare and assign if array value is less than actual found min
if(min > array[i][j]){
min = array[i][j];
}
//compare and assign if array value is more than actual found max
if(max < array[i][j]){
max = array[i][j];
}
}
}
I dont think you understand what a 2D array is
think of it as a grid. you insert into a single cell at a time.
a single cell belongs to a row and a column hence has a row number and column number...like an excel work book? cell b5?
so if you want to input numbers all you gotta do is have a single textfield lets call it txt
the rest is as follows
private void enterbtnActionPerformed(java.awt.event.ActionEvent evt)
{
int [][] array = new int [4][4]; // my array
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
array[i][j]= Integer.parseInt(txt.getText());// use for feeding the code
}
popfield.setText(Arrays.deepToString( array ) );
}

Printing chars from 2d array java

How do you print chars from a 2D array, column by column instead of row by row? Also how do you get the chars to populate the array? I know you have to use for loop but I keep getting strings which are read row by row.
String command = args[0];
String Text = args[1]; //leters to be
char letters [] = Text.toCharArray();
int m = Text.length(); //number of letters to be decrypted/encrypted
if (command.equals("-encrypt")) {
if ( m / (int) Math.sqrt(m) == Math.sqrt(m) ) { //if m is a perfect square no. eg.4,9,16
int RootM = (int) Math.sqrt(m); //find depth and width of grid, square therfore depth = width
char [][] box = new char [RootM][RootM]; //define and create grid
for (int i=0; i<RootM; i++) {
for (int j=0; j<RootM; j++) {
box[i] = letters; //change this to read each column
System.out.print(Text); //displays encrypted text
}
}
}
else if ( m / (int) Math.sqrt(m) != Math.sqrt(m) ) { //non perfect square digits
int RootM = (int) Math.pow((Math.sqrt(m))+1,2); //overall size of 2d array (depth*width)
int RootN1 = (int) Math.sqrt(RootM); //length of rows & columns
char [][] box = new char [RootN1][RootN1]; //define dimensions of 2d array
for (int i=0; i<RootN1; i++) {
for (int j=0; j<RootN1; j++) {
box[j] = letters; //change this to read each column
System.out.println(Text); //displays encrypted text
char [][] box = new char [5][3];//5 rows, 3 columns
for(int i =0;i<3; i++){
for (int j = 0; j < 5; j++) {//Iterate rows
System.out.println(box[j][i]);//Print colmns
}
}

Convert String into 2D int array

I have problem with conversion from String into two dimension int array.
Let's say I have:
String x = "1,2,3;4,5,6;7,8,9"
(In my program it will be String from text area.) and I want to create array n x n
int[3][3] y = {{1,2,3},{4,5,6},{7,8,9}}
(Necessary for next stages.) I try to split the string and create 1 dimensional array, but I don't have any good idea what to do next.
As you suggest I try split at first using ; then , but my solution isn’t great. It works only when there will be 3 x 3 table. How to create a loop making String arrays?
public int[][] RunMSTFromTextFile(JTextArea ta)
{
String p = ta.getText();
String[] tp = p.split(";");
String tpA[] = tp[0].split(",");
String tpB[] = tp[1].split(",");
String tpC[] = tp[2].split(",");
String tpD[][] = {tpA, tpB, tpC};
int matrix[][] = new int[tpD.length][tpD.length];
for(int i=0;i<tpD.length;i++)
{
for(int j=0;j<tpD.length;j++)
{
matrix[i][j] = Integer.parseInt(tpD[i][j]);
}
}
return matrix;
}
After using split, take a look at Integer.parseInt() to get the numbers out.
String lines[] = input.split(";");
int width = lines.length;
String cells[] = lines[0].split(",");
int height = cells.length;
int output[][] = new int[width][height];
for (int i=0; i<width; i++) {
String cells[] = lines[i].split(",");
for(int j=0; j<height; j++) {
output[i][j] = Integer.parseInt(cells[j]);
}
}
Then you need to decide what to do with NumberFormatExceptions
Split by ; to get rows.
Loop them, incrementing a counter (e.g. x)
Split by , to get values of each row.
Loop those values, incrementing a counter (e.g. y)
Parse each value (e.g. using one of the parseInt methods of Integer) and add it to the x,y of the array.
If you have already created an int[9] and want to split it into int[3][3]:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
toArray[i][j] = fromArray[(3*i) + j);
}
}
Now, if the 2-dimensional array is not rectangular, i.e. the size of inner array is not same for all outer arrays, then you need more work. You would do best to use a Scanner and switch between nextString and next. The biggest challenge will be that you will not know the number of elements (columns) in each row until you reach the row-terminating semi-colon
A solution using 2 splits:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
String[][] result = new String[x.length][];
for (int i = 0; i<x.length; i++) {
result[i] = x[i].split(",");
}
This give a 2 dimension array of strings you will need to parse those ints afterwards, it depends on the use you want for those numbers. The following solution shows how to parse them as you build the result:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
int[][] result = new int[x.length][];
for (int i = 0; i < x.length; i++) {
String[] row = x[i].split(",");
result[i] = new int[row.length];
for(int j=0; j < row.length; j++) {
result[i][j] = Integer.parseInt(row[j]);
}
}
Super simple method!!!
package ADVANCED;
import java.util.Arrays;
import java.util.Scanner;
public class p9 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String x=sc.nextLine();
String[] array = x.split(",");
int length_x=array.length;
int[][] two=new int[length_x/2][2];
for (int i = 0; i <= length_x-1; i=i+2) {
two[i/2][0] = Integer.parseInt(array[i]);
}
for (int i = 1; i <= length_x-1; i=i+2) {
two[i/2][1] = Integer.parseInt(array[i]);
}
}
}

Categories

Resources