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

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.

Related

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

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

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 count how many times a char from string occurs from an array [duplicate]

This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 5 years ago.
I'm new to java and I cant find the answer to this problem.
If I have two character arrays like this with counters:
Character[] abc = {'A','B','C'};
int countABC = 0;
Character[] def = {'D','E','F'};
int countDEF = 0;
And a string like this:
String something = "ABCDEFGHABAB";
How to increase the counters?
If you loop through each of the characters in the string and then within the loop use 2 'if' functions, one for each array then you can use the indexOf() function to search an array for that value. If the value is negative then it wasn't found and you don't increase the counter.
Here is some more info on indexOf():
https://www.tutorialspoint.com/java/java_string_indexof.htm

How to take in a String and return an array after modifying the String? [duplicate]

This question already has answers here:
How to split a String by space
(17 answers)
Closed 5 years ago.
I want to take in a String and split it every time I find a space. And then store each of these pieces into an array.
Let's say I have this string:
String names = "amy bob lily harry luna james";
I also have this method declaration:
public static String[] seperateNames(String names) {
String[] newNames;
// Some code here
return newNames[];
}
What would I fill this method with so I can get something like this:
newNames = {"amy", "bob", "lily", "harry", "luna", "james"};
What I think I should do is create a for-loop and inside it have an if-statement that can check if there's space.
But I really don't know how to go about doing this.
I also think I will need to use trim() after everything is stored in an array to remove spaces before and after each name stored in the array.
Any help or advice appreciated. Thanks!
public static String[] seperateNames(String names) {
return names.split(" ");
}
To start you off on your assignment, String.split splits strings on a regular expression, this expression may be an empty string:
String[] ary = "abc".split("");
Yields the array:
(java.lang.String[]) [, a, b, c]
Getting rid of the empty 1st entry is left as an exercise for the reader :-)
Note: In Java 8, the empty first element is no longer included.

How to remove [ ] from a Collection in Java? [duplicate]

This question already has answers here:
Java: convert List<String> to a join()d String
(23 answers)
Closed 6 years ago.
I have a collection arraylist in Java.
For example when I do:
test is the collection.
System.out.println(test.getTester());
Why do I get the result of:
[jamesbond]
I only want jamesbond but why do they give me the [ ] too?
From your question, assuming that you have ArrayList of Strings as the collection (since it's printing [jamesbond]).
When you write test.getTester(), the java calls the toString() method on the collection and it'll print elements between [ and ] with separated by comma.
You can use iterator over the collection to print the individual elements.
List<String> stringColl = Arrays.asList("jamesbond","danielocean");
// Java 8
stringColl.forEach(stringElem -> System.out.println(stringElem));
// Java 7 or below
for(String stringElem : stringColl){
System.out.println(stringElem);
}
Just remove the first and last character with substring method.
String foo = test.getTester().toString();
System.out.println(foo.substring(1, foo.length() - 1);
Note: If you try to print an array with more than one object, you will see that the brackets are always the first and last character, the elements themselves are sperated with commas.
Let a String help you with that and use the replace method...
Example:
// if your list doesnt contain any element with the chars [ or ]
String listNoBrackets = l.toString().replace("[", "").replace("]", "");
System.out.println(listNoBrackets);
// if your list contains at least 1 element with the chars [ or ]
String listWithBrackets = l.toString().substring(1, l.toString().length() - 1);
System.out.println(listWithBrackets);

Categories