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.
Related
I'm building a small app which auto translates boolean queries in Java.
This is the code to find if the query string contains a certain word and if so, it replaces it with the translated value.
int howmanytimes = originalValues.size();
for (int y = 0; y < howmanytimes; y++) {
String originalWord = originalValues.get(y);
System.out.println("original Word = " + originalWord);
if (toReplace.contains(" " + originalWord.toLowerCase() + " ")
|| toCheck.contains('"' + originalWord.toLowerCase() + '"')) {
toReplace = toReplace.replace(originalWord, translatedValues.get(y).toLowerCase());
System.out.println("replaced " + originalWord + " with " + translatedValues.get(y).toLowerCase());
}
System.out.println("to Replace inside loop " + toReplace);
}
The problem is when a query has, for example, '(mykeyword OR "blue mykeyword")' and the translated values are different, for example, mykeyword translates to elpalavra and "blue mykeyword" translates to "elpalavra azul". What happens in this case is that the result string will be '(elpalavra OR "blue elpalavra")' when it should be '(elpalavra OR "elpalavra azul")' . I understand that in the first loop it replaces all keywords and in the second it no longer contains the original value it should for translation.
How can I fix this?
Thank you
you can sort originalValues by size desc. And after that loop through them.
This way you first replace "blue mykeyword" and only after you replace "mykeyword"
The "toCheck" variable is not explained what is for, and in any case the way it is used looks weird (to me at least).
Keeping that aside, one way to answer your request could be this (based only on the requirements you specified):
sort your originalValues, so that the ones with more words are first. The ones that have same number of words, should be ordered from more length to less.
I am trying to print the letters of the alphabet in caps. So I wrote this in a for loop:
System.out.print(Character.toChars(i));
//where i starts at 65 and ends at 90
This works fine and prints the letters but In my code I wanted to put a space between the letters to make it look nicer. So i did this:
System.out.print(Character.toChars(i) + " ")
Why does it print the memory address of the characters instead of the letter?
The solution I came up with was to explicitly convert the char to a new String object:
String character = new String(Character.toChars(i));
System.out.print (character + " ");
but I'm not quite sure why I can't just write "Character.toChars(i)"
In the first one Does the method(Character.toChars()) point to the address of the character and System.out.print is smart enough to print the value at that address? i.e the corresponding letter?
System.out.print(Character.toChars(i)) calls PrintStream.print(char[]), an overload that handles char[] specially.
Character.toChars(i) + " " is really equivalent to Character.toChars(i).toString() + " "; calling toString() on an array type results in a string representation of its address (this behaviour is directly inherited from Object).
A simpler solution for your particular case may be this:
System.out.println((char)i + " ");
The Character.toChars method returns char[], which will be represented as [C#<hex hashcode> in String form.
You don't need to use the toChars method (or do any casting at all):
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
}
You use string concatenation, with one side being an array of chars and the other a string and according to the Java language specification, then as the char array is not a primitive type, but a reference value (aka an object), its toString method is called. And as there is no specific method implemented for arrays, they inherit the method implementation from java.lang.Object, which prints the address.
On the other hand, System.out.print(Character.toChars(i)) calls a specific implementation of print for character arrays, see the documentation of PrintStream.
I did read the documentaion on String.split(delimiter) and it says that the return type is String[]. But I don't know how to take that return of String.split() and assign its elements to my receiving String[]. The simple-minded
String[] z = stuff.split(" ");
(where stuff is a String) does not work. It compiles fine, but the z ends up being some mumbo-jumbo with ampersands. Looks like toString of something, not like a String array. Please enlighten me. Thanks.
UPADTE: Sorry for asking this. Of course it works. I knew too little at the time and was overwhelmed.
Of course a String array contains a toString method witch is what was probably called ...
From the comments by the OP:
Sorry, I made a mistake in the original question. The corrected question is shown now. No, String[] z = stuff.split(" "); does not work. System.out.println(" z = "+z); gives z = [Ljava.lang.String;#18e2b22
You should try this to print out the String array correctly:
String[] z = stuff.split(" ");
System.out.println("z = " + Arrays.toString(z));
First, the length of the of the returned array cannot be stuff.length() but count of the stuff portions delimited by given delimiter. It doesn't matter anyway because your initialized array will be discarded after assignment of new value returned by the split function. Find your string portions in z[i] strings where i < z.length ( or z.size() ).
So far I have a code that asks for a user input but a part of my code isn't accepting letters as inputs. For example if i type in say woah123 it'll give me a number format exception. Any way to get around this? Error is at the second line int i = Integer.parseInt(sentence).
Sentence is the user input
sentence.replaceAll("\\D", "");
int i = Integer.parseInt(sentence);
i = i * 2 ;
woah.replaceAll("\\d", "" + i);
System.out.println(woah);
Strings are immutable.
Generally, every modification you made on an immutable object will "give" you another immutable object.
So it should be :
sentence = sentence.replaceAll("\\D", "");
Indeed you have to do the same for woah.
You may read about what is an immutable object.
I have a strange problem when adding a value to a String array which is later involved in an array sort using a hash map. I have a filename XFR900a, and the XFR900 part is added to the array using the following code;
private ArrayList<String> Types = new ArrayList<String>();
...
Types.add(name.substring(0,(name.length() - 1));
System.out.println(name.substring(0,(name.length() - 1));
I even print the line which gives "XFR900", however the array sort later on behaves differently when I use the following code instead;
Types.add("XFR900");
System.out.println(name.substring(0,(name.length() - 1));
which is simply the substring part done manually, very confusing.
Are there any good alternatives to substring, as there must be some odd non ascii character in there?
Phil
UPDATE
Thanks for your comments everyone. Here is some of the code that later compares the string;
for (int i=0;i< matchedArray.size();i++){
//run through the arrays
if (last == matchedArray.get(i)) {
//add arrays to a data array
ArrayList data = new ArrayList();
data.add(matchedArray1.get(i));
data.add(matchedArray2.get(i));
data.add(matchedArray3.get(i));
data.add(matchedArray4.get(i));
data.add(matchedArray5.get(i));
//put into hash map
map.put(matchedArray.get(i), data);
}
else {
//TODO
System.out.println("DO NOT MATCH :" + last + "-" + matchedArray.get(i));
As you can see I have added a test System.out.println("DO NOT MATCH" ... and below is some the output;
DO NOT MATCH :FR99-XFR900
DO NOT MATCH :XFR900-XFR900
I only run the substring on the XFR900a filename. The problem is that for the test line to be printed last != matchedArray.get(i) however they are then the same when printed out to the display.
Phil
You should never use the == operator to compare the content of strings. == checks if it is the same object. Write last.equals(matchedArray.get(i)) instead. The equals() method checks if to object are equal, not if they are the same. In case of String it checks if the two strings consists of the same characters. This might eliminate your strange behaviour.
PS: The behaviour of == on string is a little unpredictable because the java virtual machine does some optimization. If two strings are equal it is possible that the jvm uses the same object for both. This is possible because String objects are immutable anyway. This would explain the difference in behaviour if you write down the substring manually. In the one case the jvm optimizes, in the other it doesn't.
Use .equals() rather than == because they are strings!
if (last.equals(matchedArray.get(i))) {}
Never use == operator if you wanted to check the value since operator will check the Object reference equality, use equals operator which check on the value not the reference i.e. for (int i=0;i< matchedArray.size();i++){
//run through the arrays
if (last.equals(matchedArray.get(i))) { // Line edited
//add arrays to a data array
ArrayList data = new ArrayList();
data.add(matchedArray1.get(i));
data.add(matchedArray2.get(i));
data.add(matchedArray3.get(i));
data.add(matchedArray4.get(i));
data.add(matchedArray5.get(i));
//put into hash map
map.put(matchedArray.get(i), data);
}
else {
//TODO
System.out.println("DO NOT MATCH :" + last + "-" + matchedArray.get(i));