Using the text to speech API I want to change the string array to increment from index 0 string and when it reaches the end it will go back to the beginning.
At the moment it uses a random generator and the method works as follows:
public static void sayHello() {
// Select a random hello.
int helloLength = HELLOS.length;
String hello = HELLOS[RANDOM.nextInt(helloLength)];
mTts.speak(hello,
TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue.
null);
}
HELLOS is the array and it holds the strings:
String [] HELLOS = {"One" "Two" "Three" "Four"};
Appreciate any help
Thanks.
When you want to increment an index but loop around to zero again modulo is your friend.
int currentHelloIndex = 0;
public static void sayHello() {
// Select a random hello.
int helloLength = HELLOS.length;
String hello = HELLOS[currentHelloIndex];
currentHelloIndex = (currentHelloIndex + 1) % helloLength;
mTts.speak(hello,
TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue.
null);
}
Related
I am developing word scramble android app. I want to display the String of word in Sequence order but in below code it get random word from the dictionary. My question is how to change my code to get words from Dictionary in Sequence Order?
String[] dictionary=
{"One","Server","Terminate","Analyze","Finish","Start","Wonder","Slow"};
r = new Random(System.currentTimeMillis());
newGame();
// shuffle algorithm
private String shuffleWord(String word){
List<String> letters = Arrays.asList(word.split(""));
Collections.shuffle(letters);
String Shuffled="";
for (String letter : letters ){
Shuffled += letter;
}
return Shuffled;
}
private void newGame(){
// get random word from dictionary
currentWord= dictionary[r.nextInt(dictionary.length)];
// show the shuffled word
tv_word.setText(shuffleWord(currentWord));
// clear the textfield
et_guess.setText("");
// switch buttons
b_new.setEnabled(false);
b_check.setEnabled(true);
}
}
Actually you pick your word with a random position
r = new Random(System.currentTimeMillis());
using an integer random from 0 to ArrayOfWords lenght.
currentWord= dictionary[r.nextInt(dictionary.length)];
Why you dont try to make a counter instead?
int r = 0;
while (r<dictionary.length()) {
currentWord = dictionary[r];
r++;
}
Or I don't understand your answer. But there is the pseudo of what I understand.
I have managed to extract the first letters on a sentence and store that into a variable.
String[] result = matches.toString().split("\\s+");
// The string we'll create
String abbrev = "";
// Loop over the results from the string splitting
for (int i = 0; i < result.length; i++){
// Grab the first character of this entry
char c = result[i].charAt(0);
// If its a number, add the whole number
if (c >= '0' && c <= '9'){
abbrev += result[i];
}
// If its not a number, just append the character
else{
abbrev += c;
}
}
I then store the values into a Final String Array;
List<String> list = Arrays.asList(abbrev);
final String[] cs12 = list.toArray(new String[list.size()]);
I then set the values into a alert dialog as follows:
builder2.setItems(cs12[0].toString().split(","), new DialogInterface.OnClickListener(){
My next task is when the user selects one of the items for it to go into the text view. However it doesn't let me do this.
public void onClick(DialogInterface dialog, int item) {
TextView speechText = (TextView)findViewById(R.id.autoCompleteTextView1);
speechText.setText(Arrays.toString(cs12));
// TextView speechText = (TextView)findViewById(R.id.autoCompleteTextView1);
// speechText.setText(matches.get(item).toString());
However for my other parts matches.get works fine but I cant seem to get cs12.get.
Any Ideas?
Thanks
Use cs12[0].toString().split(",")[item] to show selected item in TextView:
String[] strArr= cs12[0].toString().split(",");
speechText.setText(strArr[item]);
I am using a database to show random message at the push of a button.
Every time the button is pushed, a random number is generated and displays a message that corresponds to that number.
Of course, the same message can appear twice as the same number can be generated twice.
So I am creating a string, and I am concatenating each number when the button is pushed.
If the new random number is in the String, then I want to get another number. If that number is in that String, I want to get another number etc etc (Regression?).
I also want to have a global count that I can change, so if the String reaches a size of 9 numbers, it will be reset to "".
String randomList; //global
final int MAX_STRING_LENGTH = 9;
Integer randomNumber = getRandomMessage(messages.size());
if(randomList.length() > 0)
{
if(!randoms.contains(randomNumber.toString()))
{
messageText.setText(messages.get(randomNumber));
}
}
Create a boolean Array of 9 elements
boolean[] check = new boolean[9];
Everytime you use a number, set check[number] to true
void useNumber(int number){
check[number] = true;
}
To check if you already used this number
boolean checkNumber(int number){
return check[number];
}
To reset check
void resetCheck(){
for(int i = 0; i < check.length; i++) check[i] = false;
}
Edit:
Get a string for a given number, resetCheck if necessary;
String getString(int number){
if(usedString == check.length){
resetCheck();
usedString = 0;
}
if(checkNumber(number)){
return getString(getRandomNumber());
}else{
usedString++;
return strings[number];
}
}
I think you can better use a boolean array. You can store the boolean array with the SharedPreferences class. A boolean array is more flexible and you can retrieve the values in constant time. You can also easily make it larger when you have more random messages.
Do a simple trick Hope this works for you
buttonRandom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Collections.shuffle(messages);
messageText.setText(messages.get(0));
}
});
My problem is I have around 1000+ records in an Android App
string field1;
string field2;
string field3;
string field4;
//...
I want to search in this set of records and get the best results on two fields (field1 and field2).
Currently I read each record and compare() (string compare) with the text i want to search so that takes a long time.
What is the best method to perform search?
Store each records in SQLite DB and do "select query where like"
Hash-Mapped
? any other suggestions?
Or may be create an Index of the records and do search.
If you want to search for not exact matches, I would try to make an ArrayList of MyAppRecord where
public class MyAppRecord {
private String record;
private int deviance;
}
and get for each record the deviance of the String you want to find with:
public static int getLevenshteinDistance (String s, String t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
int p[] = new int[n+1]; //'previous' cost array, horizontally
int d[] = new int[n+1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i<=n; i++) {
p[i] = i;
}
for (j = 1; j<=m; j++) {
t_j = t.charAt(j-1);
d[0] = j;
for (i=1; i<=n; i++) {
cost = s.charAt(i-1)==t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
}
save it to your MyAppRecord-object and finally sort your ArrayList by the deviance of its MyAppRecord-objects.
Note that this could take some time, depending on your set of records. And NOTE that there is no way of telling wether dogA or dogB is on a certain position in your list by searching for dog.
Read up on the Levensthein distance to get a feeling on how it works. You may get the idea of sorting out strings that are possibly to long/short to get a distance that is okay for a threshold you may have.
It is also possible to copy "good enough" results to a different ArrayList.
I have a question regarding the following code
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(4);
String wordList[] = new String[4];
{
wordList[0] = "Red";
wordList[1] = "Blue";
wordList[2] = "Green";
wordList[3] = "Orange";
}
String wordToDisplay = wordList[randomInt];
This code works fine however I would like to know if it was possible to get it to not pick the same word two times in a row. For example, if it just selected "Red" then it would not pick "Red" again the next consecutive time. I read something about DISTINCT but I'm not sure if that's along the right path.
Here is the code for the button which uses this
final Button button1 = (Button) findViewById(R.id.button1);
final TextView textView = (TextView) findViewById(R.id.text_random_text);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(9);
String wordToDisplay = wordList[randomInt];
textView.setText(wordToDisplay);
Thankyou for your help
go for list and remove color once used:
private static ArrayList<String> arrayList = new ArrayList<String>();
private static Random random = new Random();
public static void fillList(){
arrayList.add("Red");
arrayList.add("Blue");
arrayList.add("Green");
arrayList.add("Orange");
}
public static String getNextRandomColor(){
if(arrayList.isEmpty()){
fillList();
}
return arrayList.remove(random.nextInt(arrayList.size()));
}
You can do this in two way (probably more but two that I can think of right now):
1) Create a function that uses a global variable to store the last generated random number.
It will look something like this:
int myRand(int i) {
int aux;
Random randomGenerator = new Random();
do {
aux = randomGenerator.nextInt(i);
} while (aux != lastRandGenerated);
lastRandGenerated = aux;
return aux;
}
, where lastRandGenerated is a global variable that you initialize to 0.
Then you use this function to generate random numbers.
2) You can create a class that has a function very similar to the one above and then instantiate an object of that class and use that to generate your random numbers. In the class create a static variable that will remember the last generated random number. Use that instead of the global variable.
The specifics are a bit out of my league but as a math problem there are 24 combinations (4 * 3 * 2 * 1). As heavy handed as this might sound, worst case you could work out all the combos and then pick a one out of 24 random.