PDA

View Full Version : Java program help


Disvengeance
9 Oct 2005, 5:52am
Im writing this program for my programming class, when you use the setRefNumber method, it is supposed to set it to what you type if ref is greater than 3. But the problem is when you type in something greater than 3, it just sets it back to the default. any help? (i didnt include all of the source code)




public class Book
{
private String author;
private String title;
private int pages;
private String refNumber;
private int borrowed;

public Book(String bookAuthor, String bookTitle, int bookPages)
{
author = bookAuthor;
title = bookTitle;
pages = bookPages;
refNumber = " ";
}
public int getBorrowed() {
return borrowed;
}
public void setBorrowed(int booksBorrowed) {
borrowed = booksBorrowed;
}
public String getAuthor() {
return author;
}

public String getBookTitle() {
return title;
}
public int getBookPages() {
return pages;
}
public void setRefNumber(String ref) {
if(ref.length() > 3) {
ref = refNumber;
}
else {
refNumber = " ";
System.out.println("Error, Reference Number must be atleast 3 digits");
}
}

Disvengeance
9 Oct 2005, 7:27pm
Bump

shwaip
9 Oct 2005, 7:42pm
ref = refNumber;

should be
this.refNumber=ref;

whenever you refer to a field of the class, you should use the identifier "this.". It makes it easier to see exactly what is happening, and catch errors like that.

Disvengeance
9 Oct 2005, 8:09pm
Thanks, I cant tell you how much I appreciate the help :D

the professor has never mentioned that before :scratch:

Disvengeance
10 Oct 2005, 3:05am
sorry to be of a bother again, but i am having the same exact problem. I tried what was suggested earlier but this time it doesnt seem to work, it might just be that i am not seeing something.

these sections of code wont display the else statements when they should

public void setName(String fn, String ln) {
if (fn.length() > 0) {
this.firstName = fn;
}
else {
System.out.println("Please enter a First Name");
}
if (ln.length() > 0) {
this.lastName = ln;
}
else {
System.out.println("Please enter a Last Name");
}
}


public void setCountry(String coun) {
if (coun.length() >= 2) {
this.country = coun;
}
else {
System.out.println("Please enter a country name with more than two characters");
}
}


public void setNumberOfBooks(int num) {
if (num > 0) {
this.numOfBooks = num;
}
else if (num <= 0) {
num = 1;
System.out.println("Please enter a number which is > 1");
}
}

Disvengeance
10 Oct 2005, 4:10am
sorry but this is somewhat urgent

bump

shwaip
10 Oct 2005, 6:51am
How are you reading in the strings?
Perhaps there's a trailing character?

Try printing the length of the parameter right after you call the method. If it's not what you expect it to be, try printing the parameter followed by a "|".
System.out.println(ln + "|");
for example. That should show you if there's a trailing " " or newline (or something else).