Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes How? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How?" Watch "How?" New topic


Lenny Peter
Ranch Hand

Joined: Apr 22, 2008
Posts: 52
How can I write this correctly?

public void setAge(int age)
if(age > 0 && age < 18) {
System.out.println("Age:" + age + " " + "this member is junior.");
else if(age >= 18) {
System.out.println("Age:" + age +" " + "this member is senior.");
else {
System.out.println("The member's age cannot be 0");

Thanks ;-)
Darryl Burke

Joined: May 03, 2008
Posts: 5115

Umm, so what's wrong with the code you posted? (apart from the unfortunately named method that doesn't in fact set a int field named age.)

luck, db
There are no new questions, but there may be new answers.
Gary Morris

Joined: Apr 29, 2008
Posts: 8
Yeah, I don't see why it couldn't work as-is, but would be more meaningful to give it a proper name like:

[ May 11, 2008: Message edited by: Gary Morris ]
arulk pillai
Ranch Hand

Joined: May 31, 2007
Posts: 3371
also use of log4j instead of System.out.println might be better.

[] | [Java job hunting know how] | [Java resumes]
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15082

Your method is called 'setAge', but I don't see you setting the entered age anywhere. You only check the value of the parameter. Maybe you intended to save the value in a member variable?

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
Also, I see that if someone passes a negative int to the method, they will get a reply "The age cannot be 0." They might say, "I didn't say 0; I said -7!"
Gary Morris

Joined: Apr 29, 2008
Posts: 8
Maybe if you gave a little more info on what it is that you WANT it to do, then someone could offer a little better advice?
Deepak Bala

Joined: Feb 24, 2006
Posts: 6662

A better title will also help

SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Arvind Mahendra
Ranch Hand

Joined: Jul 14, 2007
Posts: 1162
you also don't need those braces with every if else since you only have single statements.

I want to be like marc
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63852

Originally posted by Arvind Birla:
you also don't need those braces with every if else since you only have single statements.

Though many coding conventions state that it's best to include them regardless.

[Asking smart questions] [About Bear] [Books by Bear]
I agree. Here's the link:
subject: How?
jQuery in Action, 3rd edition