• Post Reply Bookmark Topic Watch Topic
  • New Topic

Assistance With Head First Java Problem  RSS feed

 
Dania Khan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I'm trying to teach myself Java and came across a problem I'm hoping to get insight on. I need to basically figure out what the possible output is for candidate blocks of code, which would be substituted in the program where the underline is. Here it is:



Candidates:
x = x + 3;
x = x + 6;
x = x + 2;
x ++;
x --;
x = x + 0;

Possible output:
45 6
36 6
54 6
60 10
18 6
6 14
12 14

I've tried iterating through this code, but my results will either match only with some of the x values of the possible output, or not at all...I'm not sure what I'm doing wrong. I would appreciate any assistance. Thanks!
 
Knute Snortum
Sheriff
Posts: 4287
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is your best guess?
 
Dania Khan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After multiple tries and erasures, this is what I got:

HFJava.jpg
[Thumbnail for HFJava.jpg]
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One way to find out would be to write the code with each of those lines, compile it, and run it.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dania Khan wrote:I'm trying to teach myself Java and came across a problem I'm hoping to get insight on. I need to basically figure out what the possible output is for candidate blocks of code, which would be substituted in the program where the underline is. Here it is:

Tip: I suspect it's because you're trying to take it all in at once. DON'T. Take each line you don't understand one at a time.

Get lots of paper, and a pencil and work through it. For example:

for (int outer = 0; outer < 3; outer ++) { ...

What does it do? What are the possible values for 'outer'? Forget about everything else and concentrate on THAT.

Then try the next loop, and do the same - and don't forget that the inner loop will be executed completely for each iteration of the outer one.

Then, I'd advise making some tables and tracing through each iteration in turn, noting down the value of each variable as you go.

Very often, after a few rounds, something will leap out at you and you'll go "ah, so THAT'S what it's doing"; but you won't get there unless you put in the hard work.

Welcome to programming.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!