How to print two dimensional array of strings as String - java

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

Related

how to get String array containing distinct characters?

i have a String "iye" and i want make it distinct and also i have a array ["hi", "bye", "bebe"] and i want to make each element of the array and get the distinct characters only so my array would be like this ["hi", "bye", "be"] an then at last i want to take each element from that distinct array and count how many characters of distinctArray[i] are present in the distinct String "iye" and i will store that count for each element of distinct array in same order respectively to the elements of distinct array for e.g
sample input = "iyee" and ["hi", "bye", "bebe"]
sample ouput = [1, 2, 1]
below is my solution not working for larger inputs
static int[] mathProfessor(String B,String[] a){
List<String> distinct = new ArrayList<String>();
int[] arr = new int[a.length];
// store each value of names array as distinct value
for (int i = 0; i < a.length; i++) {
StringBuilder str = new StringBuilder();
a[i].chars().distinct().forEach(c -> str.append((char) c));
distinct.add(str.toString());
}
// System.out.println("distinct list: " + distinct.toString());
// store the count
int count = 0;
for (int i = 0; i < distinct.size(); i++) {
String s = distinct.get(i);
for (int j = 0; j < B.length(); j++) {
if (s.contains(Character.toString(B.charAt(j))))
count++;
}
arr[i] = count;
count = 0;
}
return arr;
}
static int[] mathProfessor(String b, String[] a) {
b = dist(b);
int count = 0;
String[] arr = new String[a.length];
int[] countArr = new int[a.length];
for (int i = 0; i < a.length; i++) {
arr[i] = dist(a[i]);
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < b.length(); j++) {
if (arr[i].contains(Character.toString(b.charAt(j))))
count++;
}
countArr[i] = count;
count = 0;
}
//System.out.println(Arrays.toString(countArr));
return countArr;
}
public static String dist(String s) {
StringBuilder sb = new StringBuilder();
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
if (set.add(s.charAt(i)) == true)
sb.append(s.charAt(i));
}
return sb.toString();
}
Using Java 8+ Streams:
static int[] mathProfessor(String b, String[] a) {
var distinctB = dist(b);
System.out.println(distinctB);
var result = new int[a.length];
for(int i=0, j=a.length; i < j; i++) {
result[i] = (int) Arrays.stream(dist(a[i]).split("")).filter(distinctB::contains).count();
}
return result;
}
public static String dist(String s) {
Set<String> set = new HashSet<>();
set.addAll(Arrays.asList(s.split("")));
return String.join("", set);
}

when filling a 2d array it gets null values

Im trying to initialise all the elements of the 2d array into a string "EMPTY". but When ever I try to initialise the array it gets null values. I checked errors in the for loop but couldn't see any
public static void arr_2d(){
String [][] arr = new String[3][2];
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
}
for (int b = 0; b < arr.length; b++) {
for (int j = 0; j < arr[b].length; j++) {
System.out.print(arr[b][j] + " ");
}
System.out.println();
}
}
}
Your loops are nested wrongly, which will result in the filling process not being complete while you're trying to process its results. You need
public static void arr_2d() {
String[][] arr = new String[3][2];
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
}
}
for (int b = 0; b < arr.length; b++) {
for (int j = 0; j < arr[b].length; j++) {
System.out.print(arr[b][j] + " ");
}
System.out.println();
}
}
Actually for(int b) is in for(int i); that's why you observe null values. If you move for(int b) outside of for(int i), there will be no null values.
public static void arr_2d(){
String [][] arr = new String[3][2];
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
}
}
for (int b = 0; b < arr.length; b++) {
for (int j = 0; j < arr[b].length; j++) {
System.out.print(arr[b][j] + " ");
}
System.out.println();
}
}
Check the comments given below in the snippet:
public static void arr_2d(){
String [][] arr = new String[3][2];
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
// you can have the sysout statement here as well instead of having looping the entire array again.
System.out.print(arr[i][a] + " ");
}
// this loop must be executed separately inorder to check values present in the array or else you can have a sysout statement when assigning the "empty" value in the array.
for (int b = 0; b < arr.length; b++) {
for (int j = 0; j < arr[b].length; j++) {
System.out.print(arr[b][j] + " ");
}
System.out.println();
}
}
}
Although the answers you have are correct I will add that one problem is your code style is prone to errors.
Your mistake was traversing the array incorrectly. The correct way is traversing the array twice, one of filling and another for printing, but instead it seems you have attempted to do everything in one shot. That mistake can be avoided with a better code style.
This is how I would have written your code in imperative style:
String[][] arr = new String[3][2];
for (String[] a : arr)
Arrays.fill(a, "EMPTY");
for (String[] a : arr)
System.out.println(Arrays.toString(a));
Notice the code is much shorter, so there's less chances of mistakes. It's also a lot more obvious that you're traversing twice.
Instead of traversing an array explicitly:
for (int i = 0; i++; i < arr.length())
Use the implicit for loop:
for (String[] value: arr)
Instead of filling an array explicitly:
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
}
Use the already provided fill method:
Arrays.fill(value, "EMPTY");
Instead of printing an array explicitly:
for (String string : strings) {
System.out.print(string + " ");
}
System.out.println();
Use the already provided print method:
for (String[] a : arr)
System.out.println(Arrays.toString(a));
However, I would have written in functional style:
String [][] arr = new String[3][2];
Arrays.stream(arr)
.forEach(a -> Arrays.fill(a, "EMPTY"));
Arrays.stream(arr)
.map(Arrays::toString)
.forEach(System.out::println);
One particular advantage is that you are encouraged to think in a more abstract way. Instead of thinking how to explicitly set or print each element of the array, you are encouraged to use methods that implicitly traverse, transform or perform generic computations on all elements of the array.

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;

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

Java two-dimensional array of chars

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

Categories

Resources