Eclipse auto-indent incorrectly indents file - java

Something weird is happening to my Eclipse that I never remember happening before. Basically if I've got a long statement and split it onto two lines, then everything after that gets indented a tab further than it should be. Here's an example:
Correct indentation:
public static class Shape {
enum Tetrominoes { NoShape, ZShape, SShape, LineShape, TShape,
SquareShape, LShape, MirroredLShape };
private Tetrominoes pieceShape;
private int coords[][];
private int[][][] coordsTable;
public Shape() {
coords = new int[4][2];
setShape(Tetrominoes.NoShape);
}
public void setShape(Tetrominoes shape) {
}
}
What it looks like with Ctrl+A, Ctrl+I:
public static class Shape {
enum Tetrominoes { NoShape, ZShape, SShape, LineShape, TShape,
SquareShape, LShape, MirroredLShape };
private Tetrominoes pieceShape;
private int coords[][];
private int[][][] coordsTable;
public Shape() {
coords = new int[4][2];
setShape(Tetrominoes.NoShape);
}
public void setShape(Tetrominoes shape) {
}
}
Now if I keep that enum on one line and auto-indent it, then it works out just fine. I just got a new laptop and put a fresh copy of Eclipse on it and didn't change any settings, so this is how the default auto-indent works. But I remember on my old laptop if I would split a statement onto two lines then everything else after that would still be properly aligned?
(Also at the start of this post I put "Hey guys," but it looks like StackOverflow automatically removed it? I tried editing the question and reinserting it but it still got removed once posting. I tried putting "Hey," but that got removed too. Does SO not believe in greetings??)

I was able to reproduce the issue.
It seems that the ending brace for the enum is confusing Eclipse. If you put that on a separate line the indentation starts working fine :
public static class Shape {
enum Tetrominoes { NoShape, ZShape, SShape, LineShape, TShape,
SquareShape, LShape, MirroredLShape
};
private Tetrominoes pieceShape;
private int coords[][];
private int[][][] coordsTable;
public Shape() {
coords = new int[4][2];
setShape(Tetrominoes.NoShape);
}
public void setShape(Tetrominoes shape) {
}
}
You can also attempt to format the code (Ctrl + Shift + F) followed by correcting indentation (Ctrl + A and Ctrl + I ). When you format the code, you'll notice that Eclipse also puts the ending brace on the next line instead of alongside the Enum constant body.

Related

Function with same name and parameter class name (but different parameter classes)

I ran into a very strange problem that I don't know if I'm even allowed to do.
Basically I have two functions witch should have the same name but get different parameter objects which have the same name.
This is because I want to write a plugin for the game Minecraft and this should be compatible with BungeeCord and Bukkit servers.
public static void sendMessage(org.bukkit.command.CommandSender p, String k, Object...i){
//fancy stuff
}
public static void sendMessage(net.md_5.bungee.api.CommandSender p, String k, Object...i){
//fancy stuff
}
If the plugin is loaded by a Bukkit server the plugin it doesn't know anything about net.md_5.bungee.api.CommandSender since this is a class of the BungeeCord server core and the same is for org.bukkit.command.CommandSender where it is used by Bukkit but not by BungeeCore.
I have no problem compiling the code with IntellIJ even dough I'm a bit sceptic because if decompiled it looks like this:
import org.bukkit.command.CommandSender;
public static void sendMessage(CommandSender p, String k, Object...i){
//fancy stuff
}
public static void sendMessage(net.md_5.bungee.api.CommandSender p, String k, Object...i){
//fancy stuff
}
My first question is: Can I even do this, or will this give exceptions since not all Classes are loaded, even dough it will never get accessed?
Now if the first question can be answered by Sure you can then why is there a compilation problem by compiling eigther a Bukkit or a BungeeCord plugin using this sendMessage( function?
Bukkit:
BungeeCord:
Because if this doesn't work I know for sure that you can at least work with Classes that aren't loaded if you put them into your codeblock since this code works just fine and isn't even throwing an exception when not loaded by a server that is using org.bukkit.craftbukkit.v1_13_R2.entity.CraftPlayer aldough it is in the imports:
import org.bukkit.entity.Player;
import org.bukkit.craftbukkit.v1_13_R2.entity.CraftPlayer;
public static int getPing(Player p) {
String version = getVersion(instance.getServer());
if (version.startsWith("v1_8")) {
return ((org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer)p).getHandle().playerConnection.player.ping;
} else if (version.startsWith("v1_9")) {
return ((org.bukkit.craftbukkit.v1_9_R2.entity.CraftPlayer)p).getHandle().playerConnection.player.ping;
} else if (version.startsWith("v1_10")) {
return ((org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer)p).getHandle().playerConnection.player.ping;
} else if (version.startsWith("v1_11")) {
return ((org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer)p).getHandle().playerConnection.player.ping;
} else if (version.startsWith("v1_12")) {
return ((org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer)p).getHandle().playerConnection.player.ping;
} else {
return ((CraftPlayer)p).getHandle().playerConnection.player.ping;
}
}
So is this really a thing I simply cannot do or is this a problem of the compiler of IntellIJ and if so how can I fix it?
Well my attempt to your idea would be to call methods in sub classes. It might be an issue that the non found class is a parameter. When the class is accessed (just my speculations) the parameters are tried to load to determine which method to use.
So something like the following would be the output.
In the class you access have:
public static void sendMessage(Object player, String k, Object...i){
if(isBukkit())
MyBukkitUtils.sendMessage(player, k, i);
else
MyBungeeUtils.sendMessage(player, k, i);
}
MyBukkitUtils:
public static void sendMessage(Object player, String k, Object...i){
if(!(player instanceOf CommandSender))
return;
CommandSender p = (CommandSender) player;
//fancy stuff
}
Same for MyBungeeUtils just with the BunggeeCommandSender.
I don't know your code, but if you have to have everything seperated you can just code two plugins (one for spigot, one for bungee) and use a include a library in both were the common code is placed.

IntelliJ IDEA not showing member field

Problem as picture bellow, is there any option to enable showing member abc?
I am using IntelliJ IDEA CE 2017.2.1 with JDK 9+179.
Here is the sample code above:
public class Test {
#FunctionalInterface
interface IF {
String abc = "abc";
void apply();
}
public static void main(String[] args) {
IF theIF = ()->{};
System.out.println(theIF.abc); // I can print `abc` value here, but...
theIF. // DOT here(press ctrl + space) not show member `abc`
}
}
This is accessing static member with instance qualifier, and is better done as IF.abc. Therefore code completion doesn't offer it right away, but if you press Ctrl+Space second time, it should be suggested.

Collisions of while loops when in a row (Java)

I build a game that includes moving between worlds. The main class of the program suppose to start by presenting the first world (world1 which is an instance of the firstWorldClass). It should stay in this world until a variable within the class world1 is changing (checked by world1.getMoveWorldIndicator()). Then, it should move to the next world- remove world1, build world2 and add it to the graphic view. Same from world 2 to 3.
It works fine when I do it between 2 worlds (delete all the code after add(world2)) or if I leave only the transition between the second and the third worlds. When I put both in a row it stops working (when adding the second while loop).
My code:
public class GameManager extends Program implements GameContstants{
public void init() {
world1=new firstWorldClass();
add(world1);
while(!world1.getMoveWorldIndicator()){
pause(200);
if(world1.getMoveWorldIndicator())break;
}
remove(world1);
world1=null;
world2=new secondWorldClass();
add(world2);
pause(200);
while(! world2.getMoveWorldIndicator()){
pause(200);
if(world2.getMoveWorldIndicator()) break;
}
remove(world2);
world2=null;
world3=new thirdWorldClass();
add(world3);
}
private firstWorldClass world1;
private secondWorldClass world2;
private thirdWorldClass world3;
}
I suspect that there's some kind of interaction between the while loops or a memory problem but am open to hear any idea/different way to do it.
Thanks!
I think there are lots of factors coming into play here:
Clean up your code. Keeping a few coding rules is important for bug fixing!
Don't use repetitive code over and over again. Extract to method or Class
Keep to class naming conventions => Upper camel case for classes
Don't set variables to null. Usually compilers will do that for you while optimizing. If you still feel like manually freeing up space or variable names, you should use scope brackets {} around the code instead!
Breaking down your code, we see lots of redundancies, like "getMoveWorldIndicator()" checks twice per loop, without any different effect from using it only once
I have provided a cleaner - but different - version here, to show you.
But for actually helping you with your code, we really DO NEED more of your code to gain some insight to the problem.
public class GameManager /* extends ... */{
static class WorldBase {
public boolean getMoveWorldIndicator() {
return false;
}
}
static class FirstWorld extends WorldBase {}
static class SecondWorld extends WorldBase {}
static class ThirdWorld extends WorldBase {}
public void init() {
playWorld(new FirstWorld());
playWorld(new SecondWorld());
playWorld(new ThirdWorld());
}
private void playWorld(final WorldBase pWorld) {
add(pWorld);
while (!pWorld.getMoveWorldIndicator()) {
pause(200);
}
remove(pWorld);
}
private void remove(final WorldBase pWorld1) {}
private void pause(final int pI) {}
private void add(final WorldBase pWorld1) {}
}

Array of Bodies in Box2D (Java)

I'm pretty new to Box2D and have very little programming experiences at all, so please be patient. Currently I am working on a little Breakout game.Something like a really simple version of this:http://i.computer-bild.de/imgs/4/9/8/6/7/5/1/Google-Breakout-745x419-9c0b3d2ebbdeae82.jpg
It is an exercise for my university. At this point I already created the paddle, the ball and the walls. Now I want to create the bricks. My problem is that I'm not sure how to organize them. I thought about making a class for the bricks with 2 floats in the constructer for the actual position of the one brick. Then I wanted to create Arrays of the brick class.
At this point my code looks like this:
private Body brickBody;
private PolygonShape brickShape;
private BodyDef brickBodyDef;
private Fixture brickFixture;
Physik phy;
public CleverBrick(float a, float b, final Physik p) {
brickBodyDef = new BodyDef();
brickBodyDef.type = BodyType.StaticBody;
brickBodyDef.position.set(new Vector2(a,b));
phy =p;
brickBody = Physik.getWorld().createBody(brickBodyDef);
brickShape = new PolygonShape();
brickShape.setAsBox(30,5);
Fixture brickFixture = brickBody.createFixture(brickShape, 0.0f);
brickFixture.setUserData("The brick");
}
public void destroyBrick() {
brickBody.destroyFixture(brickFixture);
}
public Body getBrickbody() {
return brickBody;
}
public void setBrickbody(Body brickbody) {
this.brickBody = brickbody;
}
public PolygonShape getBrickShape() {
return brickShape;
}
public void setBrickShape(PolygonShape brickShape) {
this.brickShape = brickShape;
}
public BodyDef getBrickBodyDef() {
return brickBodyDef;
}
public void setBrickBodyDef(BodyDef brickBodyDef) {
this.brickBodyDef = brickBodyDef;
}
public Fixture getBrickFixture() {
return brickFixture;
}
public void setBrickFixture(Fixture brickFixture) {
this.brickFixture = brickFixture;
}
}
And I try to create the array with this in the main class with these lines:
for (int i =0; i<9; i++) {
bricks[i] = new CleverBrick(100,100, this);
}
Later I want to import different structures of bricks from xml files, this is just a test case.
I always get a NullPointerException at the line :
brickBody = Physik.getWorld().createBody(brickBodyDef);
and I dont know why. I think the problem is about getting the world from
I hope someone can help me with that.
Couple of questions:
what is the class Physik.java?
why do you use floats for the Brick positions? these don't seem like floating point numbers to me, an int feels natural here
regarding NPE - #Atuos is right - watch what is null. Here it seems that either Physik or getWorld() are null values. Shouldn't you write
physik.getWorld.createBody()
Either way - it would be nice if you could amend your question by clearly stating what is it that you're asking and providing more source code - the whole class CleverBrick and Physik

Trivia game with JFrame

I'm trying to make a trivia game. My problem is that, the questions does not show up in the frame when I try to run the program. what should I do? Here's what I have done so far. any help would really be great. thanks in advance.
package trivia;
import java.util.Arrays;
import java.util.List;
public class ChemistryJFrame extends javax.swing.JFrame {
String question, answer;
ChemistryJFrame[] questionbank = new ChemistryJFrame[3];
List<ChemistryJFrame> questionlist = Arrays.asList(questionbank);
int quest;
public ChemistryJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
dispose();
MainJFrame Main = new MainJFrame();
Main.setVisible(true);
}
public static void main(String args[]) {
ChemistryJFrame bank = new ChemistryJFrame();
bank.banklist();
bank.startquiz();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChemistryJFrame().setVisible(true);
}
});
}
public void banklist()
{
questionbank[0] = new ChemistryJFrame();
questionbank[0].question = "Which of the following scientists was awarded the Nobel Prize in 1911 for the discovery of the radioactive elements, radium and polonium?\n A) Charles Darwin\n B) Dmitri Mendeleev\n C) Marie Curie";
questionbank[0].answer = "C";
questionbank[1] = new ChemistryJFrame();
questionbank[1].question = "How many electrons can occupy an s orbital?\n A) one\n B) two\n C) three";
questionbank[1].answer = "B";
questionbank[2] = new ChemistryJFrame();
questionbank[2].question = "Which noble gas has the highest melting point ?\n A) argon\n B) xenon\n C) radon";
questionbank[2].answer = "C";
}
public void startquiz()
{
for(quest=1; quest<10; quest++)
{
questionlabel.setText(questionbank[quest].question);
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextField jTextField1;
private javax.swing.JLabel questionlabel;
// End of variables declaration
}
Your start quiz function seems totally wrong to me.
At the moment you are seeing nothing because the quiz start function is very rapidly setting the text to every question - finally ending at question 9 which is blank as you never set it in the banklist function.
I would imagine that you intend to set the text to the qustion[0] text and then wait for some kind of user response?
public void startquiz()
{
for(quest=1; quest<10; quest++)
{
questionlabel.setText(questionbank[quest].question);
}
}
Lots of issues:
You are iterating from 1 to 10, but you only define questionbank as an array of 3 items. ArrayIndexOutOfBounds is being thrown.
Even if the above is solved, you just iterate all questions before the data is even displayed. You would only get to see the last one. Learn to program with listeners, this is how GUIs work (not sequentially as command line programs).
You also have what seems to be an actionListener method for a button that does not exist, clean your code.
You never actually create questionlabel. You need to create it first and then add it to the frame.
Also in this piece of code:
for(quest=1; quest<10; quest++)
{
questionlabel.setText(questionbank[quest].question);
}
You'll be overwriting label text 10 times and only the last question will be shown. What you probably need is ten different labels.
Another thing is that you create only 3 questions, but iterate over 10. Arrays in Java start with zero so you need to change for(quest=1 to for (quest=0
Those are not all of the problems with your code, but keep trying, you'll get there eventually :)

Categories