how can i scroll a view (recyclerview) in relation to my tts,
ive looked at onUtterance but it seems to only have a start and stop listener, so i need to think outside the box, i give my tts a string from an Arraylist like this
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < SpeakRecyclerGrid.recyclerView.getChildCount(); i++)
{
list.add(((EditText) SpeakRecyclerGrid.recyclerView.getChildAt(i)).getText().toString());
}
speakWords(words);
I was thinking about cutting the string up into sections and giving it to the TTS one string at a time and move the view as I go. I already give my gridlayout manager an int for the amount of columns (called columns).
The array list adds a comma after every word, so I was thinking something like
find the nth/(column) comma
split the string
check if tts is speaking and listen for onUtterance onDone to pass new string
read the string
move the view
and keep doing this until theres no words left and coding for the remainder % im not sure how to do all of that so if anyone wants to help feel free, (I think Im looking at StringUtils and creating each smaller string with a for loop and passing them to the tts in onUtteranceListener onDone, but im still a little new to android), but mainly does anyone have a better way
okay this is what i have so far but it could probably use some work im still an amateur, I've split the string into blocks based on the size of the screen, and the handler that scrolls the screen relies on the amount of letters in each broken up string, also the smoothscrolltoposition is scrolling a custom layout manager that scrolls pretty slowly im having an issue though where on some devices the array list counting the words will only reach 20 not sure why but ill ask and hopefully update this when ive fixed it so here is my speak and move method
public void speakAndMove(){
final ArrayList<String> list = new ArrayList<>();
SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(0);
for (int i = 0; i < SpeakRecyclerGrid.recyclerView.getChildCount(); i++) {
list.add(((EditText) SpeakRecyclerGrid.recyclerView.getChildAt(i)).getText().toString());
}
Integer numOfWords = list.size();
words = list.toString();
Integer count = 0;
Integer startPoint = 0;
scrollPos = 0;
final Integer speed = words.length() * 15;
Integer leftOver = 0;
final int columns = getResources().getInteger(R.integer.grid_columns);
System.out.println(numOfWords);
ArrayList<String> arrayList = new ArrayList<>();
if (list.size() <= columns) {
if (words.contains("[]")) {
speakWords("");
} else if (words.contains(", 's")) {
formatString = words.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (words.contains(", ing")) {
formatString = words.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(words);
}
}
if (list.size()>=columns) {
for (int i = 0; i < words.length(); i++) {
if (words.charAt(i) == ',') {
count++;
if (count == columns) {
String ab = words.substring(startPoint, i + 1);
//speakWords(ab);
if (ab.contains(", 's")) {
formatString = ab.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (ab.contains(", ing")) {
formatString = ab.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(ab);
}
startPoint = i + 1;
count = 0;
leftOver = words.length() - startPoint;
}
//SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(scrollPos);
System.out.println("main string"+" scroll " + scrollPos + " startpoint " + startPoint +" speed " + speed);
}
}
if (leftOver > 0) {
String ab2 = words.substring(startPoint, words.length());
//speakWords(ab2);
if (ab2.contains(", 's")) {
formatString = ab2.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (ab2.contains(", ing")) {
formatString = ab2.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(ab2);
}
//SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(scrollPos);
System.out.println("leftovers "+ leftOver + " scroll " + scrollPos + " startpoint " + startPoint +" count " + scrollPos);
count = 0;
//scrollPos = 0;
}
}
final Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
scrollPos = scrollPos + columns;
SpeakGrid.recyclerView.getLayoutManager().smoothScrollToPosition(SpeakGrid.recyclerView, null ,scrollPos);
System.out.println("position "+ scrollPos + " speed " + speed + " list size " + list.size());
if (scrollPos < list.size())
h.postDelayed(this,speed);
// close this activity
}
}, speed);
}
Related
So here's the question I need to answer: Implement a method that takes a research area as an input and returns the names of scientists associated with that area.
I've got a lot of the base code necessary but am struggling because I am trying to filter out the array of scientist professions to only return the scientist whose profession is the specified input. What I need help with is finding a way to make a new array with only certain filtered scientists and excluding the unspecified scientist. Any idea on how to change the code to return an array of only certain scientists would be very helpful! The issue is in the CheckField method, and I'll put my code below of the program:
public class computerScientists {
String name;
String researchArea;
String contribution;
// Constructor
public computerScientists(String NM, String RA, String C) {
this.name = NM;
this.researchArea = RA;
this.contribution = C;
}
public static void main(String[] args) {
computerScientists[] personDatabase = {
new computerScientists("Katherine Johnson", "Mathematician", "Mathmetician for NASA during space race"),
new computerScientists("Kimberely Bryant", "Entrepreneur & Activist", "Founded black girls code"),
new computerScientists("Mark Dean", "Inventor and Engineer", "Helped design and release some of the first computers"),
new computerScientists("Marie Van Brittan Brown", "Inventor and Pioneer", "Pieneered and invented an audio-video alarm system"),
new computerScientists("Marian R Croak", "Engineer", "Helped develop the Voice Over Internet Protocol (VOIP)")
};
//int size = person1.length
for(int i=0; i<personDatabase.length; i++){
System.out.println("Innovator " + String.valueOf(i + 1) + ": \n");
System.out.println("Name: " + personDatabase[i].name + "\n"
+ "Research Area: " + personDatabase[i].researchArea + "\n"
+ "Contribution: " + personDatabase[i].contribution);
System.out.println();
}
checkField("Inventor", personDatabase);
}
public static computerScientists[] checkField(String researchField, computerScientists[] array1) {
computerScientists[] newArray1 = new computerScientists[array1.length];
//int difference = newArray1.length - array1.length;
for (int i=0; i < array1.length; i++) {
if (array1[i].researchArea.contains(researchField)) {
newArray1[i].researchArea = String.valueOf(array1[i]);
}
}
for (int j=0; j<newArray1.length; j++) {
System.out.println(newArray1[j].researchArea);
}
return newArray1;
}
}
Here is the full code for it:
public void trackAll() {
int north = count(Direction.North) * 25;
int east = count(Direction.East) * 25;
int south = count(Direction.South) * 25;
int west = count(Direction.West) * 25;
if ((north == 0) && (east == 0) && (south == 0) && (west == 0)) {
this.player.sendMessage(ChatColor.RED + "Not a valid tracking compass.");
return;
}
for (Direction direction : Direction.values()) {
int length = count(direction) * 25;
if (length != 0) {
#SuppressWarnings("rawtypes")
Set players = new TreeSet();
for (Player player : Bukkit.getOnlinePlayers()) {
if (this.player.canSee(player)) if ((on(player, direction) & !player.equals(this.player))) {
players.add(player.getDisplayName());
}
}
FancyMessage message = new FancyMessage(direction + " (" + length + "): ").color(ChatColor.DARK_AQUA);
int i = 0;
for (String str : players) {
if (i == players.size() - 1)
message.then(str).color(ChatColor.GRAY).tooltip(ChatColor.GREEN + "Click here to track " + ChatColor.RESET + str + ChatColor.GREEN + ".").command("/track " + ChatColor.stripColor(str));
else {
message.then(str).color(ChatColor.GRAY).tooltip(ChatColor.GREEN + "Click here to track " + ChatColor.RESET + str + ChatColor.GREEN + ".").command("/track " + ChatColor.stripColor(str)).then(", ");
}
i++;
}
message.send(this.player);
}
}
}
And I also have another issue "Type mismatch: cannot convert from element type Object to Block"
public int count(Direction direction, boolean b) {
int length = 0;
#SuppressWarnings("rawtypes")
Set toDelete = new HashSet();
for (int i = 1; i < 10000; i++) {
Block next = this.middle.getRelative(BlockFace.valueOf(direction.toString().toUpperCase()), i);
if (next.getType() == Material.COBBLESTONE) {
length++;
toDelete.add(next); } else {
if (next.getType() == Material.STONE) {
length++;
toDelete.add(next);
toDelete.add(this.middle);
break;
}
length = 0;
toDelete.clear();
break;
}
}
if (b) {
for (Block block : toDelete) {
block.getWorld().playEffect(block.getLocation(), Effect.STEP_SOUND, block.getTypeId());
block.setType(Material.AIR);
}
}
return length;
}
I currently don't have someone that can look over the code I personally do not see the issue but I've been working on it for hours so yeah ;/ Thanks. This code is to do with a Minecraft plugin it's tracking a players location and sending the information to the player that executed the command.
Use
Set<String> players = new TreeSet<>();
and
Set<Block> toDelete = new HashSet<>();
I'm currently working on a school project (a small android game) and so far I've written a code which generates a random equation 2 seconds after the activity InGame is launched and displays it in a textview. Another 5 seconds later, the second equation is generated and displayed in a different textview. Now the user has to decide if the second equation has a bigger result than the first one by either pressing the button bigger or smaller. If it was correct, the next equation should be displayed and it would go on like this until the user decided wrong.
Here is my code so far:
(Code for the first equation):
// Generate random equation and display it in textview
String[] operationSet = new String[]{"+", "-", "/", "*"};
String equation;
static double doubleAnswer1;
public void start1() {
Random random = new Random();
int numOfOperations = random.nextInt(2) + 1;
List<String> operations = new ArrayList<>();
for (int i = 0; i < numOfOperations; i++) {
String operation = operationSet[random.nextInt(4)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(10)+1;
numbers.add(number);
}
String equation = "";
for (int i = 0; i < numOfOperations; i++) {
equation += numbers.get(i);
equation += operations.get(i);
}
equation += numbers.get(numbers.size() -1);
TextView TextEquation = (TextView)findViewById(R.id.textView_first_equation);
TextEquation.setText(equation);
// Evaluate the result of the equation
double doubleAnswer1 = eval(equation);
String stringAnswer = Double.toString(doubleAnswer1);
TextView textAnswer = (TextView)findViewById(R.id.textView4);
textAnswer.setText(stringAnswer);
}
(Code for second equation (basically same as for first equation except the name of the strings and doubles are different)):
String equation2;
static double doubleAnswer2;
public void start2() {
Random random = new Random();
int numOfOperations = random.nextInt(2) + 1;
List<String> operations = new ArrayList<>();
for (int i = 0; i < numOfOperations; i++) {
String operation = operationSet[random.nextInt(4)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(10)+1;
numbers.add(number);
}
String equation2 = "";
for (int i = 0; i < numOfOperations; i++) {
equation2 += numbers.get(i);
equation2 += operations.get(i);
}
equation2 += numbers.get(numbers.size() -1);
TextView TextEquation = (TextView)findViewById(R.id.textView3);
TextEquation.setText(equation2);
// Evaluate the result of the equation
double doubleAnswer2 = eval(equation2);
String stringAnswer = Double.toString(doubleAnswer2);
TextView textAnswer = (TextView)findViewById(R.id.textView_result2);
textAnswer.setText(stringAnswer);
}
And here is my onCreate code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ingame);
// Display first equation 2 seconds after the activity is launched
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
start1();
}
}, 2000);
final Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
#Override
public void run() {
start2();
}
}, 7000);
// Check if user was right or wrong
final Button buttonBigger = (Button)findViewById(R.id.button_bigger);
final Button buttonSmaller = (Button)findViewById(R.id.button_smaller);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(buttonBigger) && doubleAnswer1 < doubleAnswer2) {
Log.v("TAG", "you are right");
} else if(v.equals(buttonSmaller) && doubleAnswer1 > doubleAnswer2) {
Log.v("TAG", "you are right");
} else {
Log.v("TAG", "you are wrong");
}
}
};
buttonBigger.setOnClickListener(listener);
buttonSmaller.setOnClickListener(listener);
}
The app launches correctly and it also displays the first and second equation, but when I press one of the button, it tells me in the logcat you are wrong but I decided 100% correct. However if I debug the app, it tells me that doubleAnswer1 and doubleAnswer2 are both = 0. That's why it all ways tells me 'you are wrong'. I don't know how to fix this, maybe I need to store the doubleAnswer1 and doubleAnswer2 somewhere.
I really don't know what to do, so it would really help me if someone has an idea what to do.
If anything is unclear in my question, feel free to ask and I will try to clarify the problem.
Thank you in advance for your help!
I think your problem lies here:
double doubleAnswer1 = eval(equation);
I did a quick internet search and did not find any native function called eval(). Instead you should look into Script Engine Manager for java:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "40+2";
System.out.println(engine.eval(foo));
or exp4j which is shown here:
Executing math equation in Android
Edit:
change the following:
double doubleAnswer1 = eval(equation);
to:
doubleAnswer1 = eval(equation);
Similarly do the same for doubleAnswer2
I would like to display how linear search works visually.
I have created and ADT class of just integers. I also have a frame with buttons on it, when I hit the fillButton, it generates an array of random integers which are displayed on an array of buttons.
When i hit the findButton it will look for the specific number entered. As i am iterating through the array, i would like to make corresponding button change color.
I had created a similar program that iterated through an array of buttons, and changed the color as it went through. I had used Thread.sleep(), and it was just the main class. This time i have two classes and i am not sure how to go about it. I dont't know how to go about making a connection between the ADT class and the GUI class. I've used EventObjects and custom EventListeners before, but that was merely to store objects. Any help pointing in the right direction is appreciated. Thank you.
This is part of the ADT class
public class ADT {
private int[] a;
private int nElems;
private int SIZE = 60;
public ADT(){
a = new int[SIZE];
nElems=0;
}
public void initialPlacement(int index, int value,int initialCount){
a[index] = value;
nElems = initialCount;
}
public int linearSearch(int searchKey){
int index = 0;
for(int i = 0; i < nElems; i++){
if(getVal(i) == searchKey){
index = i;
break;
}
else{
index = -1;
}
}
return index;
}
And here is part of the GUI class
public NumberFrame(){///CONSTRUCTOR===========================
arr = new ADT();
//CREATE COMPONENTS
for(int i = 0; i < 60; i++){
listButtons[i] = new JButton(String.valueOf("_"));
}
for(int i = 0; i < 60; i++){
listLabels[i] = new JLabel(String.valueOf("["+i+"]"));
}
for(int i = 0; i < 60; i++){
listMiniPanels[i] = new JPanel();
listMiniPanels[i].add(listLabels[i]);
listMiniPanels[i].add(listButtons[i]);
}
fillButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
boolean sort = true;
if(linearRadio.isSelected()){
System.out.println("linear is checked");
fill(!sort);//fills half the array and array of buttons with random numbers, unsorted
}else if(binaryRadio.isSelected()){
System.out.println("binary is checked");
fill(sort);//fills half the array with random numbers and sorts it
}else{
JOptionPane.showMessageDialog(null, "Please check a sorting method");
}
}
})
findButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
int index= 0;
if(numberField.getText().equals("")){
System.out.print("Arr size = " + arr.size());
JOptionPane.showMessageDialog(null, "You did not enter a number");
}else {
try {
int searchKey = Integer.parseInt(numberField.getText());
if(linearRadio.isSelected()){
index = arr.linearSearch(searchKey);
listButtons[index].setBackground(Color.GREEN);
if(index > -1)
JOptionPane.showMessageDialog(null, "Found number " +searchKey + " # index [" + index + "]");
else
JOptionPane.showMessageDialog(null, "No such number");
}else{
index = arr.binarySearch(searchKey);
if(index > -1)
JOptionPane.showMessageDialog(null, "Found number " + searchKey+ " # index [" + index + "]");
else
JOptionPane.showMessageDialog(null, "No such number!");
}
} catch (NumberFormatException nfe) {
System.out.println("Arr size = " + arr.size());
JOptionPane.showMessageDialog(null, "Not an integer, pleas try again!");
}
}
}
});
}//=======CONSTRUCTOR END=============================
I've got some input files from my teacher wich we are supposed to test the program with. The task is to read from file, create a directed graph and print out the output. But if there is a cycle we are supposed to terminate the program.
I've got some files named house1 and house2. in the file house1 there isn't any cycles, but in house2 there is. But I can't figure out why my program can't find that cycle.
Here I have all the code, and any help saying where I should be looking at is preciated :)
import java.util.*;
import java.io.*;
import java.lang.*;
class Input {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("enter a filename!");
System.exit(1);
} else if (args.length == 1) {
String fil = args[0]+".txt";
LesFraFil(fil);
// skrivUt();
topSort();
} else {
System.out.println("too many parameters, try again...");
}
}
static int antTask;
static Task[] ids;
static int tTid;
static void LesFraFil(String fil) {
int i = 0;
int j;
try {
String lest;
Scanner in = new Scanner(new FileReader(fil));
Edge til;
int counter = 0;
antTask = in.nextInt();
ids = new Task[antTask];
System.out.println(antTask);
while (in.hasNextLine()) {
lest = in.nextLine();
// hvis tom linje, så hopper den over
if(lest.trim().length() == 0) continue;
String split[] = lest.split("\\s+");
int id = Integer.parseInt(split[0]);
String act = split[1];
int tid = Integer.parseInt(split[2]);
int staff = Integer.parseInt(split[3]);
int depA = Integer.parseInt(split[4]);
tTid += tid;
ids[i] = new Task(id, act, tid, staff);
j = 4;
/*
* Lesingen av inputen skal avbrytes når den leser 0.
* j er den som holder på hvor langt vi er i split arrayet
* når den møter på 0
*/
while(split[j].compareTo("0") != 0) {
int tmp = Integer.parseInt(split[j])-1;
// System.out.println(tmp+1 + " Aktivitetens navn : " + act); //+ " tiden aktiviteten tar tid: " + tid + " avhengihet: " + split[j]);
j++;
if (ids[tmp] == null) {
ids[tmp] = new Task(id, act, tid, staff);
ids[tmp].visited = true;
}
ids[i].cntPredecessors++;
if(ids[tmp].outEdge == null) {
ids[tmp].outEdge = new Edge(ids[tmp], ids[i]);
} else {
til = ids[tmp].outEdge;
while(til.neste != null) {
til = til.neste;
}
// til.neste = new Edge(ids[tmp], ids[i]);
}
}
counter++;
i++;
}
if (antTask == counter) {
System.out.println("Lesinga gikk som planlagt av fil: " + fil);
System.out.println("Total arbeidstid: " + tTid);// + antTask + " == " + counter );
} else {
System.out.println("Noe gikk galt avslutter!");
System.out.println(antTask + " || " + counter);
System.exit(2);
}
in.close();
} catch (Exception e) {
System.err.println("Dette gikk galt med lesinga: " + e.getMessage());
}
}
static void topSort() {
LinkedList<Task> list = new LinkedList<Task>();
ArrayList<Task> array = new ArrayList<Task>();
Task temp;
int totalTime = 0;
int counter = 0;
for(Task t : ids) {
if (t.cntPredecessors == 0) {
list.add(t);
}
}
while (!list.isEmpty()) {
temp = list.pop();
counter++;
array.add(temp);
System.out.println("Time " + totalTime + "\t Started task " + temp.id + "\t Staff: " + temp.staff + ", Task done " + temp.id);
totalTime += temp.time;
for (Task t : ids) {
if (--t.cntPredecessors == 0)
list.add(t);
}
}
if(counter < antTask) { // checking for loop
System.out.println(counter + " != " + antTask);
System.out.println("En løkke er funnet i grafen. Avslutter...");
System.exit(0);
}
System.out.println("Topological sort: " + Arrays.toString(array.toArray()));// den sorterte "arraylisten"
System.out.println("Total tid brukt er: " + totalTime);
}
}
class Task {
int id, time, staff;
int depA, depB;
String name;
int eStart, lStart;
Edge outEdge;
int cntPredecessors;
boolean visited;
Task(int id, String name, int time, int staff) {
this.id = id;
this.name = name;
this.time = time;
this.staff = staff;
visited = false;
}
public String getName() {
return name;
}
public String toString() {
return name;
}
}
class Edge {
Task fra, til;
Task id, name, time, staff;
Edge neste;
// Task fra, til;
Edge(Task fra, Task til) { //, Task fra, Task til) {//, Task name, Task time, Task staff) {
this.fra = fra;
this.til = til;
// this.id = id;
// this.fra = fra;
// this.til = til;
/* this.name = name;
this.time = time;
this.staff = staff;*/
}
public Task getTil() {
return til;
}
}
I'll write here some kind of simple algorithm, what you are doing is a topological sort
Important thing is that topological sort is using DFS algorithm O(V+E)
What you should do is to create some kind of additional attribute for each Node (let's call it String color and set it's initial value to white.
As you'll iterate through your nodes, set it's color to gray, and continue doing a DFS, after it's done, set it's color to black.
The point is - if you visit a node with color == gray or color == black you found a cycle
I recommend reading a Topological sort chapter from Introduction to Algorithms
And let's see your code!
You read something from input file and important part is here:
while (!list.isEmpty()) {
temp = list.pop();
counter++;
array.add(temp);
System.out.println("Time " + totalTime + "\t Started task " + temp.id + "\t Staff: " + temp.staff + ", Task done " + temp.id);
totalTime += temp.time;
for (Task t : ids) {
if (--t.cntPredecessors == 0) {
list.add(t);
}
}
}
well sorry for saying it like this, but your code is little messy, without english documentation, etc. but I think you are missing the part of coloring your nodes, that can be the reason why you can't find a cycle ( and I suppose you never end ) , because you miss to "color" your nodes, so nobody knows that you have already visited them
btw my "color" attribute is called visited in your code (you can use boolean but then you can't color it to gray/black/white as in the book I posted here)
I guess you set it to true during initialization (you should set it to false and set it to true if you have already processed/visited the node)
// Sorry if I'm wrong but it's 1A.M. here, I just think this might be the issue
// + if you do this on directed graph, and exit if you detect cycle, you get and cycle detection algorithm in O(V) time :)