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 6 years ago.
Improve this question
I have the following class:
class A {
List<A> as;
}
I need to find max depth. For example, I can have this:
A firstA = new A();
A secondA = new A();
A thirdA = new A();
firstA.addA(secondA);
firstA.addA(thirdA);
secondA.addA(new A());
secondA.addA(new A());
I need to return 3.
I tried to do recursive method,
Using Java 8 streams:
class A {
List<A> as;
public int getDepth() {
return 1 + as.stream().mapToInt(A::getDepth).max().orElse(0);
}
}
If you're not familiar with streams, this can be interpreted as 'add 1 to maximum depth of all children or 0 if there are no children'.
If you can't change A you can still use this by passing A into the method:
public class MyClass {
public static int getDepth(A a) {
return 1 + a.as.stream().mapToInt(MyClass::getDepth).max().orElse(0);
}
}
Recursive depth-computing:
public static int computeDepth(A a)
{
int maxDepth = 0;
for(A innerA : a.getAs())
{
int depth = computeDepth(innerA);
if(depth > maxDepth)
maxDepth = depth;
}
return maxDepth + 1;
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
there,
I'm a beginner in Java. I got a problem. I don't know how to access to a result to work with it. Like so:
Main file:
public class App
{
public static void main(String[] args)
{
test t = new test();
t.add(10, 20);
int result = test.sum; // accessing variable
System.out.println("sum = "+result);
}
}
test.java:
class test
{
static int sum;
public static int multi;
void add(int a, int b)
{
sum = a+b;
}
void multi()
{
//I'd like to work with the result above "sum"
}
}
I tried to make a getter and setter but it didn't work. I think I made some mistakes.
Can you help me please. Thank's in advance.
You shouldn't have any fields in test, much less static ones. The usual way to structure this API would be
class test
{
int sum(int a, int b)
{
return a+b;
}
int multi(int a, int b)
{
return a * b;
}
}
If you need to use sum in multi, then you should call it instead of getting the stored result.
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 1 year ago.
Improve this question
Using arraylist and trying to get the last element, i am getting some runtime error.
import java.util.ArrayList;
public class MyProgram{
private ArrayList<String> list = new ArrayList<String>();
public void printLastThing(){
int lastIndex = list.size() - 1;
String thing = list.get(lastIndex);
System.out.println(thing);
}
public static void main(String[] args){
MyProgram example = new MyProgram();
example.printLastThing();
}
}
There are no elements added to the list and so it is empty. YOu are trying to fetch the element at -1 which will raise java.lang.IndexOutOfBoundsException.
In this case you should keep a check for going out of bounds.
I have added a method to check the lastindex. It will return -1 if list is emtpy and you can display that List if empty once you get -1.
import java.util.ArrayList;
public class MyProgram{
private ArrayList<String> list = new ArrayList<String>();
public MyProgram() {
list.add("a");
list.add("z");
}
public void printLastThing(){
int lastIndex = getLastIndex();
if(lastIndex >= 0)
System.out.println(list.get(lastIndex));
else
System.out.println("List is empty");
}
private int getLastIndex() {
if(list.size()==0) {
return -1;
}
return list.size() - 1;
}
public static void main(String[] args){
MyProgram example = new MyProgram();
example.printLastThing();
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
Currently i am getting data from my list but i get the data randomly, if anyone can help me to sort data on the basis of dayInNumber i have attached the picture of my database. I want to sort the data like 1 2 3 4 .. 14 enter image description here
Thanks
Suppose you have Client class defined as
class Client {
private long dayInNumber;
private String clientName;
private String day;
//setters and getters ommitted for brevity and clarity
}
Then you have a list of clients
List<Client> clients = new ArrayList<>();
To sort that dayInNumber you can either sort that in SQL (order by clause) assuming the data is coming from SQLite.
Or you can create a custom Comparator<T> of Client objects to do the sorting in code as below
import java.util.Comparator;
public class ClientDayInNumberComparator implements Comparator<Client> {
#Override
public int compare(Client c1, Client c2) {
if(c1.getDayInNumber() > c2.getDayInNumber()) return 1;
else if(c1.getDayInNumber() < c2.getDayInNumber()) return -1;
else
return 0;
}
}
This will sort clients by dayInNumber in ascending order (1, 2, 3,...N). Then use it as follows
List<Client> clients = new ArrayList<>();
Collections.sort(clients, new ClientDayInNumberComparator());
Collections is packed in java.utils package which you'll need to import
for sorting lists we can use sort(your_list) method of Collections class. This will sort the list as per the natural ordering i.e. ascending order. Since you want it sorted on the basis of a particular feature you should implement Comparator interface with type safety same as of your list. You will have to implement compareTo method. Refer to the below code for FYR:- `
public class Temp implements Comparable<Temp> {
Temp(int a, int b) {
this.a = a;
this.b = b;
}
int a;
int b;
public static void main(String[] args) {
Temp t1 = new Temp(11,2);
Temp t2 = new Temp(9,5);
Temp t3 = new Temp(1,7);
Temp t4 = new Temp(10,9);
Temp t5 = new Temp(14,11);
ArrayList<Temp> al = new ArrayList<Temp>();
al.add(t1);
al.add(t2);
al.add(t3);
al.add(t4);
al.add(t5);
Collections.sort(al);
for(Temp i:al) {
System.out.println(i.a+"," +i.b);
}
}
#Override
public int compareTo(Temp o) {
if(a==o.a) {
return 0;
}
else if(a>o.a) {
return 1;
}
else {
return -1;
}
}
}`
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am working on a project that requires to count the number of getters and setters in a compiled java code. I am new to this and dont know where and how to start.
I have installed eclipse and added the Bytecode plugin to see the bytecode of the java code.
Any thoughts on what i need to do next?
You can use java.lang.reflect.* package to get all the class info such as variable, methods, constructors and inner classes.
Example:
public int noOfGettersOf(Class clazz) {
int noOfGetters = 0;
Method[] methods = clazz.getDeclaredMethods()
for(Method method : methods) {
String methodName = method.getName();
if(methodName.startsWith("get") || methodName.startsWith("is")) {
noOfGetters++;
}
}
return noOfGetters;
}
Follow the same approach for setters, one thing you need to consider is boolean getters they usually starts with is instead of get.
You can use Class.getDeclaredMethods(), with something like this
public static int countGets(Class<?> cls) {
int c = 0;
for (java.lang.reflect.Method m : cls.getMethods()) {
if (m.getName().startsWith("get")) {
c++;
}
}
return c;
}
public static int countSets(Class<?> cls) {
int c = 0;
for (java.lang.reflect.Method m : cls.getMethods()) {
if (m.getName().startsWith("set")) {
c++;
}
}
return c;
}
Refer the Apache byte code manipulation library BCEL.
The Byte Code Engineering Library is intended to give users a convenient way to analyze, create, and manipulate (binary) Java class files (those ending with .class).
After that you can use reflection to get the count like this :
public static int getGetterMethodCount(Class<?> cls) {
int n = 0;
for (Method m : cls.getMethods()) {
// To identify the boolean setter "is" is used
if (m.getName().startsWith("get") || m.getName().startsWith("is")) {
n++;
}
}
return n;
}
public static int getSetterMethodCount(Class<?> cls) {
int n = 0;
for (Method m : cls.getMethods()) {
if (m.getName().startsWith("set")) {
n++;
}
}
return n;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
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.
Improve this question
I am trying to create a memoized fibonacci program to start learning Dynamic Programming. When I run this program however, it always returns 0.
private static Map<Integer, Long> stored = new HashMap<>();
static
{
stored.put(0, (long) 0);
stored.put(1, (long) 0);
}
public static long memo(int n)
{
if (n==0)
{
return stored.get(0);
}
else if (n==1)
{
return stored.get(1);
}
else if (stored.containsKey(n))
{
return stored.get(n);
}
else
{
long f = ( memo(n-1) + memo(n-2) );
stored.put(n, f);
return f;
}
}
You are only inserting 0, and adding up 0 will always be 0.
Just replace the second static insertion with this:
stored.put(1, (long) 1);
let me fix this for you
private static Map<Integer, Long> stored = new HashMap<>();
static
{
stored.put(0, 0);
stored.put(1, 1);
}
public static long memo(int n)
{
if (stored.containsKey(n))
{
return stored.get(n);
} else
{
long f = ( memo(n-1) + memo(n-2) );
stored.put(n, f);
return f;
}
}