Okay, Hi guys. Currently I am taking an online course and for my final project i opted to do blackjack. Everything is running fine except for when a player needs to "hit" for another card. I have the code required for a hit within a method which uses args from a different method i created
public void Hitcardp1(int p1total, String p1scard1, String p1scard2){
int p1hitcard;
p1hitcard = (int)Math.ceil(Math.random()*10);
p1total = p1total + p1hitcard;
P1Area.setText("Card: " +p1scard1+ "\nCard: " +p1scard2+ "\nCard: +p1hitcard);
}
I need to put this in an event handler for when the hit button is clicked or interacted with. However it comes up with an error saying:
"Required int, string, string
I have tried putting the args within the event handler, however, it just creates a larger error.
I am relatively new to java and would really appreciate the help
There is not enough information about your handler and class.
Error comes because of missing args.
your method have to be run as:
Hitcardp1(p1total,p1scard1,p1scard2);
also, you have missed " in your code.
P1Area.setText("Card: " +p1scard1+ "\nCard: " +p1scard2+ "\nCard: "+p1hitcard);
Related
I am developing my bot for discord using Java and JDA API. Before that I asked a similar question, but I ran into another problem.
From this line the problems started :
final Member MentionedMem = event.getMessage().getMentionedMembers().get(0);
Thanks to https://stackoverflow.com/users/10630900/minn for answering the previous question in which he explained to me that this line is causing the error :
java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
For some reason or other it raises an error.
I was trying to find an answer to why this command does not work. The only thing I know is that this command returns an empty array args. Because of this, I cannot finish the bot, that is, I cannot check whether a member can kick others and can't make the main block of code kick members.
How can I fix this error and / or write the rest of the code?
Sorry for my English and many thanks to you.
Some code :
public class KickComm extends ListenerAdapter {
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
String[] message = event
.getMessage()
.getContentRaw()
.split(" ");
// final Member target = event.getMessage().getMentionedMembers().get(0); ERROR CUZ I DONT NOW WHY
final Member SelfMember = event
.getGuild()
.getSelfMember();
if(message[0].equalsIgnoreCase(Main.prefix + "kick"))
{
if (message.length < 2) {
EmbedBuilder NoUser = new EmbedBuilder();
NoUser.setColor(0xff3923);
NoUser.setTitle("\uD83D\uDD34You need to add a <#username> and <reason>");
NoUser.setFooter("Usage: " + Main.prefix + "kick <#username> <reason>.",
Objects
.requireNonNull(event.getMember())
.getUser()
.getAvatarUrl());
event
.getChannel()
.sendMessage(NoUser.build())
.queue();
NoUser.clear();
} else if (message.length < 3) {
EmbedBuilder NoReason = new EmbedBuilder();
NoReason.setColor(0xff3923);
NoReason.setTitle("\uD83D\uDD34You need to add a <reason>.");
NoReason.setFooter("Usage: " + Main.prefix + "kick <#username> <reason>.",
Objects
.requireNonNull(event.getMember())
.getUser()
.getAvatarUrl());
event
.getChannel()
.sendMessage(NoReason.build())
.queue();
NoReason.clear();
} else if(!SelfMember.hasPermission(Permission.KICK_MEMBERS)) {
EmbedBuilder NoPermission = new EmbedBuilder();
NoPermission.setColor(0xff3923);
NoPermission.setTitle("\uD83D\uDD34You don't have permission to use this command.");
NoPermission.setFooter("Usage: " + Main.prefix + "kick <#username> <reason>.",
Objects
.requireNonNull(event.getMember())
.getUser()
.getAvatarUrl());
event
.getChannel()
.sendMessage(NoPermission.build())
.queue();
NoPermission.clear();
} else if(!Objects.requireNonNull(event.getMember()).hasPermission(Permission.KICK_MEMBERS) || !event.getMember().canInteract(target)) { //Example, don't works
EmbedBuilder NoPermission = new EmbedBuilder();
NoPermission.setColor(0xff3923);
NoPermission.setTitle("\uD83D\uDD34You don't have permission to use this command.");
NoPermission.setFooter("Usage: " + Main.prefix + "kick <#username> <reason>.",
Objects
.requireNonNull(event.getMember())
.getUser()
.getAvatarUrl());
event
.getChannel()
.sendMessage(NoPermission.build())
.queue();
NoPermission.clear();
}
}
}
}
UPD: Please, if you downgrade, then point out the mistakes that I made, and not just downgrade it because you wanted to. I want to correct mistakes, not ruin your mood
It seems like you didn't quite get the problems in your code.
final Member target = event.getMessage().getMentionedMembers().get(0);
This will throw an IndexOutOfBoundsException if your message doesn't include a mentioned member. Because in this case the list of getMentionedMembers() is empty. There is no object to access. get(0) can't get anything.
In order to fix this you have to check first if the list is empty or if the length is zero as Minn already proposed. If it is you can display a message stating, that they need to add an #username.
Cleaning up your code and restructuring it accordingly would help a lot I suppose. Please go over it and make sure to always check, if the needed data exists in the first place and if you really need it. Some things are only needed for a small number of cases, calling them on every message / command is not good practice.
For example, at the moment your bot tries to get the first mentioned member from EVERY message that is sent. This isn't necessary hence you only need it in case it is the kick command.
By the way, the SelfMember is the bot itself. In your code you are telling the user that they don't have the permission although the bot (and not necessarily the user) might lack it which could be confusing.
I didn't see it earlier: Your bot is receiving its own messages as well. You might want to check, if the author of a message is your / a bot before continuing.
In the end I would advice you to always try to understand the answer or advice that is given to you. Asking another question for the same problem isn't going to help you nor does it cast a good light on you and your attempt to learn.
User mentionedUser = event.getMessage().getMentionedMembers().get(0).getUser();
If someone still needs it...
The issue, for some reason, was that you used Member instead of User.
Futhermore, you must use .getUser() to really get the user you want.
I'm working on a Java GUI and I'm trying to make a button that can start a FaceTime call with a given phone number. Here is an oversimplified version of the java code.
String cellNum = "18001234567";
try {
Runtime.getRuntime().exec("open /Users/faris/Desktop/call.app --args " + cellNum);
} catch (IOException e) {
e.printStackTrace();
}
After researching how do to this, I copied part of an AppleScript app I found online that I named call.app and modified it so it takes in an input argument phone number rather than manually entering it into the script. I've run the program with an actual phone number entered instead of the input variable and it works fine so I know that the problem lies with passing the argument.
call.app
on run args
set input to first item of args
open location "tel://" & input & "?audio=yes"
delay 1
tell application "System Events"
key code 36
end tell
end run
This is the error I get every time from the AppleScript.
Can’t get item 1. (-1728)
I've never used AppleScript before so I'm completely lost currently. Haven't found anything similar anywhere on SO. Any advice would be appreciated very much.
Cause:
Error -1728 in AppleScript is "Can't get «script»", indicating that the first item of args is a script object reference. This means that the command-line argument is not getting passed to your AppleScript's run handler.
Solution:
Instead of saving your AppleScript as an applet, save it (export it) as either a .scpt or an .applescript file. Then substitute your exec(...) Java command for this:
exec("osascript /path/to/applescript " + cellNum);
My intentions are to ask the user to write down some code in a TextArea, then see if that code compiles, and if it does, print out the results to another TextArea, which acts like a console.
Edit:Solving this via online compilers is the priority.
To accomplish this, I've tried using online compilers (i.e. compilerjava.net) and used the library HtmlUnit, but the library came in with a lot of errors, especially when reading the JavaScript code and returned me pages of 'warnings' that increase the compile & run time for about 20 seconds. I will leave the code below with explanations if anyone has intentions about trying to fix it.
I've also tried using the JavaCompiler interface, which did succeed in compiling, but under the conditions that I have provided the exact location of the .java file, which is something I have to create using the information I get from the TextArea. So again, a dead end.
I decided to come back to online compilers, since if I can manage to just return the data from the compiled program, I am set. The only issue is I haven't yet found an online compiler that allows a user to access its fields via Java code ( since its something too specific). I would appreciate any help on this if anyone can provide a way to send and retrieve data from an online compiler.
Here is the code using the HtmlUnit library, on the site 'compilerjava.net'. It is so close to working that the only 2 issues I have is that,
1) Run-time is too long.
2) I cannot access the console output of the code. Reasoning is that, when you hit 'compile', the output text-area's text turns into "executing". After a few seconds, it turns into the output of the code. When I try to access it, the data I retrieve is always "executing" and not the desired output. Here is the code;
public class Test {
public static void main(String[] args) {
try {
// Prevents the program to print thousands of warning codes.
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
// Initializes the web client and yet again stops some warning codes.
WebClient webClient = new WebClient( BrowserVersion.CHROME);
webClient.getOptions().setThrowExceptionOnFailingStatusCode( false);
webClient.getOptions().setThrowExceptionOnScriptError( false);
webClient.getOptions().setJavaScriptEnabled( true);
webClient.getOptions().setCssEnabled( true);
// Gets the html page, which is the online compiler I'm using.
HtmlPage page = webClient.getPage("https://www.compilejava.net/");
// Succesfully finds the form which has the required buttons etc.
List<HtmlForm> forms = page.getForms();
HtmlForm form = forms.get( 0);
// Finds the textarea which will hold the code.
HtmlTextArea textArea = form.getTextAreaByName( "code");
// Finds the textarea which will hold the result of the compilation.
HtmlTextArea resultArea = page.getHtmlElementById( "execsout");
// Finds the compile button.
HtmlButtonInput button = form.getInputByName( "compile");
System.out.println( button.getValueAttribute());
// Simple code to run.
textArea.setText( "public class HelloWorld\n" +
"{\n" +
" // arguments are passed using the text field below this editor\n" +
" public static void main(String[] args)\n" +
" {\n" +
" System.out.print( \"Hello\");\n" +
" }\n" +
"}");
// Compiles.
button.click();
// Result of the compilation.
System.out.println( resultArea.getText());
} catch ( Exception e) {
e.printStackTrace();
}
}
}
As I said, this final code System.out.println( resultArea.getText()); prints out "executing", which implies that I have succeeded in pressing the compile button on the webpage via code.
So after this long wall of text, I'm either looking for a way to fix the code I presented, which is so darn close to my answer but not quite, or just an entirely different solution to the problem I presented at the beginning.
P.S. Maven is the last hope.
so I'm new to using IntelliJ and I've tried googling but to no avail.
I'm creating a simple java program that basically prints hello and gets the user input (name) and prints it... Just to get the ball rolling. Normal Hello World prints fine..
But as soon as I add any [args] in it just crashes? Is there a way I can type the input in?
public class Main {
public static void main(String[] args) {
System.out.println("Hello, " + args[0] + "!");
}
}
You need to provide at least 1 argument if you access args[0] otherwise you get ArrayIndexOutOfBoundsException.
Why ? because the args[] is empty without any arguments passed so accessing the first one will throw the exception
How do you input commandline argument in IntelliJ IDEA?
There's an "edit configurations" item on the Run menu. In that panel, you can create a configuration and then you can choose the Class containing main().
add VM parameters and command-line args, specify the working directory and any environment variables.
you are done.
Sorry guys figured it out:
Go to Run
Edit Configurations > on the left side make sure you're in your Main class or whatever class you're using
Enter what you want in the program arguments. i.e. "James"
I have an interesting question today. Im trying to create a program that only starts if it is executed by a program, but will error if it is started by the user. Whats some code I can use to do this?
If by user you mean DIRECT user interaction:
You can control where a user may start the program from, e.g. button click. You may also control where another program may start the program from. So any direct issued command from a user should throw an exception; for example, when said button is clicked throw new Exception("I detect user");
Make the entry point something incompatible with
public void main ( String [ ] args ) throws Exception
like
int entryPoint ( String name )