Lets say I have three classes:
Class A:
public class A {
private String s;
public A() {
s = "blah";
}
public void print() {
System.out.println(s);
}
}
Class B:
public class B{
private A a[];
public B(){
a = new A[100];
for (int i=0; i<100;i++) {
a[i] = new A();
}
}
public void print() {
for (int i=0; i<100; i++) {
a.print(); //SHOULD BE a[i].print();
}
}
}
Class Main:
public class Main {
public static void main(String args[]) {
B b = new B();
b.print();
}
}
Why do I get an outputpattern like B##, where # is a number. I think it has something to do with indirect adressing but im not quite sure. Why doesn't it print out 100 s?
You are printing the array rather than the object in the array. As a result, it is printing the address of the object (the number) and the object it is a member of.
I suspect you wanted to call each of the prints, you should, in B.print(). You are also missing an increment for i, meaning it will loop indefinitely.
for(int i = 0; i < 100; ++i)
{
a[i].print();
}
Related
This question already has answers here:
Is it possible to create n number of objects in java using a for loop? [duplicate]
(2 answers)
Closed 4 years ago.
I'm trying to create some classes but the number of them is determined by the user.
The class I want to make:
public class test {
public class test() {
int num;
//etc.
}
}
Main class:
public class main {
public static void main(String[] args) {
test class1 = new test();
test class2 = new test();
test class3 = new test();
//etc.
}
}
The problem is that currently the maximum amount of classes the user can create depends on my patience.
Is there a way to make it easier/shorter?
Ps: The project I want to use this for doesn't work with lists!
You can utilize an array (Test[]) or a list (List<Test>) or any other data structure you like to hold your Test objects.
public class Test {
private int num;
public Test(int num) {
this.num = num;
}
#Override
public String toString() {
return String.format("Test %d", this.num); // Override the toString() method
}
}
public class Main {
public static void main(String[] args) {
List<Test> tests = new ArrayList<>();
int n = 5; // Create five tests
for (int i = 0; i < n; n++) {
tests.add(new Test(i)); // Instantiate and add tests to list
}
for (Test test : tests) {
System.out.println(test.toString()); // Print the contents i.e. `num`
}
}
}
You can use a for loop and save your objects in a list:
public static void main(String[] args) {
int n = 10; //a number given
List<Test> myObjs = new ArrayList<Test>();
for(int i = 0, i < n, i ++) {
Test t = new Test();
myObjs.add(t);
}
}
just use an array
public class MyClass
{
public static void main(String[] args){
MyClass myClass[]=null;
for(int i = 0; i < 5; i++){
myClass[i] =new MyClass();
}
}
}
I am new with java and I need to save the content of a stack of objects into an array which will have an array attribute and also the array attribute has an array attribute I know it kind complicated but I need to do that because it's looks like a table. Anyway, this is my code
//First class
public static class classA //inner
{ public char sy;
public ArrayList <Integer> arrystateA;
public classA()
{ sy='0';
arrystateA= new ArrayList <Integer>();} }
//The second class
public static class ArrayofclassA// meddile
{ int num;
public ArrayList <classA> arrystateB;
public ArrayofclassA()
{ arrystateB=new ArrayList < classA>();
num=-1;}
public void creatrans(classA z)
{ arrystateB.add(z);
} }
and this the main code
classA temp2=new classA();
ArrayofclassA temp3 = new ArrayofclassA();
ArrayList<ArrayofclassA> NFAtranstable=new ArrayList<ArrayofclassA>();
while(!reslt.empty()){
temp=reslt.pop();
for (int i=0;i<NFAtranstable.size();i++)
{temp3=NFAtranstable.get(i);
if (temp3.num==temp.s_to)
{
if(temp3.arrystateB.get(i).sy==temp.t_sym)
{
temp3.arrystateB.get(i).arrystateA.add(temp.s_to);
match=true;
}else
{temp2.sy=temp.t_sym;temp2.arrystateA.add(temp.s_to);
temp3.creatrans(temp2);
match=true;
}
}
}
if(!match)
{
temp2.sy=temp.t_sym;
temp2.arrystateA.add(temp.s_to);
temp3.num=temp.s_from;
temp3.arrystateB.add(temp2);
NFAtranstable.add(temp3);
}
match=false;
}
for(int i=0;i<NFAtranstable.size();i++)
{
System.out.print(NFAtranstable.get(i).num+" ");
for(int j=0;j<NFAtranstable.get(i).arrystateB.size();j++)
{
System.out.println(NFAtranstable.get(i).arrystateB.get(j).sy+" ");
for(int k=0;k<NFAtranstable.get(i).arrystateB.get(j).arrystateA.size();k++)
{
System.out.print(NFAtranstable.get(i).arrystateB.get(j).arrystateA.get(k));
}
}
}
}
the problem that when I print the content of the array 'NFAtranstable' it's gives me duplicate results like it just save the same valus, it's been about 8 hours and I couldn't find the problem =(
class A {
static int i;
{
System.out.println("A init block"+ ++i);
}
}
class B extends A {
static int j;
{
System.out.println("B init block"+ ++j);
}
}
class C extends B {
static int k;
{
System.out.println("C init block"+ ++k);
}
public static void main(String abc[])
{
C c =new C();
}
}
In the code above, we can easily count the number of objects created for each class.
But if i want to check the number of object created explicitly , i mean if I create C's object using new C(), or B's object using new B(), then it should give the count accordingly
Take for example,
C c2=new C();
B b2=new B();
So it should give the output of B's count as 1 and not 2.
public class Foo {
private static int fooCount = 0;
public Foo() {
if (this.getClass() == Foo.class) {
fooCount++;
}
}
public static int getFooCount() {
return fooCount;
}
}
public class Test {
static int count;
Test() {
count++;
}
public static void main(String[] args) {
Test t = new Test();
Test t1 = new Test();
NewTest nt = new NewTest();
System.out.println("Test Count : " + Test.count);
System.out.println("NewTest Count : " + NewTest.count);
}
}
class NewTest extends Test
{ static int count;
NewTest()
{
Test.count--;
NewTest.count++;
}
}
OP :
Test Count : 2
NewTest Count : 1
I have a static variable and updating it's value in class. But when i access this variable from another class , it shows unupdated value.
CLASS A
public static int postID = 1;
public static String Creator()
{
String message = "POST id="+postID;
return message;
}
void updatePostID()
{
postID++; //this function is being called each 10 seconds
}
#Override
public void start() {
handler.post(show);
}
Handler handler = new Handler();
private final Runnable show = new Runnable(){
public void run(){
...
updatePostID();
handler.postDelayed(this, 10000);
}
};
CLASS B
String message = A.Creator(); //this always prints postID as 1 all time
I need a global variable that i can access from each class and update its value. Waiting for your help (I am using this with a Android Service)
this is a tested code .
public class A {
public static int id = 0;
public static int increment(){
return A.id++;
}
}
public class B {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(A.increment());
}
}
}
class A
{
static int id=0;
//I am updating id in my function ,
{
id++;
}
}
public class StartingPoint {
public static void main(String... args){
A a = new A();
A b = new A();
System.out.println(A.id);
System.out.println(a.id);
}
}
You need to call work to execute id++;
class B {
public static void main(String... args){
A a = new A();
a.work(); // You need to call it to apply add operation
System.out.println(A.id); // Prints 1
}
}
And this is a sample class A:
class A {
static int id = 0;
public void work(){
id++;
}
}
Save class A in a file named A.java and class B in a file named B.java.
Then compile B. Since B creates an instance of class A, A will be compiled and you don't need to compile A separately-
javac B.java
After compilation, to execute/run-
java B
Sajal Dutta's answer explains it perfectly, but if you want to keep it ALL static (i.e. not create any objects of class A, you could modify the code slightly to this:
class A {
static int id = 0;
public static void work(){
id++;
}
}
Then:
class B {
public static void main(String[] args){
System.out.println(A.id);
A.work();
System.out.println(A.id);
}
}
This would produce:
0
1
Edit (with regard to your updated question)
Where are you specifying the update of the static int? From the code you've provided all you will do is print out the same int over and over as the method containing the increment process is never called.
Edit 2:
Try this:
Change:
handler.post(show);
to:
handler.postDelayed(show, 10000);
Just a simple class calls a class that prints an array. I get a syntax error in Eclipse. I also get an error that I don't have a method called Kremalation.
public class AytiMain {
public static void main(String[] args) {
AytiMain.Kremalation();
}
}
public class Kremalation {
String[] ena = { "PEINAW", "PEINOUSA", "PETHAINW" };
int i; // <= syntax error on token ";", { expected after this token
for (i = 0; i <= ena.lenght; i++)
System.out.println(ena[i]);
}
}
You have code (which is not declaring a variable and/or initializing it) ouside a method, which is:
for (i=0; i<=ena.lenght; i++)
System.out.println(ena[i]);
In Java, code MUST reside inside a method. You can't call a class, you have to call a method that is declared inside a class.
WRONG:
class ClassName {
for (...)
}
CORRECT:
class ClassName {
static void method() {
for (...)
}
public static void main(String[] args) {
ClassName.method();
}
}
You can not define method as class.
It should be
public static void kremalation()
{
String ena[]={"PEINAW","PEINOUSA","PETHAINW"};
int i;
for (i=0; i<=ena.lenght; i++)
System.out.println(ena[i]);
}
public class AytiMain {
public static void main(String[] args) {
AytiMain.Kremalation();
}
public static void Kremalation() {// change here.
String ena[]={"PEINAW","PEINOUSA","PETHAINW"};
int i;
for (i=0; i<=ena.lenght; i++)
System.out.println(ena[i]);
}
}
Two possible answers.
1) Remove public from second one if you would like to define it as class.
2) Move Kremalation inside closing brace and replace class with void and make it as static method.
You cannot have executable code directly inside a class.. Add a method and use instance of that class to call that method..
public class Kremalation {
public void method() {
String ena[]={"PEINAW","PEINOUSA","PETHAINW"};
int i;
for (i=0; i<=ena.lenght; i++)
System.out.println(ena[i]);
}
}
Now, in your main method, write: -
public static void main(String[] args) {
new Kremalation().method();
}
Two approaches to solve this problem.....
1st there are 2 classes in the same file :
public class AytiMain {
public static void main(String[] args) {
new Kremalation().doIt();
}
}
class Kremalation {
public void doIt(){ // In Java Codes should be in blocks
// Like methods or instance initializer blocks
String ena[]={"PEINAW","PEINOUSA","PETHAINW"};
int i;
for (i=0; i<=ena.lenght; i++)
System.out.println(ena[i]);
}
}
2nd change the class to method :
public class AytiMain {
public static void main(String[] args) {
AytiMain.Kremalation();
}
public static void Kremalation() { // change here.
String ena[]={"PEINAW","PEINOUSA","PETHAINW"};
int i;
for (i=0; i<=ena.lenght; i++)
System.out.println(ena[i]);
}
}