Help with Integers and having 0 Arguments!!!

Discussion in 'Plugin Development' started by Proffesor_Diggi, Jul 22, 2015.

Thread Status:
Not open for further replies.
  1. Offline

    Proffesor_Diggi

    Hey there everyone, I am having trouble with integers and arguements.

    For a start, the 0 arguments function does not even work and it just comes up with an internal error and I just don't know why, please tell me if you need my core class to figure this one out. With the integers, I would like to know how to check if arg 1 is a number.

    Here is my code:
    Code:
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String s, String[] args) {
        Player p = (Player) sender;
        int number = Integer.parseInt(args[0]);
        String playername = p.getDisplayName();
       
           
       
        if(cmd.getName().equalsIgnoreCase("test")){
           
            if(args.length == 0){
                p.sendMessage("Test success");
            }
               
            if(args.length == 1){
               
                if(!p.hasPermission("test.test")){
                    p.sendMessage(ChatColor.RED + "You do not have permission! If this is an error, please contact an administrator!");
                    return true;
                   
    
                }
                    p.sendMessage("Number is " + number);
            }
     
  2. Offline

    AcePilot10

    return true or false after p.sendMessage("Test success");.

    To check if an argument is an int just make a method like so:
    Code:
    public static boolean isInt(String s) {
        try {
            Integer.parseInt(s);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }
    Also, don't initialize your number variable until you have checked if the arguments is the proper length.
    Then pass this through wherever you need. Hope this helped :)
     
  3. @Proffesor_Diggi
    You're getting an ArrayIndexOutOfBoundsException because you are trying to get an element from the array before checking the array length.
    Code:
    int number = Integer.parseInt(args[0]);
     
  4. Offline

    Proffesor_Diggi

    Ah, Thanks!

    hmm, adding the return true; or return false; did not work :/ I still get the internal error

    <Edited by bwfcwalshy: Merged posts, please use the edit button rather than double posting.>
     
    Last edited by a moderator: Jul 22, 2015
  5. Offline

    Proffesor_Diggi

  6. Offline

    Lolmewn

    Two things wrong:
    You cast to Player without checking if sender is a player. ALWAYS do if(sender instanceof Player) before casting.
    You immediately parse args[0] to an int without checking: 1. If it's an int (e.g. catching the NumberFormatException) and 2. if args[0] even exists. ALWAYS do args.length check before using args.
     
Thread Status:
Not open for further replies.

Share This Page