无法替换字符串中的字母

uni*_*nit 0 java

我已经问了几个关于for循环的问题:

  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");
  }
Run Code Online (Sandbox Code Playgroud)

哪个不会编译.我从另一个问题得到的答案告诉我,错误发生的行是错误的,因为bookNum.charAt(i)是一个(不可变的)字符串,我无法将这些值转换为书籍数组.我需要做的是检查一个ISBN号(bookNum),看它是否都是数字,除了最后一位数字可以是'x'(有效的ISBN).这是最好的方法吗?如果是这样,我到底做错了什么?如果没有,用什么方法会更好?

sjr*_*sjr 6

book是类型String[](字符串数组),bookNum.charAt(i)返回一个char.你不能String从a 分配char.

book[j] = String.valueOf(bookNum.charAt(i))代替.

您还可以更改第一个错误:

throw new ISBNException ("ISBN "+ bookNum + " must be " + ISBN_NUM + " characters");
Run Code Online (Sandbox Code Playgroud)