• 0

[Java] -- for loop -- multiple types


Question

Hey all. This article states that I can only declare multiple variables of the same type inside a for loop. I was wondering whether there is any way around that, I would like to declare multiple types of variables in my for loop.

I know this sounds unkosher, and it is :D I'm trying to transform a big block of readable code into one single for loop where everything happens in the for loop except the output to console, just for the giggles of it. If anyone is interested in a piece of code ripped out of its context, here ya go:

for(boolean player=round%2,String tokens[]=Terminal.askString("Player "+player?"1":"2"+"> ").split("\\s+"),int x=Integer.parseInt(tokens[0]),int y=Integer.parseInt(tokens[1]);
	fields[!player].dropBomb(x,y);
	Terminal.println("Hit") );
 Terminal.println("Miss");

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

while(true-what ur condition) {

String tokens[]=Terminal.askString("Player "+player?"1":"2"+"> ").split("\\s+");

int x=Integer.parseInt(tokens[0]);

int y=Integer.parseInt(tokens[1]);

boolean player=round%2;

If(fields[!player].dropBomb(x,y)) {

Terminal.println("Hit") );

} else {

Terminal.println("Miss");

}

}

for(;;) {

String tokens[]=Terminal.askString("Player "+player?"1":"2"+"> ").split("\\s+");

int x=Integer.parseInt(tokens[0]);

int y=Integer.parseInt(tokens[1]);

boolean player=round%2;

If(fields[!player].dropBomb(x,y)) {

Terminal.println("Hit") );

} else {

Terminal.println("Miss");

}

}

Link to comment
Share on other sites

  • 0

The condition is that the player can throw another bomb if he hit. Seeing as the player will always miss after a certain amount of hits (this is not true in a real game of battleships, but the code is still fun to write) I decided to approach it through that crazy for loop, just to see if things like this are possible in Java. So I would like to declare multiple variables of different types in the for loop, but apparently Java has another policy against that. I was just wondering whether that is possible maybe through something like an inline function or so (if Java has that)?

Link to comment
Share on other sites

  • 0

I did decalre those variable in the for loop. those varibles only have a life in the for / while loop. once the loop has finished, the varaibles get cleared.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.