public class ChatBot {
String[][] chatBot={
// standard greetings
{ "hi", "hello", "hey" }, { "hi user"},
// question greetings
{ "how are you" }, { "good"},
// default
{ "I did not understand. Please try something else" }, };
public ChatBot() {
}
public String checkAnswer(String message) {
byte response = 0;
int messageType = 0;
String x = null;
List temp;
int cblength = chatBot.length - 1;
while (response == 0 && messageType <= cblength) {
temp = Arrays.asList(chatBot[messageType]);
if (temp.contains(message)) {
response = 2;
x = chatBot[(messageType) + 1][0];
}
messageType = messageType + 2;
if (response == 1)
x = chatBot[chatBot.length - 1][0];
}
}
return x;
}
I created this simple chatbot to test my chat application. It uses a two dimensional String Array to save the possible inputs and outputs. The checkAnwer method receives the user input and is supposed to return the correct output. It uses a while loop to check the input fields and return the corresponding output, if the content of the field matches with the array. If the loop reaches the end of the array, it is supposed to return the default answer. The first group of inputs (hi/hello/hey) returns the right output(hi user), but every other input causes the while-loop to exceed the array length.
Edit
I removed the error in the Code, all inputs are now accepted, non valid inputs return null.
Edit2
I changed int cblength = chatBot.length - 1;
to
int cblength = chatBot.length;
and messageType = messageType + 2;
to
if ((messageType+2)>=cblength)
{
response=1;
}
else {
messageType = messageType + 2;
}
The code is now working properly.
If I'm understanding your code correctly, chatBot has a length of 5. On each full pass of the while loop, messageType is incrementing by 2. This means that on the second pass, messageType = 2. This means that on the following line :
x = chatBot[(messageType * 2) + 1][0];
We are looking for (2*2)+1 = 5 as an index. As the list is of length 5, the max index is 4, causing the IndexOutOfBoundsException.
There are two main ways I could see to fix this:
Reconsider whether you really need to repeat the same block of code twice in the while loop - this adds a bit of unneeded complexity, and reduces how often the while conditions are checked.
Update the while condition to check that any (messageType*2)+1 which will occur during the iteration will still be within the bounds of the array.
Related
I have the sums of x and y coordinates and I need to calculate the mean
float [][] sums = new float[n][2];
e.g. my array consists of:
{ [ 8,6 ],
[ 4,2 ] }
After the dividing to 2:
{ [ 4,3 ],
[ 2,1 ] }
I can do this with loops but I wonder if It is possible to do it with 1 function.
You can simply encapsulate your for loops into a function and call it:
import java.util.Arrays;
void setup(){
float [][] sums = new float[][]{ { 8,6 },
{ 4,2 } };
print("pre: ");
System.out.println(Arrays.deepToString(sums));
matMul(sums,0.5);
print("post:");
System.out.println(Arrays.deepToString(sums));
}
void matMul(float[][] data,float multiplier){
for(int y = 0; y < data.length; y++){
for(int x = 0; x < data[y].length; x++){
data[x][y] *= multiplier;
}
}
}
Here are a few pointers if you're just getting started with functions.
The simplest thing a function can do is encapsulate a bunch of instructions, but
no allow any data from outside the function to be read and not return any data out.
Here is a very simple/boring example:
void sayHello(){
println("hello");
}
The point of is it to get familiar with the syntax.
A function has:
a (return) type: if the function returns any result, what kind of result is it ? (a number, a string of text, an Object, etc.), if not it's simply void
a name (so we can call it)
arguments (0 or more) within parenthesis, each having a type and name (similar to a local variable)
a body delinieated by the { and } symbols: this everything defined within this block is only visible to this block (except what's returned, if anything). This is known as the scope of the function
You've probably already defined functions that don't return results: void setup(){}, void draw(){}
You've probavly already called functions before: used the name and arguments (if any) in paranthesis (e.g. println("hi");, point(50,50);, noCursor();, etc.)
Here's a simple example of a function that takes two inputs and returns one output: the sum of the inputs:
int sum(int a, int b){
return a+b;
}
Instead of void we return a result of int type and the arguments are a couple of integers named a and b. The only other extra thing is the return keyword used to (you guessed it) return the result (and exit the function block).
Here a basic example calling the function:
void setup(){
println(add(2,2));
println(add(4,4));
}
int add(int a, int b){
return a + b;
}
If you want to read more on it check out Kevin Workman's Creating Functions Processing Tutorial
Bare in mind the the void method transforms the array reference to pass as an argument to the function. There may be situations where you don't want to change the input data, yet return the result. In such as case you can either copy the array beforehand and pass a copy, or have a version of the function that makes a copy for you:
import java.util.Arrays;
void setup(){
float [][] sums = new float[][]{ { 8,6 },
{ 4,2 } };
print("sums: ");
System.out.println(Arrays.deepToString(sums));
float[][] result = matMul(sums,0.5);
print("result: ");
System.out.println(Arrays.deepToString(result));
print("original:");
System.out.println(Arrays.deepToString(sums));
}
float[][] matMul(float[][] data,float multiplier){
// check input data
if(data == null || data.length == 0){
println("no data to multiply, returning null");
return null;
}
// make another array of the same shape
float[][] result = new float[data.length][data[0].length];
// do the multiplcation, storing the result into the duplicate array
for(int y = 0; y < data.length; y++){
for(int x = 0; x < data[y].length; x++){
result[x][y] = data[x][y] * multiplier;
}
}
// return the result
return result;
}
Notice a few checks at the start of the function: in general it's a good idea to validata data coming in, just in case, and display a message that will make it easy to fix the issue (withouth spending to much figuring out what the error means).
Something like this:
Arrays.stream(sums).map(y -> Arrays.stream(y).map(x -> x/2).toArray(Double[]::new))
.toArray(Double[][]::new);
probably should do what you want.
Problem:
Remove the substring t from a string s, repeatedly and print the number of steps involved to do the same.
Explanation/Working:
For Example: t = ab, s = aabb. In the first step, we check if t is
contained within s. Here, t is contained in the middle i.e. a(ab)b.
So, we will remove it and the resultant will be ab and increment the
count value by 1. We again check if t is contained within s. Now, t is
equal to s i.e. (ab). So, we remove that from s and increment the
count. So, since t is no more contained in s, we stop and print the
count value, which is 2 in this case.
So, here's what I have tried:
Code 1:
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
{
i = s.indexOf(t);
s = s.substring(0,i) + s.substring(i + t.length());
}
else break;
++count;
}
return count;
}
I am just able to pass 9/14 test cases on Hackerrank, due to some reason (I am getting "Wrong Answer" for rest of the cases). After a while, I found out that there is something called replace() method in Java. So, I tried using that by replacing the if condition and came up with a second version of code.
Code 2:
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
s.replace(t,""); //Marked Statement
else break;
++count;
}
return count;
}
But for some reason (I don't know why), the "Marked Statement" in the above code gets executed infinitely (this I noticed when I replaced the "Marked Statement" with System.out.println(s.replace(t,""));). I don't the reason for the same.
Since, I am passing only 9/14 test cases, there must be some logical error that is leading to a "Wrong Answer". How do I overcome that if I use Code 1? And if I use Code 2, how do I avoid infinite execution of the "Marked Statement"? Or is there anyone who would like to suggest me a Code 3?
Thank you in advance :)
Try saving the new (returned) string instead of ignoring it.
s = s.replace(t,"");
replace returns a new string; you seemed to think that it alters the given string in-place.
Try adding some simple parameter checks of the strings. The strings shouldn't be equal to null and they should have a length greater than 0 to allow for counts greater than 0.
static int maxMoves(String s, String t) {
int count = 0,i;
if(s == null || s.length() == 0 || t == null || t.length() == 0)
return 0;
while(true)
{
if(s.contains(t) && !s.equals(""))
s = s.replace(t,""); //Marked Statement
else break;
++count;
}
return count;
}
You might be missing on the edge cases in the code 1.
In code 2, you are not storing the new string formed after the replace function.
The replace function replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
Try this out:
public static int findCount(String s, String t){
if( null == s || "" == s || null == t || "" == t)
return 0;
int count =0;
while(true){
if(s.contains(t)){
count++;
int i = s.indexOf(t);
s = s.substring(0, i)+s.substring(i+t.length(), s.length());
// s = s.replace(t,"");
}
else
break;
}
return count;
}
String r1="ramraviraravivimravi";
String r2="ravi";
int count=0,i;
while(r1.contains(r2))
{
count++;
i=r1.indexOf(r2);
StringBuilder s1=new StringBuilder(r1);
s1.delete(i,i+r2.length());
System.out.println(s1.toString());
r1=s1.toString();
}
System.out.println(count);
First of all no logical difference in both the codes.
All the mentioned answers are to rectify the error of code 2 but none told how to pass all (14/14) cases.
Here I am mentioning a test case where your code will fail.
s = "abcabcabab";
t = "abcab"
Your answer 1
Expected answer 2
According to your code:
In 1st step, removig t from index 0 of s,
s will reduce to "cabab", so the count will be 1 only.
But actual answer should be 2
I first step, remove t from index 3 of s,
s will reduced to "abcab", count = 1.
In 2nd step removing t from index 0,
s will reduced to "", count = 2.
So answer would be 2.
If anyone know how to handle such cases, please let me know.
As title says I need to do the following. But I somehow am getting the wrong answer, perhaps something with the loops is wrong?
And here's what I have coded so far, but it seems to be giving me the wrong results. Any ideas, help, tips, fixes?
import java.util.ArrayList;
public class pro1
{
private String lettersLeft;
private ArrayList<String> subsets;
public pro1(String input)
{
lettersLeft = input;
subsets = new ArrayList<String>();
}
public void createSubsets()
{
if(lettersLeft.length() == 1)
{
subsets.add(lettersLeft);
}
else
{
String removed = lettersLeft.substring(0,1);
lettersLeft = lettersLeft.substring(1);
createSubsets();
for (int i = 0; i <= lettersLeft.length(); i++)
{
String temp = removed + subsets.get(i);
subsets.add(temp);
}
subsets.add(removed);
}
}
public void showSubsets()
{
System.out.print(subsets);
}
}
My test class is here:
public class pro1
{
public static void main(String[] args)
{
pro1s = new pro1("abba");
s.createSubsets();
s.showSubsets();
}
}
Try
int numSubsets = (int)java.lang.Math.pow(2,toSubset.length());
for (int i=1;i<numSubsets;i++) {
String subset = "";
for (int j=0;j<toSubset.length();j++) {
if ((i&(1<<j))>0) {
subset = subset+toSubset.substring(j,j+1);
}
}
if (!subsets.contains(subset)) {
subsets.add(subset);
}
}
where toSubset is the string that you wish to subset (String toSubset="abba" in your example) and subsets is the ArrayList to contain the results.
To do this we actually iterate over the power set (the set of all subsets), which has size 2^A where A is the size of the original set (in this case the length of your string).
Each subset can be uniquely identified with a number from 0 to 2^A-1 where the value of the jth bit (0 indexed) indicates if that element is present or not with a 1 indicating presence and 0 indicating absence. Note that the number 0 represents the binary string 00...0 which corresponds to the empty set. Thus we start counting at 1 (your example did not show the empty set as a desired subset).
For each value we build a subset string by looking at each bit position and determining if it is a 1 or 0 using bitwise arithmetic. 1<<j is the integer with a 1 in the jth binary place and i&(i<<j) is the integer with 1's only in the places both integers have a 1 (thus is either 0 or 1 based on if i has a 1 in the jth binary digit). If i has a 1 in the jth binary digit, we append the jth element of the string.
Finally, as you asked for unique subsets, we check if we have already used that subset, if not, we add it to the ArrayList.
It is easy to get your head all turned around when working with recursion. Generally, I suspect your problem is that one of the strings you are storing on the way down the recursion rabbit hole for use on the way back up is a class member variable and that your recursive method is a method of that same class. Try making lettersLeft a local variable in the createSubsets() method. Something like:
public class Problem1
{
private String originalInput;
private ArrayList<String> subsets;
public Problem1(String input)
{
originalInput = input;
subsets = new ArrayList<String>();
}
// This is overloading, not recursion.
public void createSubsets()
{
createSubsets(originalInput);
}
public void createSubsets(String in)
{
if(in.length() == 1)
{
// this is the stopping condition, the bottom of the rabbit hole
subsets.add(in);
}
else
{
String removed = in.substring(0,1);
String lettersLeft = in.substring(1);
// this is the recursive call, and you know the input is getting
// smaller and smaller heading toward the stopping condition
createSubsets(lettersLeft);
// this is the "actual work" which doesn't get performed
// until after the above recursive call returns
for (int i = 0; i <= lettersLeft.length(); i++)
{
// possible "index out of bounds" here if subsets is
// smaller than lettersLeft
String temp = removed + subsets.get(i);
subsets.add(temp);
}
subsets.add(removed);
}
}
Something to remember when you are walking through your code trying to think through how it will run... You have structured your recursive method such that the execution pointer goes all the way down the recursion rabbit hole before doing any "real work", just pulling letters off of the input and pushing them onto the stack. All the "real work" is being done coming back out of the rabbit hole while letters are popping off of the stack. Therefore, the first 'a' in your subsets list is actually the last 'a' in your input string 'abba'. I.E. The first letter that is added to your subsets list is because lettersLeft.length() == 1. (in.length() == 1 in my example). Also, the debugger is your friend. Step-debugging is a great way to validate that your code is actually doing what you expect it to be doing at every step along the way.
I'm working on a card game with 1-4 players. When I start a new game it will instantiate a class DialogCreator that asks you to enter the number of players you want. Here is the code for the DialogCreator:
private class DialogCreator {
/**
* Creates a dialog for the input of how many players you want in the game.
* Takes an integer between 1 and 4.
* #param msg
* #return
*/
int createIntDialog(String msg) {
String inValue = null;
String error_msg = "";
int v = 0;
while ((inValue = JOptionPane
.showInputDialog(msg + error_msg + ":")) != null) {
error_msg = "";
int inVal = Integer.parseInt(inValue);
try {
if(inVal >= 1 && inVal <= 4)
v = inVal;
break;
} catch (NumberFormatException nfe) {
error_msg = "(Entered values can only be integers between 1 and 4)";
}
}
return v;
}
}
I thought that this code would try to set v = inVal only if 1 <= inVal >= 4 and if inVal is < 1 or > 4 it would go to catch and give me the error message. This does not work and I get an IndexOutOfBoundsException if I enter a number that is not between 1 and 4. It works fine to check if I enter a String that can not be parsed to int. Can someone tell me what I'm doing wrong here?
The problem is here:
if(inVal >= 1 && inVal <= 4)
v = inVal;
break;
Without any braces, only the v = inVal; is under the if statement. Therefore, whatever inVal is, you are going to break out of the while loop and return 0 (v was initialized to 0). Then I guess that if this method returns 0, the rest of your code fails. If you add braces around then you can assure that you will break only if the input is valid:
if(inVal >= 1 && inVal <= 4) {
v = inVal;
break;
}
As a side-note, you should be consistent with your namings: error_msg doesn't respect Java naming conventions.
A simpler solution is to just use a JOptionPane with a combo box containing the values 1-4. Then there is no need for any edit checking.
Read the section from the tutorial on Getting User Input From a Dialog for an example showing how this is done.
Or if you want to insist that the user enter a number then the tutorial also contains a section on Stopping Automatic Dialog Closing, which is a little more complicated, but a better overall solution for using the JOptionPane.
I am trying to send two variables from one sketch to another, using the oscP5 library for processing.
The message I am sending is created like this:
OscMessage myMessage = new OscMessage("/test");
myMessage.add(title);
myMessage.add("Zeit");
oscP5.send(myMessage, remoteLocation);
In the second sketch, I receive the data like that:
void oscEvent(OscMessage theOscMessage) {
if(theOscMessage.checkAddrPattern("/test")) {
String title = theOscMessage.get(0).stringValue();
String layoutType = theOscMessage.get(1).stringValue();
addToQueue(title, layoutType);
}
}
And here my simplified addToQueue function:
void addToQueue(String title, String layoutType) {
if(!existsInQueues(title)) {
upcomingHeadlines.add(new Headline(title, printAxis, scrollSpeed, layoutType));
}
}
Every time I start the sketches, I get the error:
ERROR # OscP5 ERROR. an error occured while forwarding an OscMessage to a method in your program. please check your code for any possible errors that might occur in the method where incoming OscMessages are parsed e.g. check for casting errors, possible nullpointers, array overflows ... .
method in charge : oscEvent java.lang.reflect.InvocationTargetException
I have been able to track the problem down to the layoutType-Variable. If I change
String layoutType = theOscMessage.get(1).stringValue();
to
String layoutType = "Zeit";
no error occurs.
That is quite confusing, because both versions should have the same result.
The error message does not help me in any way.
Edit
I have compared the two possible variables like that:
String layoutType = theOscMessage.get(1).stringValue();
String layoutTypeB = "Zeit";
if(layoutType.equals(layoutTypeB)) println("Same String!");
Since gets printed to the console, both have to be the same … I really do not know where to search for an error anymore.
Edit 2
I have wrapped my second sketch in try {...} catch(Exception ex) {ex.printStackTrace();} like that:
void oscEvent(OscMessage theOscMessage) {
try {
if(theOscMessage.checkAddrPattern("/test")) {
if(debug && debugFeed) println("Received message from other sketch.");
String title = theOscMessage.get(0).stringValue();
String layoutTypeO = (String)theOscMessage.get(1).stringValue();
String layoutType = "Zeit";
if(debug && debugTemp) {
if(layoutType.equals(layoutTypeO)) println("IS DOCH GLEICH!");
}
if(debug && debugFeed) println("Parsed Information.");
if(debug && debugFeed) println("-----");
addToQueue(title, layoutTypeO);
}
} catch(Exception ex) {ex.printStackTrace();}
}
That gives me this error as result:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at printer$Headline.useLayout(printer.java:260)
at printer$Headline.<init>(printer.java:188)
at printer.addToQueue(printer.java:407)
at printer.oscEvent(printer.java:395)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at oscP5.OscP5.invoke(Unknown Source)
at oscP5.OscP5.callMethod(Unknown Source)
at oscP5.OscP5.process(Unknown Source)
at oscP5.OscNetManager.process(Unknown Source)
at netP5.AbstractUdpServer.run(Unknown Source)
at java.lang.Thread.run(Thread.java:744)
Edit 4
Constructor for my Headline-Class:
class Headline {
//Define Variables
Layout layout;
String title, lastHeadline;
float yPos, speed;
float transparency = 255;
boolean fullyPrinted = false;
int boundingBoxHeight;
// Initialize Class Function
Headline(String t, float y, float s, String lay) {
title = t;
yPos = y;
speed = s;
layout = useLayout(lay);
boundingBoxHeight = calculateTextHeight(title);
}
You might want to know about useLayout() too, so here it is:
Layout useLayout(String name) {
ArrayList layoutVariants = new ArrayList<Layout>();
int existingLayouts = layouts.size();
Layout chosenLayout;
for(int i = 0; i < existingLayouts; i++) {
Layout currentLayout = (Layout)layouts.get(i);
if(currentLayout.layoutType == name) {
layoutVariants.add(currentLayout);
}
}
if(layoutVariants != null) {
int rand = (int)(Math.random() * layoutVariants.size());
chosenLayout = (Layout)layoutVariants.get(rand);
} else {
chosenLayout = (Layout)layouts.get((int)(Math.random() * existingLayouts));
}
return chosenLayout;
}
There are two problems with your code, and both of them are in your useLayout method.
The first problem is that you are not comparing Stringss correctly on this line:
if(currentLayout.layoutType == name) {
name is a String, and I assume currentLayout.layoutType is too. Two Strings that are equal but not the same will not compare equal under ==. As a result of this, your layoutVariants list will quite probably be empty at the end of the for loop.
This line should read:
if(currentLayout.layoutType.equals(name)) {
See also this question.
The second problem is that you don't correctly handle the case that the layoutVariants list is empty. The problem is on this line:
if(layoutVariants != null) {
layoutVariants will never be null, so the else branch of this if statement will never execute. Because layoutVariants.size() will be zero, rand will always be zero. Trying to get the element at index 0 in an empty ArrayList will give you precisely the IndexOutOfBoundsException you are seeing.
I imagine you want the else block to execute if the layout name given isn't recognised, in other words, if the layoutVariants list is empty, rather than null. In that case, change this line to
if(!layoutVariants.isEmpty()) {
Note the ! (not-operator) before layoutVariants. You want the code under the if statement to run if the layoutVariants element is not empty.
EDIT in response to your comments: a null ArrayList is very much not the same as an empty one. null is a special value meaning that the variable doesn't have an object of a given type.
Let's try a real-world analogy: a shopping bag. If you have an empty bag, or no bag at all, then you have no shopping either way. However, you can put things into an empty bag, and count how many items it contains, for example. If you don't have a bag, then it doesn't make sense to put an item in it, as there's no bag to put the item into. null represents the case where you don't have a bag.
Similarly, a String is a collection of characters, and the collection of characters can exist even if it doesn't contain any characters.
isEmpty() can be used for any collection, and, if you're using Java 6 or later, Strings as well. Off the top of my head I can't name any other classes that have an isEmpty method. You'll just have to consult the documentation for these classes to find out.
I've not worked with Processing much, but I am aware that Processing is built on Java, so I would expect any standard Java method to work. Also, I wouldn't worry about 'clearing' a variable: the JVM is generally very good at clearing up after you. There's certainly nothing I can see wrong with your code in this respect.
EDIT 2 in response to your further comment: ArrayList arr; declares a variable of type ArrayList. However, the variable arr is uninitialized: it does not have a value (not even null) and it is an error to try to read the value of this variable before you have assigned a value to it:
ArrayList arr;
System.out.println(arr); // compiler error: arr might not have been initialised.
Assign null and the code then compiles:
ArrayList arr = null;
System.out.println(arr); // prints 'null'.
It's not often you need to declare a variable and not give it a name, but one common case is where you want to assign different values to the same variable on both sides of an if statement. The following code doesn't compile:
int y = getMeSomeInteger(); // assume this function exists
if (y == 4) {
int x = 2;
} else {
int x = 5;
}
System.out.println(x); // compiler error: cannot find symbol x
The reason it doesn't compile is that each variable x is only available within the braces { and } that contain it. At the bottom, neither variable x is available and so you get a compiler error.
We need to declare x further up. We could instead write the following;
int y = getMeSomeInteger(); // assume this function exists
int x = 0;
if (y == 4) {
x = 2;
} else {
x = 5;
}
System.out.println(x);
This code compiles and runs, but the value 0 initially assigned to x is never used. There isn't a lot of point in doing this, and we can get rid of this unused value by declaring the variable but not immediately giving it a value.
int y = getMeSomeInteger(); // assume this function exists
int x;
if (y == 4) {
x = 2;
} else {
x = 5;
}
System.out.println(x);