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]);
}
}
}
Related
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;
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'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.
I have a board game define as
boardArray = new int[4][4];
and I have a string in this format:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]"
Is there a way to put it in the int array? Consider that it should look like this
[0,0,2,0]
[0,0,2,0]
[0,0,0,0]
[0,0,0,0]
You could simply do the following:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]";
String myNums[] = s.split("[^0-9]+");
//Split at every non-digit
int my_array[][] = new int[4][4];
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
my_array[i][j] = Integer.parseInt(myNums[i*4 + j + 1]);
//The 1 accounts for the extra "" at the beginning.
}
}
//Prints the result
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++)
System.out.print(my_array[i][j]);
System.out.println();
}
If you want to to it dynamically, I've written a librray: https://github.com/timaschew/MDAAJ
The nice thing is, that it's really fast, because internally it's a one dimensional array, but provides you same access and much more nice features, checkout the wiki and and tests
MDDA<Integer> array = new MDDA<Integer>(4,4);
or initialize with an existing array, which is one dimensional "template", but will be converted into your dimensions:
Integer[] template = new Integer[] {0,0,2,0, 0,0,2,0, 0,0,0,0, 0,0,0,0};
MDDA<Integer> array = new MDDA<Integer>(template, false, 4,4);
//instead of array[1][2];
array.get(1,2); // 2
My task is to create a static method named "dupWords" that gets a strings as a parameter and returns how many times a word is at the same string. Now the catch is, that I need to return it as a Two-dimensional array, that have 2 columns and the rows will be how many different sub strings are in the string...
for example: "abcd xyz abcd abcd def xyz"
this will be the pairs [0][3] [5][2] [19][01] the first pair means that the word "abcd" appears 3 times and state at the index 0 (and you get the rest..)
this is an image of the two-dimensional array: (the text is in hebrew but you can see the drawing)
I started something...you will probably think its way off :/ (its just some start)
I think I didn't really understand how to deal with the two-dimensional array..
public static int[][] dupWords (String str) {
String [] stringArray = str.split(" ");
int countWords = 0;
int index = 0;
int [][] retArr;
for (int i = 0; i < stringArray.length; i++) {
for (int j = 0; j < stringArray.length; j++) {
if (stringArray[i].equalsIgnoreCase(stringArray[j])){
countWords++;
index = stringArray[i].indexOf(str);
}
}
}
}
Please help,
thankss
Find the number of unique words.
You can do it, by putting all the words from the stringArray to a hashmap. The hashmap will come handy later.
Create an array like that retArr = new int[unique][2];
Complete solution below (beware, I didn't even compile it!)
public static int[][] dupWords (String str) {
String [] stringArray = str.split(" ");
int countWords = 0;
int index = 0;
HashMap<String, Integer> indexMap = new HashMap<String, Integer>();
HashMap<String, Integer> countMap = new HashMap<String, Integer>();
int index = 0;
for (int i = 0; i < stringArray.size(); i++) {
String s = stringArray[i];
if (!indexMap .containsKey(s)) {
indexMap.put(s, index);
countMap.put(s, 1);
}
else {
int cnt = countMap.get(s);
countMap.put(s, cnt+1);
}
index += s.length() + 1;
}
int [][] retArr = new int[map.size()][2];
for (int i = 0; i < stringArray.size(); i++) {
String s = stringArray[i];
retArr[i][0] = indexMap.get(s);
retArr[i][1] = countMap.get(s);
}
return retArr;
}
Now, without HashMap, or any other dynamic structure it's quite difficult to do. The easiest approach is to create a bigger than necessary array and at the end trim it. This could look like this.
public static int[][] dupWords (String str) {
String [] stringArray = str.split(" ");
int countWords = 0;
int index = 0;
int [][] retArr = new int[stringArray.size()][2];
int uniqeWords = 0;
for (int i = 0; i < stringArray.size(); i++) {
String s = stringArray[i];
if (s != null) {
retArr[uniqueWords][0] = str.indexOf(s);
int cnt = 1;
for (int j = i + 1; j < stringArray.size(); j++) {
if (s.equalsIgnoreCase(stringArray[j])) {
stringArray[j] = null;
cnt++;
}
}
retArr[uniqueWords][1] = cnt;
uniqueWords++;
}
}
int[][] newRetArr = new int[uniqueWords][2];
for (int i = 0; i < uniqueWords; i++) {
newRetArr[i][0] = retArr[i][0];
newRetArr[i][1] = retArr[i][1];
}
return newRetArr;
}
Use a HashMap to store the count and first index of each unique word.
Map<String, Map<String, int>> uniqueWords = new HashMap<>();
Then Change your loop through stringArray to only use the first outer loop. You don't need the inner loop.
In each iteration through stringArray, do
if(!uniqueWords.get(stringArray[i])) {
uniqueWords.put(stringArray[i], new HashMap<String, int>());
uniqueWords.get(stringArray[i]).put("Count", 0);
uniqueWords.get(stringArray[i]).put("Index", str.indexOf(stringArray[i]));
}
uniqueWords.get(stringArray[i]).get("Count")++;
You can then use the uniqueWords map to build your return array. I'll leave that for you to code.