I'm trying to read the title from a webpage and save it as a String. However, since Strings are immutable in java, I can't just set it to null and change it when I need to. Therefore, I'm getting an error on the next to last line that strTitle may not have been initialized. This seems like it should be easy to deal with, but I can't figure it out. Thanks in advance.
URL allRecipe = new URL(inputLine); //user defined url
BufferedReader urlIn = new BufferedReader(
new InputStreamReader(allRecipe.openStream()));
String inputFromWeb;
//loops through webpage and finds title
while((inputFromWeb = urlIn.readLine()) != null){
//getting title
if(inputFromWeb.contains("<title>")){
strTitle = urlIn.readLine();
}
}//end while
urlIn.close();
//print out title
System.out.println("Title:");
System.out.println(strTitle); //this line returns the error
System.out.println("\n");
since strings are immutable in java and I can't just set it to null
and change it when I need to.
Sure you can. If you are initializing a String reference to null and then assigning to it a different String, you are not changing any String, you are just changing the String reference.
However, as is I'm getting an error on the next to last line that
strTitle may not have been initialized.
String strTitle = null;
will solve your problem.
Related
I am trying to remove every punctuation from my string: So far, I've done the following :
String line = "there's, isn't";
line.replaceAll("\\p{Punct}", "")
yet, this can't change "there's" into "theres" or "isn't" into "isnt".
I thought \p{Punct} includes every punctuation, including " ' " (as it's shown in api) yet this doesn't work. Can someone pls help?
Thanks in advance.
PS: expected outcome is: theres isnt
Strings are immutable in Java. String methods don't change the string in place, but instead return a modified copy of the string, so you need to assign the result back to the variable:
String line = "there's, isn't";
line = line.replaceAll("\\p{Punct}", "");
System.out.println(line); // theres isnt
As the previous answer said, the strings are immutable and once created you can't really change it. So once you code like String line = "there's, isn't";the string object "there's, isn't" will be created and line variable will be assigned to it. Java doesn't have the concept of pointers, but you can think of it as line variable pointing to the given string "there's, isn't". Now your next line line.replaceAll("\\p{Punct}", "") returns a newly created string object. You can assign it to another variable, say line_cleared=line.replaceAll("\\p{Punct}", "" and print that out: So here is the fully updated code:
String line = "there's, isn't";
line_cleared= line.replaceAll("\\p{Punct}", "");
System.out.println(line_cleared);
I am having two problems here:
The following block of codes has got me confused. Primarily, I do not know what exactly the code is doing from the basics; I just copied it from a tutorial, and it seems to do what i want it to do. If anyone can explain in bits what it does, it will be really helpful.
The second problem is that I do not know why it throws an ArrayIndexOutOfBounds error, maybe because I do not understand it or otherwise. I really need clarification.
try {
Document searchLink = Jsoup.connect("https://www.google.com.ng/search?dcr=0&source=hp&ei=5-cIWuZ30cCwB7aUhrAN&q=" + URLEncoder.encode(searchValue, encoding))
.userAgent("Mozilla/5.0").get();
String websiteLink = searchLink.getElementsByTag("cite").get(0).text();
//we are setting the value for the action "titles" in the wikipedia API with our own article title
//we use the string method replaceAll() to remove the title of the article from the wikipedia URL that we generated from google
//
String wikiAPItoSearch = "https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles="
+ URLEncoder.encode(websiteLink.replaceAll("https://en.wikipedia.org/wiki/", ""),encoding);
System.out.println(wikiAPItoSearch);
//extraction of textfiles
//from this point till down i cant really grab what is happening
HttpURLConnection httpconn = (HttpURLConnection) new URL(wikiAPItoSearch).openConnection();
httpconn.addRequestProperty("userAgent", "Mozilla/5.0");
BufferedReader bf = new BufferedReader(new InputStreamReader(httpconn.getInputStream()));
//read line by line
String response = bf.lines().collect(Collectors.joining());
bf.close();
///it returns ArrayIndexOutOfBounds here
String result = response.split("\"extract\":\"")[1];
System.out.println(result);
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
I don't think anyone will take the time to explain the code for you. A good opportunity for you to do some debugging.
ArrayIndexOutOfBounds comes from response.split("\"extract\":\"")[1]. There is no guarantee that the String response can be split into at least 2 parts.
Add a check to avoid the error. Instead of...
String result = response.split("\"extract\":\"")[1];
use...
String[] parts = response.split("\"extract\":\"");
String result;
if (parts.length >= 2) {
result = parts[1];
} else {
result = "Error..." + response; // a simple fallback
}
This is how split works:
String input = "one,two,three";
String[] parts = input.split(",");
System.out.println(parts[0]); // prints 'one'
System.out.println(parst[2]); // prints 'three'
So in your case, [1] means the second item in the parts array. "\"extract\":\"" has to appear at least once in the response, otherwise there will be only one item in the parts array, and you will get an error when you try to reach the second item (since it doesn't exist). It all gets extra tricky since .split accepts a regexp string and "\"extract\":\"" contains regexp reserved characters.
OPPS... i realized it was the API that i was using that caused the error, the API i got from wikimedia does not use /extract /as a delimetre , so i checked other stack overflow articles for a more cleaner API especially a one that uses /extract/ as a delimetre for the API response.
this is the new API i got :
https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=
this was the former one that causes the error:
https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=
i think the error was caused by my inability to understand the process in-dept.. thanks for the responses.
I have a script which visits links from a text file. I am trying to delete the string if value returned is null
Example:
1. some link (returned value 'hi')
2. some link (returned null value) //DELETE STRING FROM FILE BECAUSE NULL VALUE RETURNED
3. some link (returned value 'hello')
Some code:
while ((input = in.readLine()) != null) {
System.out.println(input);
if ((input = in.readLine())=="0"){
System.out.println("1 String deleted from file because null value returned ");
}
I'm aware that I'm checking for String "0" instead of an integer 0 because the server stores it as a string i suppose.
I think, rather than trying to remove to the file mid-read (and I don't even really know how you'd do that, and if you could it'd be a horrible idea) you might have an easier time of this by just reading the entire file in and storing each value in an index of an ArrayList<string>:
ArrayList<string> lines = new ArrayList<string>();
while ((input = in.readLine()) != null) {
lines.add(input);
}
Then write the file again after you've finished reading it, skipping any index of lines that's equal to "0":
for (String line : lines)
{
// skip "0"
if (line.equals("0")) {
continue;
}
// write to file if not
writer.write(line);
writer.newLine();
}
Note that == compares reference equality in Java, and .equals compares value equality, so for almost all cases you want to use .equals.
Granted, if as your comment states above, you have another file constantly writing to this one, you're better off looking for an entirely new idea. For that matter, if you've got a script writing these, why not change the script so that it just doesn't write lines for null values in the first place? Unless you have literally no way at all of changing the script, spinning another one up to constantly rewrite parts of its work (on the same constantly-accessed file!) is going to be a. ineffective and b. extremely problematic.
I have TextView with text that changed dynamically.
i want tokenizing this text with delimiter space " " and send to another textview
this is my code
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId()==R.id.button5){
Intent i = new Intent(this, Tokenizing.class);
String test = ((TextView)findViewById(R.id.textView6)).getText().toString();
String result = null;
StringTokenizer st2 = new StringTokenizer(test," ");
while (st2.hasMoreTokens()) {
String st3 = st2.nextToken();
System.out.println(st3);
result = st3;
}
i.putExtra("result", result);
startActivity(i);
Log.i("Test Klik Next", result);
but i have just last word in the textview.
text before tokenizing:
Examples of paradoxes can be humorous and confusing
text after tokenizing:
confusing
where is the part of my coding is wrong?
You are overwriting the result every time you read a new token
result = st3;
So it's always equal to the last value. Change the type of result from String to StringBuilder and just build it as you go
result.append(st3 + " "); //re-adding the space as the StringTokenizer will remove it
Then after the StringTokenizer loop just get the built String using result.toString()
Why not result += st3?
Some other answers suggest you do this. The reason not to do this is that in Java, String is immutable. This means they can't be changed so any time you append two String objects, a new String object is created.
So every step through the loop you are creating a new String object which is inefficient and unnecessary. StringBuilder is not immutable and Strings can be appended to it without the overhead of creating new objects every time.
StringTokenizer
Worth noting -as #RGraham said in the comments- that this class is deprecated. This means it's no longer in common use, use of it is discouraged and it could be removed at some point.
More information here.
Tokens - in or out
As other answers assumed the opposite of me and after discussion on one of said answers and on meta, I feel I need to clarify this. I
'm not sure if your intention was to get rid of the tokens (in this case spaces " ") and end up with
Examplesofparadoxescanbehumorousandconfusing
or to replace them when outputting the final String and get out what you put in. So I assumed you wanted to preserve the original meaning and replace them. Otherwise a quicker way to get the result above would be to simply skip all the tokenizing and do
test.replaceAll(" ","");
while (st2.hasMoreTokens()) {
String st3 = st2.nextToken();
System.out.println(st3);
result = st3; // Everytime you are reassigning result to some other String
}
Replace
result = st3; by (initialize String result=" ";)
result+=st3+" "
and then replace
i.putExtra("result", result); with i.putExtra("result", result.trim());
Try this , it will show perfect result.
You can also do this result.append(st3+" "); and then i.putExtra("result", result.trim());
I've ran into a bit of a confusion.
I know that String objects are immutable. This means that if I call a method from the String class, like replace() then the original contents of the String are not altered. Instead, a new String is returned based on the original. However the same variable can be assigned new values.
Based on this theory, I always write a = a.trim() where a is a String. Everything was fine until my teacher told me that simply a.trim() can also be used. This messed up my theory.
I tested my theory along with my teacher's. I used the following code:
String a = " example ";
System.out.println(a);
a.trim(); //my teacher's code.
System.out.println(a);
a = " example ";
a = a.trim(); //my code.
System.out.println(a);
I got the following output:
example
example
example
When I pointed it out to my teacher, she said,
it's because I'm using a newer version of Java (jdk1.7) and a.trim()
works in the previous versions of Java.
Please tell me who has the correct theory, because I've absolutely no idea!
String is immutable in java. And trim() returns a new string so you have to get it back by assigning it.
String a = " example ";
System.out.println(a);
a.trim(); // String trimmed.
System.out.println(a);// still old string as it is declared.
a = " example ";
a = a.trim(); //got the returned string, now a is new String returned ny trim()
System.out.println(a);// new string
Edit:
she said that it's because I'm using a newer version of java (jdk1.7) and a.trim() works in the previous versions of java.
Please find a new java teacher. That's completely a false statement with no evidence.
Simply using "a.trim()" might trim it in memory (or a smart compiler will toss the expression entirely), but the result isn't stored unless you precede with assigning it to a variable like your "a=a.trim();"
String are immutable and any change to it will create a new string. You need to use the assignment in case you want to update the reference with the string returned from trim method. So this should be used:
a = a.trim()
You have to store string value in same or different variable if you want some operation (e.g trim)on string.
String a = " example ";
System.out.println(a);
a.trim(); //output new String is not stored in any variable
System.out.println(a); //This is not trimmed
a = " example ";
a = a.trim(); //output new String is stored in a variable
System.out.println(a); //As trimmed value stored in same a variable it will print "example"