Finch robot. Java - java

I am currently using loops with the finch robot to test some java codes and have come across an error. Here is my code.
import edu.cmu.ri.createlab.terk.robot.finch.Finch;
public class CS1702_Lab4 {
public static void main (String[] args) throws Exception
{
Finch myf = new Finch();
myf.setWheelVelocities(100,100);
long before = System.currentTimeMillis();{
while(System.currentTimeMillis() - before < 5000)
{
Thread.sleep(500);
if (myf.isTapped()) break;
}
myf.stopWheels();
myf.quit();
}
}
On line "myf.setWheelVelocities(100,100)", I am getting the following error;
Syntax error on tokens, delete these tokens
-Syntax error on token(s), misplaced construct(s).
Any help towards solving this error is appreciated. Many thanks.

you have too many brackets { }
remove them in these lines:
long before = System.currentTimeMillis();{
and here:
myf.quit();
}
Also it seems as if you have no class declaration.
public class CS1702_Lab4 {
public static void main (String[] args) throws Exception
{
Finch myf = new Finch();
myf.setWheelVelocities(100,100);
long before = System.currentTimeMillis();
while(System.currentTimeMillis() - before < 5000)
{
Thread.sleep(500);
if (myf.isTapped()) break;
}
myf.stopWheels();
myf.quit();
}
}

It might be too late now, but this piece of code
myf.setWheelVelocities(100,100);
should have 3 sets of numbers e.g.
myf.setWheelVelocities(100,100,5000);

Related

Java Robot doesnt Press Enter Key how it should

Im trying to program a litte Robot, that should just write for some hours the same phrase with a delay.
But somehow, if i have mor than 1 Letter at the same time before the Enter Key, it rather types a Pyramide.
For Example, if i wanna print "ted", it prints the following:
ted
tedted
tedtedted
tedtedtedted
[...]
(There is no empty line between the Pyramide-Lines)
It gets really frustrating.
I Tried many solutions, but none worked. Making a Delay for the robot, an extra Robot for the Enter Key, put it in an extra Thread or creating new Robots every time before a new Typing. It just doesnt work. What am i doing wrong?
Here is a SSCCE with some trys i did:
#SuppressWarnings("CallToPrintStackTrace")
public class RobotTest {
private static Robot robo;
private static Robot okRobo;
static {
createRobos();
}
private static void createRobos(){
try {
robo = new Robot();
okRobo = new Robot();
} catch (AWTException ex) {
ex.printStackTrace();
}
}
#SuppressWarnings({"CallToPrintStackTrace", "SleepWhileInLoop"})
public static void main(String[] args) throws InterruptedException {
Thread.sleep(5000);
for (int i = 0; i < 16; i++) {
createRobos();
perform();
// Thread.sleep(500);
performOk();
}
}
private static void perform() {
robo.keyPress(KeyEvent.VK_SHIFT);
robo.keyPress(KeyEvent.VK_1);
robo.keyRelease(KeyEvent.VK_SHIFT);
robo.keyRelease(KeyEvent.VK_1);
robo.keyPress(KeyEvent.VK_B);
robo.keyRelease(KeyEvent.VK_B);
robo.keyPress(KeyEvent.VK_O);
robo.keyRelease(KeyEvent.VK_O);
robo.keyPress(KeyEvent.VK_O);
robo.keyRelease(KeyEvent.VK_O);
robo.keyPress(KeyEvent.VK_S);
robo.keyRelease(KeyEvent.VK_S);
robo.keyPress(KeyEvent.VK_T);
robo.keyRelease(KeyEvent.VK_T);
robo.keyPress(KeyEvent.VK_E);
robo.keyRelease(KeyEvent.VK_E);
robo.keyPress(KeyEvent.VK_D);
robo.keyRelease(KeyEvent.VK_D);
// robo.waitForIdle();
}
private static void performOk() {
okRobo.keyPress(KeyEvent.VK_ENTER);
okRobo.keyRelease(KeyEvent.VK_ENTER);
// okRobo.waitForIdle();
}
}
And here is my first try, that should work in my opinion too, but it doesnt:
public class RobotTest {
private static Robot robo;
#SuppressWarnings("CallToPrintStackTrace")
static {
try {
robo = new Robot();
} catch (AWTException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
Thread.sleep(5000);
for (int i = 0; i < 16; i++) {
perform();
}
}
private static void perform() {
robo.keyPress(KeyEvent.VK_SHIFT);
robo.keyPress(KeyEvent.VK_1);
robo.keyRelease(KeyEvent.VK_SHIFT);
robo.keyRelease(KeyEvent.VK_1);
robo.keyPress(KeyEvent.VK_B);
robo.keyRelease(KeyEvent.VK_B);
robo.keyPress(KeyEvent.VK_O);
robo.keyRelease(KeyEvent.VK_O);
robo.keyPress(KeyEvent.VK_O);
robo.keyRelease(KeyEvent.VK_O);
robo.keyPress(KeyEvent.VK_S);
robo.keyRelease(KeyEvent.VK_S);
robo.keyPress(KeyEvent.VK_T);
robo.keyRelease(KeyEvent.VK_T);
robo.keyPress(KeyEvent.VK_E);
robo.keyRelease(KeyEvent.VK_E);
robo.keyPress(KeyEvent.VK_D);
robo.keyRelease(KeyEvent.VK_D);
robo.keyPress(KeyEvent.VK_ENTER);
robo.keyRelease(KeyEvent.VK_ENTER);
robo.delay(500);
}
Try not to initialize your Robot at each iteration of the loop. Call createRobos() outside of the loop. That is unless you have a specific reason that you're doing it that way.
I don't think you need two separate instances of Robot to get this to work.
Instead of using Thread.sleep(), you can use the delay() method within the Robot class. This is if you want to add a delay between Robot method calls.
You may want to try to add a delay between when you're typing out the letter keys and when you're pressing the enter key and after you press the enter key. A 50 - 100 ms delay will usually do the trick. Sometimes, things get a little messed up, especially when you throw Thread.sleep() into the mix.
I ran your code with these small changes and it seemed to work fine.

Awaiting for message using discordJDA not working as intended

I'm currently working on my discord bot. One problem I encountered is that I'm not able to find out how to allow the bot to wait for a user reply after a message is sent.
I also have tried reading the git documentation regarding using RestAction over here: https://github.com/DV8FromTheWorld/JDA/wiki/7)-Using-RestAction but it seems it does not mention anything about implementing an "await" function similar to discord.js
I tried coding to mimic such an effect:
public class EventHandler extends ListenerAdapter {
private static final String PREFIX = "&";
public static String[] args;
public void sendMessage(String s, GuildMessageReceivedEvent event) {
event
.getChannel()
.sendMessage(s)
.queue();
}
public void onGuildMessageReceived (GuildMessageReceivedEvent event) {
args = event
.getMessage()
.getContentRaw()
.split(" ");
if (args[0].equalsIgnoreCase(PREFIX + "any_command")) {
sendMessage("Type hello!");
if (args[0].equalsIgnoreCase(PREFIX + "hello") {
sendMessage("hello there!");
}
}
}
}
Main class:
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
public class Main {
public static void main(String[] args) throws Exception {
JDA jda = new JDABuilder(AccountType.BOT)
.setToken("token goes here")
.setAutoReconnect(true).build();
try {
jda.addEventListener(new EventHandler());
} catch (Exception e) {
e.printStackTrace();
}
}
}
This doesn't register the hello command typed after the prompt given. My best guess would be that the condition is never met since the original condition overrides the upcoming one (args[0] is already any_command)
Any help would be appreciated!
I'd suggest the EventWaiter from JDA-Utilities (https://github.com/JDA-Applications/JDA-Utilities/)
Taking a quick look at the source, looks like you'll need something like this
EventWaiter waiter = new EventWaiter();
// SO wouldn't let me insert new lines for some reason.
waiter.waitForEvent(GuildMessageReceivedEvent.class, (event) -> event.getMessage().getContentRaw().equalsIgnoreCase("hello"), (event) -> event.getChannel().sendMessage("hello!").queue()));

Scanner reading File - nextLine()

I have a problem with the assignment. Basically the method printLinesWhichContain(String word) should print the lines that contain the given word, which works fine, and if the String is empty (""), print all lines in the file. The last part doesn't work. Any advice?
import java.io.File;
import java.util.Scanner;
public class Printer {
private File lol;
private Scanner reader;
public Printer(String fileName)throws Exception{
this.lol = new File(fileName);
this.reader = new Scanner(lol);
}
public void printLinesWhichContain(String word) {
if (word.isEmpty()) {
while (this.reader.hasNextLine()) {
String x = this.reader.nextLine();
System.out.println(x);
}
} else {
while (this.reader.hasNextLine()) {
String x = this.reader.nextLine();
if (x.contains(word)) {
System.out.println(x);
}
}
}
}
}
Main
public class Main {
public static void main(String[] args) throws Exception {
Printer printer = new Printer("src/textfile.txt");
printer.printLinesWhichContain("Väinämöinen");
System.out.println("-----");
printer.printLinesWhichContain("Frank Zappa");
System.out.println("-----");
printer.printLinesWhichContain("");
System.out.println("-----");
}
}
File text
Siinä vanha Väinämöinen
katseleikse käänteleikse
Niin tuli kevätkäkönen
näki koivun kasvavaksi
Miksipä on tuo jätetty
koivahainen kaatamatta
Sanoi vanha Väinämöinen
Output
Siinä vanha Väinämöinen
Sanoi vanha Väinämöinen
-----
-----
-----
In your application you created only one Scanner which can iterate over entire file only once. If you want to iterate over entire file each time you invoke printLinesWhichContain method, you need to reset your scanner, most likely by creating new one.
So one of options would be reinitializing already used scanner at the end of
public void printLinesWhichContain(String word) {
//...your original code
this.reader = new Scanner(lol);
}
method. But if you don't use scanner elsewhere outside of this method maybe it may be worth making it local variable instead of class field.
public void printLinesWhichContain(String word) {
Scanner reader = new Scanner(lol);
//...your original code
}
Other option could be reading file once and storing its content, using code like
List<String> allLines = Files.readAllLines(lol.toPath());
You can iterate over this list instead of file.
If you change the main to this:
public static void main(String[] args) throws Exception {
Printer printer = new Printer("src/textfile.txt");
printer.printLinesWhichContain("Väinämöinen");
System.out.println("-----");
printer.printLinesWhichContain("Frank Zappa");
System.out.println("-----");
printer = new Printer("src/textfile.txt");
printer.printLinesWhichContain("");
System.out.println("-----");
}
It will work. Reason being that, due to the way you've written your code, printer needs to be reinitialized so that it can start reading from the beginning again.

Getting "Exception in thread "main" java.lang.NoSuchMethodError: main"? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Exception in thread “main” java.lang.NoSuchMethodError: main
I am fairly new to Java, and I am unable to figure out why I am getting NoSuchMethodError: main when I execute the following code. I am not sure what does the NoSuchMethodError is pertaining to. It looks like I have everything right. Please help me out here. Thanks a lot.
public class ThreadExample1 extends Thread
{
static String[] msg = {"Java", "programming", "is", "the", "best"};
public ThreadExample1(String id)
{
super(id);
}
#Override
public void run()
{
try
{
Output.displayList(getName(), msg);
}
catch (InterruptedException ex)
{
}
}
}
class Output
{
public static void displayList(String name, String list[]) throws InterruptedException
{
for (int i = 0; i < list.length; i++)
{
Thread.currentThread().sleep((long) (3000 * Math.random()));
System.out.println(name + list[i]);
}
}
public static void main(String[] args)
{
ThreadExample1 thread1 = new ThreadExample1("thread1: ");
ThreadExample1 thread2 = new ThreadExample1("thread2: ");
thread1.start();
thread2.start();
boolean t1IsAlive = true;
boolean t2IsAlive = true;
do
{
if (t1IsAlive && !thread1.isAlive())
{
t1IsAlive = false;
System.out.println("t1 is dead.");
}
if (t2IsAlive && !thread2.isAlive())
{
t2IsAlive = false;
System.out.println("t2 is dead.");
}
}while (t1IsAlive || t2IsAlive);
}
}
I don't have any problem compiling and executing the above code ... Keep in mind that when you want to execute it , you need to use this command line :
java Output
and NOT :
java ThreadExample1
because the main method is within the Output calss and not in ThreadExample1 ...
Save the file as ThreadExample1.java and compile. After that you should run Output class but not the ThreadExample1 class. This is because you have added your main method inside Output class. But since you have made your ThreadExample1.java class public you have to save and compile using that name(javac ThreadExample1.java). After that java Output
Take a look at code-snippet the main() method is in Output class.
Use following command line to launch the Output.main() method:
c:\>java Output
When you do compile a java program you do need to give the file name after javac.
like javac MyProgram.java
and when you do run it using java then you need to mention the name of the class that is having "public static void main(String args[])" method.
Say I have two classes in MyProgram.java : Class First and Class Second
and I have "public static void main(String args[])" in Class Second then I will do the following :
javac MyProgram.java
java Second

Get the method name and it's contained parameters by parsing the exception

When I received an exception such as IOException or RunTimeException, I can only know the line number in the class.
First of my question. Is it possible to retrieve the method name through exception?
Second, is it possible to retrieve the method and the parameter of this method by line number?
p.s. I need to know the exact method name and its parameters, because I want to distinguish the overloading methods. To distinguish overloading methods, all that I know is to determine its parameters.
try{
//your code here}
catch(Exception e){
for (StackTraceElement st : e.getStackTrace())
{
System.out.println("Class: " + st.getClassName() + " Method : "
+ st.getMethodName() + " line : " + st.getLineNumber());
}
}
as you can see in the code above, you can get the stackTrace and loop over it to get all the method names and line numbers, refer to this for more info http://download.oracle.com/javase/1.4.2/docs/api/java/lang/StackTraceElement.html
If you look at the stacktrace you can know in which line the error occurred.
When using an overriden method you get the exact class name, source file and line number, you just have to know how to read it.
From that page:
java.lang.NullPointerException
at MyClass.mash(MyClass.java:9) //<--- HERE!!!!
at MyClass.crunch(MyClass.java:6)
at MyClass.main(MyClass.java:3)
This says, the problem occurred in line 9 of file MyClass.java in the method mash, which was in turn invoked by the method crunch at line 6 of the same file which was invoked by main in line 3 of the same file.
Heres the source code:
class MyClass {
public static void main(String[] args) {
crunch(null); // line 3
}
static void crunch(int[] a) {
mash(a); // line 6
}
static void mash(int[] b) {
System.out.println(b[0]);//line 9, method mash.
}
}
Basically you just have to ... well read it!
Stacktraces are a bit hard to grasp the first time, but later they become a very powerful tool.
I hope this helps.
pass it the exception and it will print the parameter types of the methods along with the exception
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
new Main().run();
}
public void run(){
try
{
new Car().run(60, "Casino");
}
catch (Exception e)
{
detailedException(e);
}
try
{
new Engine().run(10);
}
catch (Exception e)
{
detailedException(e);
}
}
public void detailedException(Exception e)
{
try
{
StringBuilder buffer = new StringBuilder(e.getClass().getName()).append(" \"").append(e.getMessage()).append("\"\n");
for (var trace: e.getStackTrace())
{
buffer.append("\tat ").append(trace.getClassName()).append(".").append(trace.getMethodName()).append("(").append(trace.getFileName()).append(":").append(trace.getLineNumber()).append(")[");
Class<?> clazz = Class.forName(trace.getClassName());
ArrayList<Method> methods = new ArrayList<>(Arrays.asList(clazz.getMethods()));
methods.removeIf(m -> !m.getName().equals(trace.getMethodName()));
Method method = methods.get(0);
for (var param: method.getParameters())
{
buffer.append(param.getName()).append(":").append(param.getParameterizedType().getTypeName()).append(", ");
}
buffer.append("]->").append(method.getGenericReturnType().getTypeName()).append("\n");
}
System.err.println(buffer);
}
catch (Exception parseFailed){
e.printStackTrace();
}
}
}
class Car extends Engine
{
public void run(int when, String where) throws Exception
{
super.run(25);
}
}
class Engine
{
public String run(int For) throws Exception
{
throw new Exception("need more fuel");
}
}

Categories

Resources