Java two-dimensional array of chars - java

I need to write a java program that has an array-returning method that takes a two-dimensional array of chars as a parameter and returns a single-dimensional array of Strings.
Here's what I have
import java.util.Scanner;
public class TwoDimArray {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of Rows?");
int rows = s.nextInt();
System.out.println("Enter the number of Colums?");
int cols = s.nextInt();
int [][] array = new int [rows] [cols];
}
public static char[ ] toCharArray(String token) {
char[ ] NowString = new char[token.length( )];
for (int i = 0; i < token.length( ); i++) {
NowString[i] = token.charAt(i);
}
return NowString;
}
}

You need an array of String, not of chars:
public static String[] ToStringArray(int[][] array) {
String[] ret = new String[array.length];
for (int i = 0; i < array.length; i++) {
ret[i] = "";
for(int j = 0; j < array[i].length; j++) {
ret[i] += array[i][j];
}
}
return ret;
}

The above answers are right; however you may want to use StringBuilder class to build the string rather than using "+=" to concatenate each char in the char array.
Using "+=" is inefficient because string are immutable type in java, so every time you append a character, it will have to create a new copy of the string with the one character appended to the end. This becomes very inefficient if you are appending a long array of char.

public String[] twoDArrayToCharArray(char[][] charArray) {
String[] str = new String[charArray.length];
for(int i = 0; i < charArray.length; i++){
String temp = "";
for(int j = 0; j < charArray[i].length; j++){
temp += charArray[i][j];
}
str[i] = temp;
}
return str;
}

Related

How do I convert a String into a 2D array

I have to define a method called getDistance. That takes the following string:
0,900,1500<>900,0,1250<>1500,1250,0 and returns a 2d array with the all the distances. The distances are separated by "<>" symbol and they are separated into each column by ",".
I know I need to use String.split method. I know splitting by the commmas will give me the columns and splitting it by the "<>" will give me the rows.
public static int[][] getDistance(String array) {
String[]row= array.split(",");
String[][] distance;
int[][] ctyCoord = new int[3][3];
for (int k = 0; k < row.length; k++) {
distance[k][]=row[k].split("<>");
ctyCoord[k][j] = Integer.parseInt(str[j]);
}
return ctyCoord;
This is a working dynamic solution:
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] _2d = null;
// let us take the column size now, because we already got the row size
if (rows.length > 0) {
String[] cols = rows[0].split(",");
_2d = new int[rows.length][cols.length];
}
for (int i = 0; i < rows.length; i++) {
String[] cols = rows[i].split(",");
for (int j = 0; j < cols.length; j++) {
_2d[i][j] = Integer.parseInt(cols[j]);
}
}
return _2d;
}
Let's test it:
public static void main(String[] args) {
String given = "0,900,1500<>900,0,1250<>1500,1250,0";
int[][] ok = getDistance(given);
for (int i = 0; i < ok.length; i++) {
for (int j = 0; j < ok[0].length; j++) {
int k = ok[i][j];
System.out.print(k + " ");
}
System.out.println();
}
}
I think you should first split along the rows and then the colums. I would also scale the outer array with the number of distances.
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] out = new int[rows.length][3];
for (int i = 0; i < rows.length, i++) {
String values = rows[i].split(",");
for (int j = 0; j < 3, j++) {
out[i][j] = Integer.valueOf(values[j]);
}
}
return out;

java ", imcompatable types issue im having with my code: char cannot be converted to a string

For this java program I am taking in a string then printing/saving the string of characters in order of their frequency.
import java.util.*;
public class freqChar
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
int myArray[] = new int[256];
int len = s.length();
String array1 [] = new String [len];
String strArray [] = new String [len];
for(int i = 0; i < s.length(); i++)
{
myArray[(int)s.charAt(i)]++;
}
for(int i = s.length(); i > 0; i--)
{
for(int j = 0; j < myArray.length; j++)
{
if(myArray[j] == i) // Here I am trying to fill a string array with the characters from the original string after I have casted them back from ints.
{
int g = 0;
char x = ((char)(j));
array1[g] = x;
g++;
}
}
}
for (int i = 0; i < len; i++)
{
System.out.println(array1[i] + " ");
}
}
}
When I compile it gives me the error:
cannot convert char to a string.
Short answer: a char is not a String so putting a char into an array of Strings won't work.
But its very easy to fix the problem, just replace char x =((char)(j)); with char x = Character.toString((char) j);

How to convert a String array to char array in Java

We are given an array of Strings and what we require is a char[], i.e, array of all characters in all the Strings
For example:
Input: [i, love, you]
output: [i, l, o, v, e, y, o, u]
First I made an array of arrays.
Then I have found the length of the required char[] array.
I have tried the following so far:
char[][] a1 = new char[str.length][];
for(int i =0;i<str.length;i++){
a1[i]=str[i].toCharArray();
}
int total=0;
for(int i =0;i<str.length;i++){
total = total + a1[i].length;
}
char[] allchar = new char[total];
for(int i=0;i<str.length;i++){
//NOW HERE I WANT TO MERGE ALL THE char[] ARRAYS TOGETHER.
//HOW SHOULD I DO THIS?
}
String[] sArray = {"i", "love", "you"};
String s = "";
for (String n:sArray)
s+= n;
char[] c = s.toCharArray();
You can do that like this
char[] allchar = new char[total]; // Your code till here is proper
// Copying the contents of the 2d array to a new 1d array
int counter = 0; // Counter as the index of your allChar array
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a1[i].length; j++) { // nested for loop - typical 2d array format
allchar[counter++] = a1[i][j]; // copying it to the new array
}
}
You can do something like the following method..
public void converter(String[] stringArray) {
char[] charsInArray = new char[500]; //set size of char array
int counterChars = 0;
for (int i = 0; i < stringArray.length; i++) {
int counterLetters = 0; //declare counter for for amount of letters in each string in the array
for (int j = 0; j < stringArray[i].length(); j++) {
// below pretty self explanatory extracting individual strings and a
charsInArray[counterChars] = stringArray[i].charAt(counterLetters);
counterLetters++;
counterChars++;
}
}
}
String [] s = new String[]{"i", "love", "you"};
int length = 0;
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s[i].length(); j++) {
length++;
}
}
char [] c = new char[length];
int k = 0;
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s[i].length(); j++) {
c[k] = s[i].charAt(j);
k++;
}
}
for (int j = 0; j < c.length; j++) {
System.out.print("char is: " + c[j]);
}
In Java 8 we can use streams.
public char[] convert(String[] words) {
return Arrays.stream(words)
.collect(Collectors.joining())
.toCharArray();
}
Here we created a stream from an array using
Array.stream(T[] array) where T is the type of the array elements.
Than we obtain a string using Collectors.joining(). Finally we get a char array using the String's toCharArray() method.
public static void main(String[] args)
{
String sentence="Gokul Krishna is class leader";
String[] array=sentence.split("\\s");
int counter;
//String word = new String();
for(String word:array)
{
counter=0;
char[] wordArray=word.toCharArray();
for(int i=0;i<wordArray.length;i++)
{
counter++;
}
System.out.println(word+ " :" +counter);
}
}
public char[] convert(String[] arr) {
StringBuilder sb = new StringBuilder();
for (String s : arr) {
sb.append(s);
}
return sb.toString().toCharArray();
}

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]);
}
}
}

How to print two dimensional array of strings as String

I know how to do the toString method for one dimensional arrays of strings, but how do I print a two dimensional array? With 1D I do it this way:
public String toString() {
StringBuffer result = new StringBuffer();
res = this.magnitude;
String separator = "";
if (res.length > 0) {
result.append(res[0]);
for (int i=1; i<res.length; i++) {
result.append(separator);
result.append(res[i]);
}
}
return result.toString();
How can I print a 2D array?
The Arrays class defines a couple of useful methods
Arrays.toString - which doesn't work for nested arrays
Arrays.deepToString - which does exactly what you want
String[][] aastr = {{"hello", "world"},{"Goodbye", "planet"}};
System.out.println(Arrays.deepToString(aastr));
Gives
[[hello, world], [Goodbye, planet]]
You just iterate twice over the elements:
StringBuffer results = new StringBuffer();
String separator = ","
float[][] values = new float[50][50];
// init values
for (int i = 0; i < values.length; ++i)
{
result.append('[');
for (int j = 0; j < values[i].length; ++j)
if (j > 0)
result.append(values[i][j]);
else
result.append(values[i][j]).append(separator);
result.append(']');
}
IMPORTANT: StringBuffer are also useful because you can chain operations, eg: buffer.append(..).append(..).append(..) since it returns a reference to self! Use synctactic sugar when available..
IMPORTANT2: since in this case you plan to append many things to the StringBuffer it's good to estimate a capacity to avoid allocating and relocating the array many times during appends, you can do it calculating the size of the multi dimensional array multiplied by the average character length of the element you plan to append.
public static <T> String to2DString(T[][] x) {
final String vSep = "\n";
final String hSep = ", ";
final StringBuilder sb = new StringBuilder();
if(x != null)
for(int i = 0; i < x.length; i++) {
final T[] a = x[i];
if(i > 0) {
sb.append(vSep);
}
if(a != null)
for(int j = 0; j < a.length; j++) {
final T b = a[j];
if(j > 0) {
sb.append(hSep);
}
sb.append(b);
}
}
return sb.toString();
}
Two for loops:
for (int i=1; i<res.length; i++) {
for (int j=1; j<res[i].length; j++) {
result.append(separator);
result.append(res[i][j]);
}
}
public static void main(String[] args) {
String array [] [] = {
{"*","*", "*", "*", "*", "*"},
{"*"},
{"*"},
{"*"},
{"*","*", "*", "*", "*", "*"},
{"*"},
{"*"},
{"*"},
{"*"},
{"*"}};
for (int row=0; row<array.length;row++) {
for (int column = 0; column < array[row].length; column++) {
System.out.print(array[row][column]);
}
System.out.println();
}
}

Categories

Resources