How do you do this in java? To check your understanding of this section you shou
ID: 3694493 • Letter: H
Question
How do you do this in java?
To check your understanding of this section you should write two small functions. The first is a function which will sum an array of integers. Arrays have a built in forEach method which works on every element in the array. For example [1,2,3].forEach(foo) would call the function foo three times passing the arguments 1, 2 and 3 respectively. This function can do more advanced things as well if you want to read about it at MDN's forEach reference. You can use this or you can write your own forEach function. Either way, use a higher-order function to achieve this and do not simply directly loop through the array to sum it.
Next you should write a function which creates dialog functions. It should take a character name as an argument. It should return a function which takes a line of dialog and returns a string which quotes it and adds the reference to the speaker. For example:
So the output of this code to the console should be Donald Duck says "Hello There".
example:
function sumArr(arr) {
var sum = 0;
arr.forEach(function (v) {
sum += v;
});
return sum;
}
console.log(sumArr([2,2,3]));
function dialog(speaker) {
return function(speech){
return speaker + " says "" + speech + """;
}
}
var Donald = { name: "Donald Duck"};
Donald.speak = dialog(Donald.name);
console.log(Donald.speak("Hello there"));
Explanation / Answer
package foreach;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class ForEach {
JFrame frame = new JFrame();
public String input(){
Dialog d= new Dialog("Mec Donald");
return d.uname;
}
public Object in(){
Object result = JOptionPane.showInputDialog(frame, "Enter Dialog:");
return result;
}
public static void main(String[] a) {
ForEach fe=new ForEach();
System.out.println(fe.input()+ " says "+fe.in());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.