Get all field values java program [closed] - java

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...

Related

Why do I get this error when trying to read integers from a file and copy them into an array? [closed]

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 ...
}

MongoDB Aggregate query in Java [closed]

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 new to Java and like to know how to build mongoDB query in java.
db.coll.aggregate(
{ $match : {
loc: {
"$ref" : "location",
"$id" : ObjectId("4fe69610e7e9fa378c3c802e")
}
}},
{ $unwind : "$ActivityList" },
{ $match : {
'ActivityList.user': {
"$ref" : "userProfile",
"$id" : ObjectId("4fdeafe1de26fd298262bb82")
}
}},
{ $group : {
_id : "$ActivityList.type",
latest: { $max: '$ActivityList.timestamp' }
}}
);
Thanks for your help.
There is limitation in aggregate command, pipeline can't operate on values of Binary, Symbol, MinKey, MaxKey, DBRef, Code, CodeWScope. Check Aggregation Framework for more information.

Breaking out of a method in a loop [closed]

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 a method with a break statement in its if statement. The method is in a while loop. Will it break out of the while loop if I use break within the method's if statement or do I have to use nested loops?
public int x=0;public int y=0;
public boolean endCondition = true;
public void someMethod()
{
if(x!=y) {//do something}
else break;
}
while(endCondition==true)
{
this.someMethod();
}
System.out.println("Bloke");
You can not use break without a loop or a switch . You need to use return. But it seems a endless method calling which would cause StackOverflow exception.
To break out from a function you have to use return. break will break you out from only the inner loop inside which you are calling it.
You probably need to return a boolean value from the method, which you can then use to decide whether to break the loop.
It's not important in this simple example, but it's usually a good idea to label your loops when using break, so it's clear what you are breaking out of, especially when using nested loops. See the label FOO below.
public boolean someMethod()
{
if(x!=y)
{
//do something
return false;
}
return true; // break
}
FOO:while(true)
{
if(someMethod()) break FOO;
}

Basic debugging with Java [closed]

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/

What does (String args []) mean? [closed]

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.

Categories

Resources