How can I add a String to a 2-dimensional array? [duplicate] - java

This question already has answers here:
How to insert a string into a 2D string array in Java?
(3 answers)
Closed 4 years ago.
I have a project I am working in in my comp sci class and I completely forgot how to add a String to a 2-dimensional array. Any help would be appreciated.

You can do this like below:
String[][] array = new String[2][2]; // Initializing 2x2 array that will contains Strings
array[0][0] = "Some text"; // Put String object into array at index 0-0
System.out.println(array[0][0]); // Print element from array at index 0-0

Reading strings and store them to 2 dimensional array :
String[][] data=new String [10][10];
Scanner sc=new Scanner(System.in);
for(int i=0;i<data.length;i++){
for(int j=0;j<data[i].length;j++){
data[i][j]=sc.nextLine();
}
}
This will dynamically input the strings and store in 2D array.

The answer depends on which programming language you're using. Generally speaking, you'll access the 2D array through its rows and columns with indices. Then, to add an element to that location in the array, you'll simply assign a string to that particular location. For example, in Java you'll do the following:
String[][] arr = new String[10][10];
arr[0][0] = "Element 0";

Related

Sort 2D String Array with respect to a column in Java [duplicate]

This question already has answers here:
java Arrays.sort 2d array
(16 answers)
Closed 11 months ago.
I have String array which has 3 columns (id, name, city), I want to sort the array in ascending order with respect to name column. Please help me with this.
String[][] array1 = {{"54","jim","delhi"},
{"67","dwight","bangalore"},
{"39","pam","pune"}};
Expected output should be:
array1 = {{"67","dwight","bangalore"},
{"54","jim","delhi"},
{"39","pam","pune"}};
Use stream and Comparator Then you could sort that array how ever you want :
String[][] array1 = {{"54", "jim", "delhi"},
{"67", "dwight", "bangalore"},
{"39", "pam", "pune"}};
List<String[]> collect1 = Arrays.stream(array1).sorted(Comparator.comparing(a -> a[1])).collect(Collectors.toList());
String[][] sortedArray = new String[array1.length][3];
for (int i = 0; i < collect1.size(); i++) {
sortedArray[i] = collect1.get(i);
}
System.out.println(Arrays.deepToString(sortedArray));

How to randomly assign text to JButtons from String Array (without duplicates) [duplicate]

This question already has answers here:
How to generate a random permutation in Java?
(3 answers)
Closed 4 years ago.
I'm making a "Who Wants to be a Millionaire" type of quiz game for a University assignment but I can't find a way to randomly assign the 4 answer strings in my string array to my 4 answer JButtons without duplicates. I've tried a few solutions that I found online and the best I managed to do was randomly set the text but with a chance for a duplicate (a fairly high chance of course as there's only 4 strings).
Can anyone help?
if (currentGKQNum <=9){
currentQuestion = Game.getGKQuestion(currentGKQNum); //gets a question object at the index specified by currentGKQNum
questionLabel.setText(currentQuestion.getQuestion()); //gets the actual question string from the question object and assigns it to question label
currentGKQNum += 1;
}
else{
questionLabel.setText("End of general knowledge questions");
}
String[] answers = new String[] {currentQuestion.getAnswer1(),currentQuestion.getAnswer2(),currentQuestion.getAnswer3(),currentQuestion.getCorrectAnswer()};
answer1Button.setText(//need random string from answers[] here)
answer2Button.setText(//need random string from answers[] here)
answer3Button.setText(//need random string from answers[] here)
answer4Button.setText(//need random string from answers[] here)
Convert your array to list and shuffle the list.
String[] str = new String[] { "one", "two", "three" };
List<String> list = Arrays.asList(str);
Collections.shuffle(list);
Then get the texts from the list.

Java- Array creating a matrix based on the first two numbers of a read file [duplicate]

This question already has an answer here:
Convert string into two dimensional string array in Java
(1 answer)
Closed 5 years ago.
If I had a file text:
3#2/3#9#1
# and / are delimiters,
The first two numbers will always be the size of the matrix
In order to code this I would have to run a while loop, then int row and column to equal the scanned text?
First, split your text using the delimiter "/":
String text = "3#2/3#9#1";
String[] splits = text.split("/");
Now, splits[0] includes "3#2" and splits[1] includes "3#9#1".
Split the string splits[0] using the delimiter "#":
String[] dims = splits[0].split("#");
String dims[0] is the row value 3 and dims[1] is the column value 2.
Parse dims to integer in order to use them in construction of your matrix:
int r = Integer.parseInt(dims[0]);
int c = Integer.parseInt(dims[1]);
Create your matrix:
int[][] matrix = new int[r][c];

java split function. Store in an array from custom index? [duplicate]

This question already has answers here:
How I can index the array starting from 1 instead of zero?
(6 answers)
Closed 5 years ago.
I want to split a string and store in an array from custom index and NOT from "0" index by default.
Eg:
String splitThis = "cat,dog";
String [] array = splitThis.split(",");
System.out.println array[0] + array[1]
Above code prints "catdog" but I want "cat" to be store in index "1" and "dog" in index "2"
PS: I am very new to Programming and this is my very first question. Please correct me in syntax/logic/whatever :)
You may just add an empty entry at index 0. Something like this
String splitThis = "cat,dog";
String spit2 = ","+splitThis;
String [] array = split2.split(",");
System.out.println (array[1]);
System.out.println (array[2]);
You should probably create an entirely new class to handle that.

Java help regarding of arrays and printing out the individual lengths in the arrays

Currently, I have trouble attempting to print out the individual lengths efficiently.
String[] array = {"test", "testing", "tests"};
int arraylength = array[0].length();
System.out.println(arraylength);
Now, this does work in printing out the length however, it is inefficient and doesn't work if theoretically I don't know the length of the array.
Thanks for your input and I would appreciate if the code insisted contains "System.out.println" included so I don't have trouble figuring out which to print out.
Use this:
String[] array = {"test", "testing", "tests"};
for(String str : array) {
System.out.println(str.length());
}
If you are using Java 8 then it's a one liner :)
Arrays.asList(array).forEach(element -> System.out.println(element.length()));
What you are doing is, converting your array to a list and then running a for loop over it. Then for every element, you are printing out the length of the element.
EDIT
From one of the comment, this is even a better version of my code.
Arrays.stream(array).map(String::length).forEach(System.out::println);
Here first you convert your array to a list and then map each element to the function length of string class, then you run a foreach over it which prints out the mapped values.
String[] array = {"test", "testing", "tests"};
The length for array is:
int arraylength = array.length;
To have retrieve length for string:
for(String string: array) {
System.out.println(string.length());
}

Categories