Homework 4 (Birthdays) FAQ

Q: How do I use Scanner? How do I do returns?

A: Look at the examples in the textbook. For examples of Scanner, look at the "case study" examples from Chapters 3 and (especially) 4. The case study in Ch. 4 is also good for understanding returns, with its getBMI and bmiFor methods (and examining how they are called and used from main).

Also look at the lecture examples from this past week.

Q: I'm returning a variable, but I get a "cannot find symbol" error in main when I try to use the variable. Why can't main see my variable?

A: Just returning a variable from your method doesn't mean main now can refer to that variable. The variable's value is returned, not its name. The main method must store the result into a variable and then examine that variable. Instead of:

myMethodThatReturns(param1, param2);

You may need to say something like:

int result = myMethodThatReturns(param1, param2);

Q: Why does my program always print 0 as the result after I do math operations?

A: Maybe you are mistakenly using integer arithmetic. Remember that in Java, 40 / 50 is 0.

Q: How do I return two things from a method?

A: You can't! You need to organize your program so you only need to return one thing from each method.

Q: But I have a method that reads / computes two important values. How do I get those values over to the other parts of my program?

A: There are several ways. One would be to have your method call the other method, passing the two important values as parameters, rather than trying to return the two values. Another possibility is that maybe you don't need to return both the values; maybe one of them is more important than the other, so you can just return the more important one. Third, if the method is short, you might consider just putting that code in main and then having main pass the two important values to the rest of your program.

Q: How do I round a number to a certain number of decimal places?

A: See the third page of the homework write-up. There is a method called System.out.printf that you'll find useful.

Q: How do I read two values from the Scanner on the same line?

A: Just prompt once and then call nextInt twice in a row on the Scanner. See the back page of the homework write-up.

Q: Can my main method contain println statements? Can it contain an if statement? How many lines long can it be? ...

A: You should not have very many println statements in main, though you can have a few if necessary. You also shouldn't read user input directly inside the main method. main should be short, but it should summarize the overall program and should not contain too large a share of your overall code. The main method should represent a reasonable summary of the overall program's execution.