It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I don't know how to fix these errors:
class or interface expected errors
package doesn't exists
cannot find symbol
illegal start of type
cannot access java.lang
How can I better understand where the problems in my code are occurring? How can I debug these issues?
Here is my code:
import java.io.*;
public class ResourcesTesterApp {
public static void main(String[] args) {
String s1 = readLineWithResources();
String s2 = readLineWithFinally();
}
public static String readLineWithResources() {
System.out.println("Starting readLineWithResources method.");
try (RandomAccessFile in = new RandomAccessFile("products.ran", "r")) {
return in.readLine();
}} catch (IOException e) {
System.out.println(e.toString());
}
}
public static String readLineWithFinally() {
System.out.println("Starting readLineWithFinally method.");
RandomAccessFile in = null;
String s = null;
try {
in = new RandomAccessFile("products.ran", "r");
s = in.readLine();
} catch (IOException e) {
System.out.println(e.toString());
} finally {
if (in != null) {
try {
in.close();
System.out.println("RandomAccessFile closed");
} catch (IOException e) {
System.out.println("RandomAccessFile " + e.getMessage());
}
}
}
return s;
}
You question is how to better understand and debug these errors. Well all I can say is, look at the actual error message output, it will normally include a line number. Now you can look at the specific line of code and see if you can spot what is wrong.
I don't know if the formatting of the code in your question comes from a failed attempt at pasting it into stackoverflow.com or if that is also how you are working with it, but you should format it properly and that will help with spotting problems. For example, when I formatted your code above straight away you can see an additional closing curly brace.
Once you have the actual error messages and line numbers etc. your best bet is to google the error and try to understand what it means. Once you have exhausted that avenue come back here and formulate a specific question showing exactly what the error message is and the code you are running. Avoid grouping many problems into one question like you have done here.
this usually means you are writing code outside of a method.
this simply means you referenced a package that the java compiler cannot find.
this means you wrote a nonexistant variable.
this usually means you did not complete a statement, and you started writing the next one.
I dont know about this one, maybe be more specific?
I strongly suggest you take a look at the java tutorials, and follow their examples.
you can find them at http://docs.oracle.com/javase/tutorial/
Related
This question already has answers here:
Does log.debug decrease performance
(5 answers)
Closed 2 years ago.
I don't really know what is the best way to log information from an application. Most of what I've seen is programmed like this:
while(true) {
//code
if(debug == true) {
log(info);
}
end
And I've thought of using two separate loops like this:
if(debug == true) {
while(true) {
//code
log(info);
}
else {
while(true) {
//code
}
}
But that has the problem of being twice the work to change later on. The last solution, which I think is probably the best, is to use something like a lambda expression and pass an empty implementation to use without debug:
public void loop(Debug debug) {
while(true) {
//code
debug.log(info)
}
}
public static void main(String[] args) {
loop(d -> {
//print to file, command line, etc. OR do nothing
});
}
Any clarity on issues or unintended consequences would be greatly appreciated.
Thanks in advance!
Don't try to invent a bicycle. Use existing logging frameworks and follow their guidelines.
Whatever you will think of - you will need to get over same problems that are already solved there.
For example https://logging.apache.org/log4j/2.x
Or http://www.slf4j.org/
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 8 years ago.
Improve this question
I have a small program for inserting data into a database with http.
I made a function to do this but when i call the function in my main file it seems that it does not work. I tried debugging it but when I set a breakpoint on the line it does not show that the function is used. Can someone help me?
public class School_Planner {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
HTTP_Conncetion.Connect();
}
}
.
public class HTTP_Conncetion {
public static void Connect(){
try {
// open a connection to the site
URL url = new URL("http://localhost:8080/HTTP_Connection/index.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print("firstKey=firstValue");
//ps.print("&secondKey=secondValue");
// we have to get the input stream in order to actually send the request
con.getInputStream();
// close the print stream
ps.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
EDIT
After the command of Jon Skeet, i think i have to be a little more specific. The problem i think is that the function does not work or that it skips over the function.
The posted code is just fine it calls the URL
http://localhost:8080/HTTP_Connection/index.php
with the parameter firstKey and its value firstValue
Unless you forgot to do the imports which would result in a compile error to begin with.
I guess your error is on the server side. Please double check the server.
For sure your question is very unspecific - no exception, no exact description of what "function" you think is not called. Not what you expect to happen and what you miss of happening. Please adjust your question in a way that there can be a more concrete answer to your question.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am building a Tetris game. I am currently debugging the game and in order to do this I need to see the values of all the variables and the variables variables and so on. With reflection I can get all a classes fields by doing this:
try
{
for(Field field : this.getClass().getDeclaredFields())
{
field.setAccessible(true);
System.out.println(field.get(this));
}
}
catch(Exception e)
{
}
What I don't know how to get all the field values of each field object.
There are two things you need to do:
Create a set of reachable objects. You don't want to recursively traverse your object graph forever.
Print values for every object.
For the first one, you need to use something like IdentityHashMap:
import java.util.IdentityHashMap;
class MyObjectCache
{
final IdentityHashSet objects = new IdentityHashSet ();
...
}
To traverse objects you can use recursive function (it is simpler, but has a stack restriction):
class MyObjectCache
{
....
void registerObject(Object o)
{
if (objects.contains(o))
{
return;
}
objects.add(o);
for(Field field : o.getClass().getDeclaredFields())
{
field.setAccessible(true);
registerObject(field.get(o));
}
}
...
}
And then you can start printing collected objects...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a text file named "hours.txt" that has lines of integers that I would like to read and copy them into an array.
The integers are the number of hours worked by 8 employees in a week. So I created a two-dimensional array with the rows being the employees and the columns being the days of the week.
public static void read()
{
Scanner read = new Scanner(new File("hours.txt"));
int[][] hours = new int[8][7];
for(int r=0; r<hours.length; r++)
{
for(int c=0; c<hours[0].length; c++)
{
while(read.hasNextInt())
{
hours[r][c]= read.nextInt();
}
}
}
}
When I try to compile this, I get the following error:
EmployeeHours.java:16: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Why is that?
Because FileNotFoundException is a checked exception. You must either catch and handle it, or throws it in the method declaration. And don't just swallow the exception; that's almost never the right way to "handle" them.
Lots more reading on exactly this topic can be found in the official Java Tutorial.
try {
//block of code
} catch (FileNotFoundException fnfe) {
}
or
public static void read() throws FileNotFoundException
The exception FileNotFoundException must be declared as part of your method signature, to tell the Java compiler that your method can throw that particular exception. You must change your method definition to:
public static void read() throws FileNotFoundException
{
... code here ...
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have this in the File.java:
public static void main(String args[]) throws Exception_Exception {
URL wsdlURL = CallSService.WSDL_LOCATION;
if (args.length > 0) {
File wsdlFile = new File(args[0]);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(args[0]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
and I want to transfer this to a JSP file, so I do like that:
List<String> Search(String keyS){
if(keyS!=null){
QName SERVICE_NAME = new QName("http://ts.search.com/", "callSService");
String arg=??????????????;
URL wsdlURL = CallSService.WSDL_LOCATION;
File wsdlFile = new File(arg);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(arg);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
I want to replace the args[0] with arg. What does (String args[]) mean? and how can I replace it ?
String args[] is an array of Strings passed in from the command line.
So, if you started your app with java MyApp arg1 arg2
Then args[] would contain => ["arg1", "arg2"]
Java will automatically split up arguments separated by spaces, which is how it knows how many arguments you passed in.
Don't do this in a JSP :(
Don't put your functionality in a main, it's confusing: public static void main is conventionally a program's entry point, not a general purpose method. You may use it as one, but IMO it is misleading.
Instead, create an instance method you can call with the argument you want. It could be a static method, but this builds in some inflexibility making things more difficult to test. Embeddeding the code in a JSP also increases testing difficulty.
You'll need to use ServletContext.getRealPath() to get a file relative to the web app, unless you're providing an absolute path. If the file is "embedded" in the app (on the classpath) you'll want to use one of the resourceAsStream variants.