문제

I'm using Blue J and would love to be able to test out small fragments of code without having to create a new program, create a class, and write a method. Does Blue J have any way to run simple segments of code (like trying out a new method) without creating a whole new program?? Similar to operating in the Python shell rather than a new file.

도움이 되었습니까?

해결책

The code pad allows you to run some code and instantiate objects. It is helpful for testing small bits of code, but not the type of tool that allows for complete methods as far as I understand. The code pad can be accessed under View -> Show code pad.

다른 팁

Sorry, I'm not able to comment on answers yet - you can write as much code in the code pad as you want, really, probably including full methods if you really wanted to - the only differences between the code pad and regular coding are 1. You don't need to write any 'boilerplate', ie code does not have to be in a method or class structure, and 2., BlueJ will evaluate each line as you enter it, rather than all at once.

Don't forget that SHIFT + ENTER goes to the next line without 'sending' what you've typed to the compiler, too - though in most cases you can write line-by-line, this can help you practice formatting and keep multiple statements (with semicolons of course) from getting unreadable and confusing to debug.

Just as a proof-of-concept, try the below out in the BlueJ codepad. It should work either as one block (using shift+enter) OR as a series of individual lines:

    int apples = 5; 
    int pears = 4;
    int fruit = apples + pears;
    System.out.println("we have " + apples + " apples and " + pears + " pears.");
    System.out.println("that's " + fruit + " pieces of fruit");

It seems, however, that while coming up with examples I've found a limitation. While if (apples > pears) System.out.println("We have more apples than pears"); works fine, it doesn't seem to like me adding an else statement. But if/else statements are probably reaching the threshold where you are better off writing your code out properly, anyway. The code pad is more useful for "how does this work" type of queries that beginners like us tend to have, or to test an individual line before putting it into your method. I often use it to experiment with formatting/structure problems like "is it possible to do evaluations within a println statement" (It is - in the above example we could have just had System.out.println("that's " + (apples + pears) + " pieces of fruit");

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top