What means can not be resolved to a variable? The condition contains an action that creates the variable Double xco, which is equal to the difference in the coordinates of the players by the "x". In another condition, I call this variable: "If_ (xco <10) {...}" At this stage, an error is generated

@EventHandler public <ChatMessage> void onPlayerChat(AsyncPlayerChatEvent z) { Player p=z.getPlayer(); Location I=p.getLocation(); String a=z.getMessage(); if (a.equals("word")) { for (Player ps : Bukkit.getOnlinePlayers()) { Location i = ps.getLocation(); if (I.getX()<0 && i.getX()<0){ double xco = I.getX() - i.getX();} else if (I.getX()>0 && i.getX()>0 ) { double xco = I.getX() - i.getX();} if (I.getY()<0 && i.getY()<0) { double yco = I.getY() - i.getY();} else if (I.getY()>0 && i.getY()>0 ) { double yco = I.getY() - i.getY();} if (I.getZ()<0 && i.getZ()<0) { double zco = I.getZ() - i.getZ();} else if (I.getZ()>0 && i.getZ()>0 ) { double zco = I.getZ() - i.getZ();} if (xco<10) { ps.playSound(ps.getLocation(), Sound.BLOCK_ANVIL_DESTROY, 1, 5); ps.sendMessage("Test");} 
  • It is not recommended to create variables "in condition". This leads to such errors. - Enikeyschik
  • Is there any alternative? - Antony Antony

1 answer 1

Variables must be created at the beginning of the class / method where they are used. First, they are then available throughout the class / method, and secondly, it makes reading and understanding the code easier:

 public <ChatMessage> void onPlayerChat(AsyncPlayerChatEvent z) { Player p = z.getPlayer(); Location I = p.getLocation(); String a = z.getMessage(); double xco = 0; // <- вот здесь double yco = 0; double zco = 0; 

In your code, the xco variable may not be created at all, which will cause the program to crash during execution.

  • If this is overwritten, then Duplicate local variable errors occur under the conditions where they were given values - Antony Antony
  • Because in the future you just need to write xco , not double xco . - Enikeyschik
  • 1. Open the tutorial and read about the scope of variables. 2. What happens if I.getX() greater than 0 and i.getX() less than 0? 3. Learn to give variable clear names. What is the difference between i and i ? I generally recommend not using anything as a name. See the difference between I and l? And she is. - Enikeyschik
  • Thanks, get acquainted - Antony Antony