• Advertisement
Sign in to follow this  

The Joys Of Nesting

This topic is 1657 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This is part of a project I was working on some time ago, and boy it was fun to work with. Every time I had to go back and make changes, it took 10 - 20 minutes just to determine which nest I was in. Many times I accidentally broke the code by deleting / moving the wrong brace.

public class Main extends JavaPlugin{
	// Banned Items
	ArrayList<String> Banned = new ArrayList<String>();
	// Import Money
	boolean Imoney;
	// Export Money
	boolean Emoney;
	// Maximum Money Per Day
	int Mmoney; // Not Used In Plugin - Server Side Use Only
	// Money Name
	String Money_Name;
	// Import Items
	boolean Iitems;
	// Export Items
	boolean Eitems;
	// Maximum Items Per Day
	int Mitems; // Not Used In Plugin - Server Side Use Only
	// Banned Player Deletion
	boolean Bplayer; 
	public void onEnable(){
    	File file = new File("MC_Web");
    	if (!file.exists()){ // First Time Config
    		System.out.println("\n** MC_Web First Time Set Up **");
    		file.mkdir();
    		File file1 = new File ("MC_Web/Users");
    		file1.mkdir();
    		File cfg = new File ("MC_Web/MC_Web.config");
    		File ban = new File ("MC_Web/Banned_Items.ban");
    		try { 
				cfg.createNewFile();
				ban.createNewFile();
				FileWriter fileWritter = new FileWriter("MC_Web/MC_Web.config",true);
    	        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
    	        bufferWritter.write("Allow_Money_Export=true\n");
    	        bufferWritter.write("Allow_Money_Import=true\n");
    	        bufferWritter.write("Max_Money_Per_Day=-1\n");
    	        bufferWritter.write("Money_Name=Gold\n");
    	        bufferWritter.write("Allow_Material_Export=true\n");
    	        bufferWritter.write("Allow_Material_Import=true\n");
    	        bufferWritter.write("Max_Material_Per_Day=-1\n");
    	        bufferWritter.write("Auto_Delete_Banned_Player_Account=false\n");
    	        bufferWritter.close();
    	        FileWriter fW = new FileWriter("MC_Web/Banned_Items.ban",true);
    	        BufferedWriter bW = new BufferedWriter(fW);
    	        bW.write("Bukkit_Materials_Only\nDIAMOND_AXE\nDIAMOND_BOOTS\nDIAMOND_CHESTPLATE\nDIAMOND_HELMET\nDIAMOND_LEGGINGS\nDIAMOND_PICKAXE\nDIAMOND_SWORD\nGOLD_AXE\nGOLD_BOOTS\nGOLD_CHESTPLATE\nGOLD_HELMET\nGOLD_HOE\nGOLD_LEGGINGS\nGOLD_PICKAXE\nGOLD_SWORD\nIRON_AXE\nIRON_BOOTS\nIRON_CHESTPLATE\nIRON_HELMET\nIRON_LEGGINGS\nIRON_PICKAXE\nIRON_SWORD\nLEATHER_BOOTS\nLEATHER_CHESTPLATE\nLEATHER_HELMET\nLEATHER_LEGGINGS\nMOB_SPAWNER\nMONSTER_EGG\nMONSTER_EGGS\nSTONE_AXE\nSTONE_PICKAXE\nSTONE_SWORD\nWOOD_SWORD\nWOOD_PICKAXE\nWOOD_AXE\n");
    	        bW.close();
    	        
			} 
    		catch (IOException e) {
    			System.out.println("\n** MC_Web Error Creating Config File **");
    		}}
    		System.out.println("\n** MC_Web Loading Config **");
    		File cfg = new File ("MC_Web/MC_Web.config");
    		if (!cfg.exists()){ // If Config Missing .... 
    			System.out.println("\n** MC_Web Error Finding Config File - Creatinng New Config File **");
        		try {
    				cfg.createNewFile();
    				FileWriter fileWritter = new FileWriter("MC_Web/MC_Web.config",true);
        	        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
        	        bufferWritter.write("Allow_Money_Export=true\n");
        	        bufferWritter.write("Allow_Money_Import=true\n");
        	        bufferWritter.write("Max_Money_Per_Day=-1\n");
        	        bufferWritter.write("Money_Name=Gold\n");
        	        bufferWritter.write("Allow_Material_Export=true\n");
        	        bufferWritter.write("Allow_Material_Import=true\n");
        	        bufferWritter.write("Max_Material_Per_Day=-1\n");
        	        bufferWritter.write("Auto_Delete_Banned_Player_Account=false\n");
        	        bufferWritter.close();
    		}
        		catch (IOException e) {
        			System.out.println("\n** MC_Web Error Creating New Config File **");
        		}}
        		
        		try{
        			  FileInputStream fstream = new FileInputStream("MC_Web/MC_Web.config");
        			  DataInputStream is = new DataInputStream(fstream);
        			  BufferedReader br = new BufferedReader(new InputStreamReader(is));
        			  String Line;
        			  int x = 0; 
        			  // If you add config lines, change X and case
        			  while (x != 8)    {
        				  Line = br.readLine().trim();
        				  String[] Temp = Line.split("=");
        			      switch(x){
        			      case 0:Imoney = Boolean.parseBoolean(Temp[1]);break; 
        			      case 1:Emoney = Boolean.parseBoolean(Temp[1]);break; 
        			      case 2:Mmoney = Integer.parseInt(Temp[1]);break; 
        			      case 3:Money_Name = Temp[1];break; 
        			      case 4:Iitems = Boolean.parseBoolean(Temp[1]);break; 
        			      case 5:Eitems = Boolean.parseBoolean(Temp[1]);break; 
        			      case 6:Mitems = Integer.parseInt(Temp[1]);break; 
        			      case 7:Bplayer = Boolean.parseBoolean(Temp[1]);break; 
        			      default:System.out.println("\n** MC_Web Error - Extra Config Lines **\n ** Line " + (x+1) + ": " + Line + " **");
        			      }
        			      x += 1;
        			      }
        			  is.close();
        			  br.close();
        			    }
        		catch (Exception e){
        			  System.out.println(e);
        			  System.out.println("\n ** MC_Web Error Setting Configurations From File  **");
        			  }
        		try{
     				  FileInputStream fstream = new FileInputStream("MC_Web/Banned_Items.ban");
        			  DataInputStream is = new DataInputStream(fstream);
        			  BufferedReader br = new BufferedReader(new InputStreamReader(is));
        			  String Line;
        			  while ( ( Line = br.readLine() ) != null )    {
        				  Banned.add(Line.trim() );
        			  }} 
        		catch (Exception e){
      			  System.out.println(e);
      			  System.out.println("\n ** MC_Web Error Loading Banned Item List  **");
        		}
        		if (Bplayer){
        		Delban(); // deleate banned players
        		System.out.println("\n ** MC_Web - Deleating banned player accounts **");
        			  }}
    public void onDisable(){}
// #####################
// #### Book Mark ######
//######################
    public void error(Player x){ // If Player Does Something Wrong
    	x.sendMessage(ChatColor.GOLD + "** MC_Web Help **");
    	x.sendMessage(ChatColor.GOLD + "@ Account Create <Password_Here> <NickName_Here>");
    	x.sendMessage(ChatColor.GOLD + "This will create an account for you");
    	x.sendMessage(ChatColor.GOLD + "@ Account Reset <Password_Here>");
    	x.sendMessage(ChatColor.GOLD + "This will reset your password");
    	x.sendMessage(ChatColor.GOLD + "@ Item Deposit");
    	x.sendMessage(ChatColor.GOLD + "This will deposit all the same type of items as in your hand,\n from your inventory to your 'in box' ");
    	x.sendMessage(ChatColor.GOLD + "@ Item Withdraw"); 
    	x.sendMessage(ChatColor.GOLD + "This will deposit all items from your 'out box', to your inventory");
    	x.sendMessage(ChatColor.GOLD + "@ Money Deposit <Ammount_Here>");
    	x.sendMessage(ChatColor.GOLD + "This will deposit money into your account ");
    	x.sendMessage(ChatColor.GOLD + "@ Money Withdraw <Ammount_Here>"); 
    	x.sendMessage(ChatColor.GOLD + "This will withdraw money from your account");
    }
    public void Delban (){ // Delete banned users
    	ArrayList<String> BP = new ArrayList<String>();
    	try{
    		  FileInputStream fstream = new FileInputStream("banned-players.txt");
			  DataInputStream is = new DataInputStream(fstream);
			  BufferedReader br = new BufferedReader(new InputStreamReader(is));
			  String Line;
			  int Z = 0;
			  while ( Z < 3){
				  br.readLine(); 
				  Z += 1;
			  }
			  while ( ( Line = br.readLine() ) != null )    { 
				  String[] Temp = Line.split("\\|");
				  BP.add(Temp[0].trim() );
			}
			    is.close();
			    br.close();  
    	}
    	catch (IOException e){
    		System.out.println(e);
    		System.out.println("\n ** MC_Web Error - Problem removing banned players.");
    	}

    	  File folder = new File("MC_Web/Users");
    	  File[] listOfFiles = folder.listFiles(); 
    	  for (int i = 0; i < listOfFiles.length; i++) {
    	 
    	     if (listOfFiles[i].isDirectory()) 
    	   {
    	    	 for (String item : BP) {
    	           if (listOfFiles[i].getName().equalsIgnoreCase(item) ) {
    	    	       File files2 = new File("MC_Web/Users/" + listOfFiles[i].getName());
    	    	       File[] lof2 = files2.listFiles();
    	    	       for (int x = 0; x < lof2.length; x++){
    	    	    	   lof2[x].delete();
    	    	       }
    	    	       listOfFiles[i].delete();
    	    	       }}}}}
  public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    	
   	 if (sender instanceof Player) {
        if (cmd.getName().equalsIgnoreCase("mc_web")){
       		Player pl = (Player) sender;
       		String Name = pl.getName();
       		Account account = new Accounts().get(Name);
			Double Money = account.getHoldings().getBalance();
			DecimalFormat Trun = new DecimalFormat("0.00");
			File Test = new File("MC_Web/Users/" + Name);
   			if (args.length < 2  ){
   				error(pl);
   			}
// Account Creation
   			else if ( args[0].equalsIgnoreCase("account") && args[1].equalsIgnoreCase("create") ){
   				if ( args.length < 3 || args.length < 4){
   					error(pl);
   				}
   				else{
   			    File file = new File("MC_Web/Users/" + Name);
   			    if (file.exists() ){
   			    	pl.sendMessage(ChatColor.AQUA + "Error - Account '" + Name + "' allready exists");
   			    }
   			    else{
   			    	file.mkdir();
   			    	String Temp = "MC_Web/Users/" + Name;
   			    	File file1 = new File(Temp + "/Blarg.acc");
   			    	File file2 = new File(Temp + "/Account.acc");
   			    	File file3 = new File(Temp + "/In.box");
   			    	File file4 = new File(Temp + "/Out.box");
   			    	try{
   			    		file1.createNewFile();
   			    		file2.createNewFile();
   			    		FileWriter fileWritter1 = new FileWriter("MC_Web/Users/" + Name +"/Account.acc",false);
   		        	    BufferedWriter bufferWritter1 = new BufferedWriter(fileWritter1);
   		        	    bufferWritter1.write("0.0");
   		        	    bufferWritter1.close();
   			    		file3.createNewFile();
   			    		file4.createNewFile();
   			    		FileWriter fileWritter = new FileWriter(Temp + "/Blarg.acc",true);
   	        	        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
   	        	        bufferWritter.write(args[3] + "\n");
   	        	        bufferWritter.write(args[2] + "\n");
   	        	        Random rand = new Random();
   	        	        bufferWritter.write("" + rand.nextInt(999999999) + "\n"); // User Number
   	        	        bufferWritter.close();
   	        	        pl.sendMessage(ChatColor.GOLD + "Account Created");
   	        	        pl.sendMessage(ChatColor.GOLD + "Username: " + Name);
   	        	        pl.sendMessage(ChatColor.GOLD + "Password: " + args[2]);
   	        	        pl.sendMessage(ChatColor.GOLD + "Nickname: " + args[3]);
   	        	        System.out.println("\n ** MC_Web User Account Created '" + Name + " '");
   			    	}
   			    	catch (IOException e) {
   			    		pl.sendMessage(ChatColor.AQUA + "Error - Account Failed To Create");
   			    		System.out.println("\n ** MC_Web Error - Account '" + Name + "' Failed To Create");
   			    	}}}}
// Password Reset
   			else if(args[0].equalsIgnoreCase("account") && args[1].equalsIgnoreCase("reset") && Test.exists()){
   				if ( args.length < 3 ){
   					error(pl);
   				}
   				else{
   					boolean pf = true;
   					String pnn = "not_me";
   					String pwr = args[2];
	        	    Random rand = new Random();
   					String pwn = "" + rand.nextInt(999999999);
   					try{
   					  FileInputStream fstream = new FileInputStream("MC_Web/Users/" + Name +"/Blarg.acc");
          			  DataInputStream is = new DataInputStream(fstream);
          			  BufferedReader br = new BufferedReader(new InputStreamReader(is));
          			  pnn = br.readLine();
          			  is.close();
          			  br.close();
   					}
   					catch (IOException e){
   						pl.sendMessage(ChatColor.AQUA + "Error - Account Failed To Reset");
   						System.out.println(e);
   			    		System.out.println("\n ** MC_Web Error - Account '" + Name + "' Failed To Reset - Failure Type 1");
   			    		pf = false;
   					}
   					try{
   						if (pf){
   							FileWriter fileWritter = new FileWriter("MC_Web/Users/" + Name +"/Blarg.acc",false);
   	   	        	        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
   	   	        	        bufferWritter.write(pnn +"\n");
   	   	        	        bufferWritter.write(pwr +"\n");
   	   	        	        bufferWritter.write(pwn +"\n"); // User Number
   	   	        	        bufferWritter.close();
   	   	        	        pl.sendMessage(ChatColor.GOLD + "Account Updated");
   	   	        	        System.out.println("\n ** MC_Web User Account Updated '" + Name + " '");
   						}
   					}
   					catch (IOException e){
   						pl.sendMessage(ChatColor.AQUA + "Error - Account Failed To Reset");
   						System.out.println(e);
   			    		System.out.println("\n ** MC_Web Error - Account '" + Name + "' Failed To Reset - Failure Type 2");
   					}}}
 // Item Deposit
   			else if(args[0].equalsIgnoreCase("item") && args[1].equalsIgnoreCase("deposit") && Test.exists() ){
   				if (Eitems == true){
   				ItemStack It[] = pl.getInventory().getContents();
   				ItemStack Ih  = pl.getItemInHand();
   				String Mih = "" + Ih.getType(); // Deposit Type
   				int Amm = 0; // Deposit Amount
   				short dur; // Not implemented
   				boolean temp = true;
               	for (String item : Banned) {
               	    if (item.contains("" + Ih.getType()) ) {
               	        temp = false;
               	    }}
   				if (Ih.getType() != Material.AIR && temp){
   					for (int i = 0; i < It.length; i++){
   	                    if ( It[i] != null  ){
   	                    	if ( Ih.getType() == It[i].getType() ){
   	                    	dur = Ih.getDurability(); // Not implemented
   	                    	Amm += It[i].getAmount();
   	                    	pl.getInventory().setItem( i , new ItemStack(Material.AIR, 0) );
   	                    	 }}}
   					try{
   						FileWriter fileWritter = new FileWriter("MC_Web/Users/" + Name +"/In.box",true);
   	        	        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
   	        	        bufferWritter.write(Mih + "|" + Amm + "\n");
   	        	        bufferWritter.close();
   	        	        pl.sendMessage(ChatColor.GOLD + "Items Deposited");
   					}
   					catch (IOException e){
   						pl.sendMessage(ChatColor.AQUA + "Error - Deposit Failed");
   						System.out.println(e);
   			    		System.out.println("\n ** MC_Web Error - Account '" + Name + "' Failed To Deposit Items");
   					}}
   				else{
   					pl.sendMessage(ChatColor.AQUA + "Error - You are not allowed to deposit that.");
   				}}
   				else{
   					pl.sendMessage(ChatColor.AQUA + "Error - You are not allowed to deposit items");
   				}}
// Item Withdraw
   			else if (args[0].equalsIgnoreCase("item") && args[1].equalsIgnoreCase("withdraw") && Test.exists() ){
   				if (Iitems == true){
   					int X = 0;
   				try{
   				  FileInputStream fstream = new FileInputStream("MC_Web/Users/" + Name + "/Out.box");
      			  DataInputStream is = new DataInputStream(fstream);
      			  BufferedReader br = new BufferedReader(new InputStreamReader(is));
      			  String Line;
      			  while ( ( Line = br.readLine() ) != null )    { 
      				String[] Temp = Line.split("\\|");
      				ItemStack item = new ItemStack(Material.getMaterial(Temp[0].trim()),Integer.parseInt(Temp[1].trim()));
      				pl.getLocation().getWorld().dropItemNaturally(pl.getLocation(), item);
      				X += 1;
      			  }
      			    is.close();
      			    br.close();
					FileWriter fileWritter = new FileWriter("MC_Web/Users/" + Name +"/Out.box",false);
	        	    BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
	        	    bufferWritter.write("");
	        	    bufferWritter.close();
	        	    if ( X > 0){
	        	    pl.sendMessage(ChatColor.GOLD + "Items Withdrawn");
	        	    }
	        	    else{
	        	    	pl.sendMessage(ChatColor.AQUA + "Error - Nothing To Withdraw");
	        	    }}
   				catch (IOException e){
						pl.sendMessage(ChatColor.AQUA + "Error - Item Withdraw");
						System.out.println(e);
			    		System.out.println("\n ** MC_Web Error - Account '" + Name + "' Failed To Withdraw Items");
					}}
   				else{
   					pl.sendMessage(ChatColor.AQUA + "Error - You are not allowed to withdraw items");
   				}}
// Money Deposit
   			else if ( args[0].equalsIgnoreCase("money") && args[1].equalsIgnoreCase("deposit") && Test.exists() ){
   				if (args.length < 3  ){
   	   				error(pl);
   	   			}
   				else{
   					if(Emoney == true){
   						double Mon = 0.;
   						double Bal = 0.;
   						boolean pf = true;
   						try{
   						  Mon = Double.valueOf(args[2]).doubleValue();
   						  FileInputStream fstream = new FileInputStream("MC_Web/Users/" + Name +"/Account.acc");
   	          			  DataInputStream is = new DataInputStream(fstream);
   	          			  BufferedReader br = new BufferedReader(new InputStreamReader(is));
   	          			  Bal = Double.valueOf(br.readLine()).doubleValue();
   	          			  is.close();
   	          			  br.close();
   	          			  }
   						catch (Exception e){
   							pf = false;
   							pl.sendMessage(ChatColor.AQUA + "Error - Invalad Number Conversion");
   						}
   						if ( pf ){
   						int Enough_Money = Double.compare(Mon,Money);

   						if (Enough_Money < 0 ) {
   							try{
   								Bal += Mon;
   								FileWriter fileWritter = new FileWriter("MC_Web/Users/" + Name +"/Account.acc",false);
   	   	   	        	        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
   	   	   	        	        bufferWritter.write(Bal +"\n");
                                bufferWritter.close();
                                account.getHoldings().subtract(Mon);
         	          			pl.sendMessage(ChatColor.GOLD + ""+ Mon + " " + Money_Name + " has been deposited");
           	          			pl.sendMessage(ChatColor.GOLD + "Account balance is now " + Trun.format(Bal) + " " + Money_Name);
   							}
   							catch (IOException e){
   	   							pl.sendMessage(ChatColor.AQUA + "Error - Making Deposit");
   	   							System.out.println("\n ** MC_Web Error - '" + Name + "' deposit failed");
   	   						}}
   						else{
   							pl.sendMessage(ChatColor.AQUA + "Too Much To Deposit: " + Trun.format(Mon) + " " + Money_Name);
   							}}
   						}
   					else{
   						pl.sendMessage(ChatColor.AQUA + "Error - You are not allowed to deposit money");
   					}}}
// Money Withdraw	
   			else if ( args[0].equalsIgnoreCase("money") && args[1].equalsIgnoreCase("withdraw") && Test.exists() ){
   				if (args.length < 3  ){
   	   				error(pl);
   	   			}
   				else{
   					if(Imoney == true){
   						double Mon = 0.;
   						double Bal = 0.;
   						boolean pf = true;
   						try{
   							Mon = Double.valueOf(args[2]).doubleValue();
   							FileInputStream fstream = new FileInputStream("MC_Web/Users/" + Name +"/Account.acc");
     	          			DataInputStream is = new DataInputStream(fstream);
     	          			BufferedReader br = new BufferedReader(new InputStreamReader(is));
     	          			Bal = Double.valueOf(br.readLine().trim() ).doubleValue();
     	          			is.close();
     	          			br.close();
   							
   						}
   						catch (Exception e){
   							pf = false;
   							pl.sendMessage(ChatColor.AQUA + "Error - Invalad Number Conversion");
   						}
   						if ( pf ){
   							int Enough_Money = Double.compare(Bal,Mon);
   							if (Enough_Money > 0  ){
   								try{
   	   								Bal -= Mon;
   	   								FileWriter fileWritter = new FileWriter("MC_Web/Users/" + Name +"/Account.acc",false);
   	   	   	   	        	        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
   	   	   	   	        	        bufferWritter.write(Bal +"\n");
   	                                bufferWritter.close();
   	                                account.getHoldings().add(Mon);
   	                                pl.sendMessage(ChatColor.GOLD + ""+ Mon + " " + Money_Name + " has been withdrawn");
            	          			pl.sendMessage(ChatColor.GOLD + "Account balance is now " + Trun.format(Bal) + " " + Money_Name);
   	   							}
   	   							catch (IOException e){
   	   	   							pl.sendMessage(ChatColor.AQUA + "Error - Making Withdraw");
   	   	   							System.out.println("\n ** MC_Web Error - '" + Name + "' withdraw failed");
   							}}
   							else{
   								pl.sendMessage(ChatColor.AQUA + "Too Much To Withdraw: " + Trun.format(Mon) + " " + Money_Name);
   							}
   						}}
   					else{
   						pl.sendMessage(ChatColor.AQUA + "Error - You are not allowed to withdraw money");
   					}}}
// Catch 
   			else{
   				error(pl);
   			}}}
   	 return true;
    }}

Share this post


Link to post
Share on other sites
Advertisement

I have this plugin wired into Eclipse, that adds big red warning flags in the sidebar whenever an individual function exceeds 10 statements in length.

 

You might want to consider getting it smile.png

 

I was flipping through and this made my day!

Share this post


Link to post
Share on other sites

Ctrl+A then Ctrl+Shift+F :D

No, at this point the right keys are:
Ctrl+A then Delete (or Backspace)

Share this post


Link to post
Share on other sites

Hah, yeah, modularity is a good thing. :P

 

Then again, the old versions of towny's code was a nightmare to work with. And yet it is an excellent and popular plugin.

Share this post


Link to post
Share on other sites

I do not know what's worse: excessive nesting, or excessive classes in Java ....

Share this post


Link to post
Share on other sites

Excessive code!

 

But on a serious note, I've been taught a rule of thumb that whatever reduces complexity tends to be the lesser evil.

Edited by Mitchell314

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement