Is there any easy way such as break for whiles to stop/skip a running function?
public void a(){
do_this();
//break the function here
do_that(); //do not load this
}
What I want to approach could be done with boolean and if statements as well, but I was wondering if there was some shortcut command in order to do this.
public void a(){
do_this();
if(1==1)
return;
do_that(); //do not load this
}
Just curious, why do you want to write such a code?
let the first function return a boolean that indicates if the calling function should move on:
public void a(){
boolean doContinue = do_this();
if(doContinue) {
do_that();
}
}
i you ALWAYS want to skip the second part, it's dead code. you could just remove it.
Always have in mind that your code should be readable for other programmers!
Related
Is it good or bad practice to have an else branch which only returns in a function that returns type void? Such as this code:
public void myFunc() {
if (<some condition>) {
//run some code
} else {
return;
}
}
Note that this topic is opinion based, you will probably see many different preferences from user to user.
For readability and maintainability you should try to reduce the complexity of your code. Therefore you want to also reduce the nesting. Thus my prefered variant would be:
public void myFunc() {
// Directly leave if condition does not hold
if (!condition) {
return;
}
// Now do the rest of the code
}
If you want to stick to your current variant then I would suggest to just drop the else part because it just aggravates the readability in my opinion, so:
public void myFunc() {
if (condition) {
// Do something
}
// You can always leave a comment if you think
// that helps a reader, so you can put "Do nothing
// if condition does not hold" here
}
However as said, I personally prefer the first variant because it reduces the nesting of the overall code.
No, this else statement is not required if you are not doing any operation.
The else statement is basically used to carry out an operation, if the condition of if do not met.The best practice is not to write the else statement, if you are not doing any operation.
public void myFunc() {
if (<some condition>) {
//call FunctionA();
} else {
//call FunctionB();
}
}
In the above case, the use of else is valid. But if you are not doing any operation, then the statement is useless. Please read Clean Code Book by Robert Cecil Martin. It will help you in writing clean code.
From the java.lang.Void class documentation:
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.
So any of the following would suffice:
Parameterizing with Object and returning new Object() or null.
Parameterizing with Void and returning null.
Parameterizing with a NullObject of yours.
You can't make this method void, and anything else returns something. Since that something is ignored, you can return anything.
So i'm trying to make a text game in java for a project and i have a problem in the main loop.I have the available commands in a hashmap named commands in the class CommandWords and i want to check if the user input exists in the hashmap and if it does to execute the associated object.But i can't exactly find a way.Here is my code.I understand it's probably an if but i don't know how to check.
public void play()
{
System.out.println("Welcome to the world of JZork " +player.name);
printWelcome();
boolean finished = false;
while (! finished) {
Command command = parser.getCommand();
if(command == null) {
System.out.println("I don't understand...");
}
}
}
It is possible to do it the way you said, but you would need to learn to use Java reflection. This isn't THAT hard, but you aren't going to like it.
if (command.equals("quit")) {
quit();
}
else if (command.equals("whatever")) {
whatever();
}
This isn't that elegant, but it's easy to implement.
I really like the mechanism and style of this code, but Im kinda unaware if this coding style is appropriate or a bad practice.
public class Test
{
private static int counter;
private final static ArrayList<Object> _objects = new ArrayList<>();
public static void main(String[] args)
{
//iterate till you find a valid object randomly
while (!doStuffIfValid(_objects.get(Rnd.get(_objects.size()))));
}
public static boolean doStuffIfValid(Object obj)
{
if (++counter > 30)
return true; //dont try more than 30 times
// if condition
// {
// //do stuff then exit the caller loop
// return true;
// }
return false;
}
}
Well,
The answer to that lies within the boolean method. If that method is bloated, and resource heavy; then no.
Also, if you're randomly checking objects, it may be a better idea to instead: eliminate the objects you know aren't valid from a list, then randomly select from that list.
This way the pseudo-randomizer doesn't (by chance) select invalid objects to validate over, and over again; and waste time/resources.
Cheers.
There is nothing wrong with using a boolean method as a condition for a while-loop. However, stuffing loop functionality in the loop header is, generally, a bad practice. It leads to a code which is difficult to understand, debug (breakpoints become inconvenient) and maintain.
Hi Im a begginer with Java so no complex code etc
Basically to avoid my code from getting too long i want my user to input a choice and then i have a bunch of for and elese's for what happens if they enter a certain phrase, e.g.
if(choice.equals("Fight")) {
//Grab code from fight.java/fight.class
}
else
{
if(choice.equals("Train")) {
//Grab code from train.java/train.class
}
else
so on and so forth for two other possible inputs. I just need to know how to call external code so it doesn't get too cluttered.
You should create objects of these classes.
For example:
if(choice.equals("Fight")) {
//Grab code from fight.java/fight.class
fight f = new fight();
f.foo(); // A method
}else{
if(choice.equals("Train")) {
//Grab code from train.java/train.class
train t = new train();
t.foo(); // A method
}
//...
}
Or you can try static methods like that:
public class train{
public static void foo(){
//...
}
}
Then you can use it.
if(bool_expression){
train.foo(); // foo is a static method
}
Instead of using the for else structure I would suggest using a switch statement. This will look like:
switch(choice){
case"fight":
Fight.kickHard();
break;
case"train":
Train.run();
break;
default:
Program.learn();
}
Don't forget about the break statements when using a switch. In my example I used static methods from the classes. You would probably be well served by looking further into object oriented design to see if you can come up with a more streamlined answer to your particular problem. The additional classes will need to be imported with an import statement. You will want to look into the shortcut for your IDE to do that for you, but it is a fairly elementary statement e.g import my.package.Train; etc.
If you are trying to call static methods, it would be as simple doing the following.
train.doStuff();
If the methods belong to an object you would first have to instantiate an object to access any methods on it.
Train train = new Train();
train.doStuff();
NOTE: an IDE will automatically link up the classes for you. Otherwise you have to manually import these classes first by adding "import somepackage.someclass".
First focus on different things you program can do. Place that code in a method with a name indicating its intent:
private static void doWork(){
System.out.println("Working");
}
private static void play(){
System.out.println("Playing");
}
private static void sing(){
System.out.println("Singing");
}
Now, you need to bind these to user's phrases (assuming Java 7):
switch(choice){
case: "work"
doWork();
break;
case: "play"
play();
break;
case: "sing"
sing();
break;
default:
System.out.println("Unknown choice");
}
I'm developing a Java application that uses Kahlua for embedded Lua scripting. After calling a lot of functions it always crashes with a stack overflow... is there something I need to do to remove unused call frames from the stack?
In standard Lua, you can use the lua_pop function to remove items from the Lua stack. See this answer for hints on this usage.
If you are calling your code repeatedly, the easiest thing to do is store the height of the stack before the processing and restore it afterwards:
int top = lua_gettop(L);
... /* some processing involving the stack*/
lua_settop(L, top);
Now, I'm not sure how to achieve this in Kahlua. But in the source I see LuaCallFrame.getTop() and LuaCallFrame.setTop() so the code should be similar.
If you're using the Kahlua framework correctly, the stack should automatically get cleaned up when returning from a function. If this is not so, you've found a bug, and I would very much like a bug report on it :)
Best would a (close to) minimal testcase which exposes the problem.
You have to make sure you return out of every method call. For example:
...main(...){
displayMenu();
}
void displayMenu(){
System.out.println("1.Do A. \n2.Do B");
int q = readInt;
if (q==1){
doA();
}else{
doB();
}
}
void doA(){
.....
displayMenu()
}
void doB(){
....
displayMenu();
}
A way to make the stack not blow up is to do something like this:
...main(...){
while(true){displayMenu()};
}
void displayMenu(){
System.out.println("1.Do A. \n2.Do B");
int q = readInt;
if (q==1){
doA();
}else{
doB();
}
}
void doA(){
.....
}
void doB(){
....
}
This way all the calls return back to the base level.
Try and use tail calls where you can, they don't take up a stack slot:
function foo ( )
return bar()
end