开发者

Can't replace a letter in a string

I have asked a couple of questions about this for loop:

  String[] book = new String [ISBN_NUM];
  bookNum.replaceAll("-","");
  if (bookNum.length()!=ISBN_NUM)
    throw new ISBNException ("ISBN "+ bookNum + " must be 10 characters");
  for (int i=0;i<bookNum.length();i++)
  {
      if 开发者_开发技巧(Character.isDigit(bookNum.charAt(i)))
      book[j]=bookNum.charAt(i);  //this is the problem right here
      j++;
      if (book[9].isNotDigit()|| 
          book[9]!="x"        ||
          book[9]!="X")
      throw new ISBNException ("ISBN " + bookNum + " must contain all digits" + 
                               "or 'X' in the last position");
  }

which will not compile. An answer I had from the other question I asked told me that the line where the error occurs is wrong in that bookNum.charAt(i) is an (immutable) string, and I can't get the values into a book array that way. What I need to do on my assignment is check an ISBN number (bookNum) to see that it is all numbers, except the last digit can be an 'x' (valid ISBN). Is this the best way to do it? If so, what the hell am I doing wrong? If not, what method would be a better one to use?


book is of type String[] (array of strings), bookNum.charAt(i) returns a char. You can't assign a String from a char.

Do book[j] = String.valueOf(bookNum.charAt(i)) instead.

Also you might want to change the first error:

throw new ISBNException ("ISBN "+ bookNum + " must be " + ISBN_NUM + " characters");


The book[] array contains Strings.

The method bookNum.charAt() returns a char.

You can't assign a char to a member of a String array.

If you want an array of Strings, consider using bookNum.substring( i, i + 1 ).


What you are doing wrong is that you declare book as a String Array instead of just a String.


Here is the problem :

String[] book = new String [ISBN_NUM];

You create an array of String objects, but then you feed it with chars :

book[j]=bookNum.charAt(i);

Just initialize the array like this :

char[] book = new char[ISBN_NUM];

Furthermore, you should get rid of your j variable that does the same as i. And end the for loop before checking book[9] or you will get a NullPointerException.

Hopefully there are not any more problems :)


See my answer in your other thread. You are basically treating an array of strings like a string (or array of characters). What is your goal here? You just want to validate that the bookNum is a valid ISBN, correct? What is the course of action if it is not? If your goal is to take the whole bookNum if it is valid and abort if it isn't, my answer in the other thread should give hints as to a possibly better way to do that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜