How to move Cursor in Java Jsoup while loop? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm using Jsoup with while loop but the cursor stuck at a=0. I have tried to move it by added doc.next(); but not working. I want a run from 0-29 in the url. Thank you!
Edited: The url structure is www.example.com/0, www.example.com/1,www.examplecom/2,www.example.com/3,www.example.com/4.....to unlimited "a", but only one number contain the information i need ( range from 0-30). There is no 404 return. The problem is the cursor does not move to the next "a", it's stuck at a=0. There must be someway to make the cursor move because the loop don't move it.
try {
int a = 0;
boolean condition = true;
while (a < 30 && condition) {
doc = Jsoup.connect("http://www.example.com/" + a).get();
Elements info = doc.select("td[valign=top]");
if (null != info) {
System.out.println(info);
condition = false;
System.out.println(a);
} else {
a = a + 1;
}
}
} catch (Exception e) {
}

I'm not sure what exactly you are trying to achieve here, but I will tell you why the loop is stuck at 0.
It is because the url you are trying to access with Jsoup (e.g. www.google.com0) is not a valid url, and it will return a 404 response, which Jsoup will treat as a http exception, and hence the loop is stopped and the control goes to catch block to catch the exception.
If you really want to go from 0 to 29, below code will work for you:
UPDATE:
I now see the problem. Change your code to this:
try {
int a = 0;
boolean condition = true;
while (a < 30 && condition) {
try{
doc = Jsoup.connect("http://www.google.com" + a).get();
} catch(Exception jsoupE){
continue;
}
Elements info = doc.select("td[valign=top]");
if (info.first() != null) {
System.out.println(info);
condition = false;
System.out.println(a);
} else {
a = a + 1;
}
}
} catch (Exception e) {
}

Related

Function executes well without error but not returning expected response

public static ArrayList<String> cleanUpUrls(ArrayList<String> oldList,String url) {
ArrayList<String> cleanedList = new ArrayList<String>();
for (int i =0; i <oldList.size(); i++) {
boolean isAnchorLink = false;
String link = oldList.get(i);
link = link.toLowerCase();
//clean href="" part
link = link.substring(link.indexOf("\"") + 1);
link = link.substring(0, link.indexOf("\""));
//check if anchor link
if (link.charAt(0) == '#') {
isAnchorLink = true;
}
//relative to absolute
if (link.charAt(0) == '/') {
link = url.concat(link);
}
//if no http or https then add
if (link.indexOf("http") == -1 && link.indexOf("https") == -1) {
String http = "http://";
link = http.concat(link);
}
//remove query strings
if (link.indexOf("?") != -1) {
link = link.substring(0,link.indexOf("?"));
}
if (!isAnchorLink){
cleanedList.add(link);
}
} System.out.println("xxxx");
return cleanedList;
}
Here is a function cleanUpUrls which takes an arrayList of strings as parameter and removes all anchor links i.e. href ="" part and converts them to absolute links, if they are relative.
The problem is that when I call it, it executes without compile-time/runtime error but does not return expected response. In fact if I print anything after the function call It does not print anything, even the println("xxx"); does not get display. I am not getting any compilation/run-time errors.
You probably have an exception here:
link = link.substring(0, link.indexOf("\""));
since in your example "x" does not contain '\' the second arg will be -1 and will cause substring to throw and exception (IndexOutOfBoundsException).
Since you catch the exception but print nothing, it will look like it runs with no error so put a print code for displaying the exception:
catch (Exception e) {
System.out.println("Exception caught: " + e);
}

Android/Java Java socket oputput or input stream is null [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I making android applicaton and i have java.lang.NullPointerException with this code. Java server is on the comuter. Thanks for help.
try {
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Socket socket;
socket = new Socket("192.168.0.179", 5450);
os = new PrintStream(socket.getOutputStream());
is = new DataInputStream(socket.getInputStream());
in = is.readLine().trim();
if(in == "hello") {
os.print(edit.getText().toString());
os.flush();
Log.d("LoL", in);
Log.d("LoL", edit.getText().toString());
in = is.readLine().trim();
edit.setText(in);
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (Exception e) {
Log.d("LoL",e.toString());
}
The in == "hello" expression will always return false, because you'll want to compare the contents of the strings in and "hello"; that expression checks that they are the same object, and that will never happen. For any non-primitive type like strings, we should write "hello".equals(in). (you may also write in.equals("hello") but the latter form prevents another possible NullPointerException)
Since that expression will always return false, the if block will never execute. Therefore, the NPE may happen only in two places:
in ok.setOnClickListener: if the ok variable is null, e.g. is not initialized, calling any method on it will lead to NPE;
in in = is.readLine().trim();: if the InputStream is empty (e.g. got no data or EOF from the server) is.readLine() will return null, and calling trim() on a null object will lead to NPE.
BTW, InputStream.readLine() is deprecated, better use BufferedReader instead. That's explained here.

How to append text into text file dynamically [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
[12]
key1=val1
key2=val2
key3=val3
key4=val4
key5=val5
[13]
key1=val1
key2=val2
key3=val3
key4=val4
key5=xyz
[14]
key1=val1
key2=val2
key3=val3
key4=val4
key5=val5
I want to update key5=val5 where [13].
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
if (line.contains("[13]"))
{
while (line.contains("key5")) {
if (line.contains("key5"))
{
line = line.replace("key5", "key5= Val5");
bw.write(line+"\n");
}
}
}
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
This block of code is problematic:
if (line.contains("[13]"))
{
while (line.contains("key5")) {
//etc....
Because there are NO lines which contain both [13] and key5 (they are on separate lines), so the while loop will NEVER be entered.
Instead, when the line [13] is encountered, it's necessary to remember it and store the flag in a boolean, something like the following:
boolean in13 = false;
//... other lines...
if (line.equals("[13]")) {
in13 = true;
} else if (line.startsWith("[")) {
in13 = false; //another block started, clear flag
}
if (in13 && line.startsWith("key5=")) {
// you've found it
}
You really need to step through your logic in your head; in your code:
if (line.contains("[13]")) {
while (line.contains("key5")) {
if (line.contains("key5")) {
line = line.replace("key5", "key5= Val5");
bw.write(line+"\n");
}
}
}
Try writing this out on a piece of paper or something and following it. Look at your while (line.contains("key5")) loop for example. If the line contains "[13]" then it does not contain "key5" and your loop does not even run once. There are many other problems as well (such as the fact that you're only attempting to write one line back out, as another person mentioned in the comments, or that you're not reading any more lines inside your loop, among other issues). For these types of things, work out precisely what you want to do, then write code to match. It looks like you want to do the following:
Search for the line "[13]". Once found...
Search for a line starting with "key5=", but stop when a new section (starting with "[") is encountered. If that is found:
Replace that line with "key5=" + new value.
And for each line you touch that you do not replace, you'd have to write it back out (although a general formula here, barring memory constraints, is to parse/load, then modify, then write).
So you'll want your code to do that.
Also note that some INI file parser implementations (presuming you are treating this as an INI file) ignore whitespace and/or case in the key and section names, so depending on the source of your file, you may want to take that into account.
By the way, perhaps consider using an INI file handling library such as ini4j, where you can load the file and replace keys directly. See What is the easiest way to parse an INI file in Java?.
This part looks wrong:
while (line.contains("key5")) {
if (line.contains("key5"))
I assume that NOT operator is missing in loop condition

error: exception IOException is never thrown in body of corresponding try statement [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I receive an error each time. What am I doing wrong?
My Code:
public static void hashMap(String crnString)
{
try
{
if (mMap.containsKey(crnString))
{
int count = mMap.get(crnString);
count++;
mMap.put(crnString, count);
}
else
{
mMap.put(crnString, 1);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
Assuming mMap is a HashMap, the code inside the try block never throws an IOException. Remove the try-catch block wrapping your code.
public static void hashMap(String crnString){
if (mMap.containsKey(crnString)) {
int count = mMap.get(crnString);
count++;
mMap.put(crnString, count);
} else {
mMap.put(crnString, 1);
}
}
IOException is checked exception. So code in try block is not potential code that can raise IOExcption that's why the compiler shows error. Use specific exception type catch block that can be raised or use unchecked exception catch block. In you try block code, only NPE can be raised.
try
{
if (mMap.containsKey(crnString))
{
int count = mMap.get(crnString);
count++;
mMap.put(crnString, count);
}
else
{
mMap.put(crnString, 1);
}
} catch (NullPointerException e)
{
e.printStackTrace();
} catch(Exception e) {
System.out.println("Unexcepted Exception");
e.printStackTrace();
}
finally
{
}

Why is my ArrayList not being saved to my file?

Why is ArrayList not being written into "MyCalendar.txt"? Even when I use out.write() it still returns false but does not write to the file.
import java.util.*;
import java.io.*;
public static Boolean addAppointment(ArrayList<String> calendar,
String specifiedDay,
String specifiedTime) {
PrintWriter out = new PrintWriter("myCalendar.txt"); //declare calendar file
for (int i = 0; i<calendar.size(); i++) {
String index = calendar.get(i);
if (index.equals(specifiedDay + "" + specifiedTime))
{
out.println(specifiedDay + "" + specifiedTime);
return false;
}
}
return true;
}
Below 2 are important to flush data to file and close the stream
out.flush();
out.close();
Regards,
you forgot to close it:
out.close()
So, a couple of things here.
If you're using Java 7, you should consider using try-with-resources. This will absolutely ensure that your PrintWriter is closed after you're done.
try (PrintWriter out = new PrintWriter("somefile.txt")) {
// code
} catch (FileNotFoundException e) {
System.out.println("Bang!");
}
Next, there are a few cases in which the file could not be written to, either in part or at all:
calendar.size() == 0
index.equals(specifiedDay + "" + specifiedTime)
If the first condition is met, nothing is written and the method happily returns true. Probably not what you expected.
If the second condition is met, you write the first element, and early return. It would probably be a better idea to place that in your loop condition, and return the return value when you're done looping.
int i = 0;
boolean good = true;
while(good && i < calendar.size()) {
// critical actions
String index = calendar.get(i);
if(index.equals(specifiedDay + "" + specifiedTime)) {
good = false;
}
}
// other code
return good;
If that condition is never met, then nothing is ever written to the file.
The default behavior of PrintWriter is not to automatically flush the buffer. See the PrintWriter Documentation for more details.
Alternatively, you might have a data issue:
String index = calendar.get(i);
if (index.equals(specifiedDay + "" + specifiedTime))
If this condition isn't satisfied, you won't print anything out. Have you made sure this condition is true?

Categories

Resources