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();
}
}
}
Related
Hello So I have a entire class called tractor with different data's stored in it but now I'm suppose to create an object call tractor with a zero parameter constructor but This is the code I have so far and its giving em errors
First off this my Tractor Class which is in a different file:
import java.util.Scanner;
class Tractor
{
private int RentalRate;
private int RentalDays;
private int VehicleID;
private int RentalProfit;
public void setRentalRate(int r)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the Rental Rate?");
int num = input.nextInt();
num = r;
if(r<0 || r >1000)
RentalRate = r;
RentalRate= 1;
}
public int getRentalRate()
{
return RentalRate;
}
public void setVehicleID(int v)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the vehicleID?");
int num1 = input.nextInt();
num1 = v;
if(v<0)
VehicleID = v;
VehicleID = 1;
}
public int getVehicleID()
{
return VehicleID;
}
public void setRentalDays(int d)
{
Scanner input = new Scanner(System.in);
System.out.println("How many rental days?");
int num2 = input.nextInt();
num2 = d;
if(d<0)
RentalDays = d;
RentalDays = 1;
}
public int getRentalDays()
{
return RentalDays;
}
public String toString()
{
String str;
str = "RentalDays:" + RentalDays +"\nRenalRate:" + RentalRate + "\nVehicleID " + VehicleID;
return str;
}
public void RentalProfit(int RentalRate, int RentalDays)
{
RentalProfit = RentalRate * RentalDays;
}
}
import java.util.Scanner;
public class testTractor
{
public static void main(String[] args)
{
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
}
}
The error is :
testTractor.java:7: error: illegal start of expression
public tractor()
^
testTractor.java:7: error: ';' expected
public tractor()
^
2 errors
You have compilation errors. You need to first declare the Tractor class then add the constructor inside it. One way to do is declare in a separate file. Also in Java unless you had defined d you couldnt have assigned it. Maybe you wanted to assign the day as a String look in the examples I provide below.
You need to to first create a file call Tractor.java and then define variables there. For example contents of Tractor.java:
public class Tractor {
String rentaldays,someOtherValue;
public Tractor(){
rentaldays ="monday";
someOtherValue="value";
}
//or
public Tractor(String rentalDays){
this.rentaldays = rentalDays;
someOtherValue = "asf";
}
}
Then in your main method You can do Tractor trac = new Tractor(); or Tractor trac = new Tractor("tuesday"); also after that you can print the rentaldays of trac using System.out.println(trac.rentaldays);
From the looks of it you will probably be making a tractor rental system. In that case, rentalDays may be an array of Strings. And then you would have an array of Tractor objects to store in the rental system. You can look at these terms and keywords to point you in the right direction.
You are defining it wrong, define your methods inside class then call them in main() method.
class Test{
public void greeting(){
System.out.print("hello to JAVA..");
}
public static void main(String[] args){
Test testObj = new Test();
testObj.greeting();
}
}
you use an illegal of java syntax, if you already have class tractor in your project. for calling it to in other class, try below code
public class TestTractor(){
Tractor objTractor;
public static void main(String[] args){
//create new tractor object with no parameter
objTractor = new Tractor();
//create new tractor object with parameter
objTractor = new Tractor(parameter here);
//do some action of object here
...........
}
}
//This is just a sample
in your tractor class add below code
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
And keep your TestTractor class as
public class TestTractor(){
public static void main(String[] args){
Tractor objTractor = new Tractor();
// objTractor.yourMethodName
}
}
I've written up a code with several different methods. I can't seem to find the correct way to get the last method I have into the main method so it can print out the correct output.
CODE:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number:");
int num = in.nextInt();
} // this is my main method
public void results (int num) {
for (int i = 1; i < num; i++) {
System.out.print(space(num - i));
System.out.println(method1(i));
}
for (int i = 0; i < num; i++) {
System.out.println(method2(num-i));
System.out.print(space(i));
}
} //this is the method that I want inside my main method
I thought I could simply put System.out.println(results(num)); into my main method but that doesn't work. Can anyone explain what I'm doing wrong and help me with this problem?
Your main method is static, but your results method is not. Either make results be static, or declare a new instance of your class to use inside of main.
public class MyClass
{
public static void main(String[] args) {
results(1);
}
public static void results (int num) {
}
}
or
public class MyClass
{
public static void main(String[] args) {
new MyClass().results(1);
}
public void results (int num) {
}
}
You can't pass what results returns to anything such as System.out.println, because results has a void return type. But results already is printing out information, so just call results.
results(num);
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
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();
}
I have 2 classes 'Main' and 'FOR'. From 'Main' I will call method 'display' in class 'FOR'. 'display' will get multiple String values and return it to 'Main' class. Here the returned values must be displayed.
Only one single value is returned. How to get that multiple values returned?
Main.class
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
FOR obj = new FOR();
String str = obj.display();
System.out.print(str);
}
}
FOR.class
public class FOR {
int j=5;
String hi="hi";
String display()
{
for(int i=0;i<j;i++)
{
System.out.print(hi);
// If I use this I will get 5 times hi.. but I dont
/// want like this. I have to return hi String 5times to main and I have to display
/// but should not call 5 times display() too,by calling one time, I have to return
/// 5 time a string to Main class
}
return hi;
}
}
Desired output is to return 5 values from the method 'display'. Here I have to get 5 times HI .. But I am getting only one time .. the comment inline explains in more detail.
You can use List.
Example:
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
FOR obj=new FOR();
List<String> str= obj.display();
for(String v: str) {
System.out.print(v);
}
}
}
import java.util.List;
import java.util.ArrayList;
List<String> display() {
int j=5;
String hi="hi";
List<String> result = new ArrayList<String>();
for(int i=0;i<j;i++) {
result.add(hi);
}
return result;
}
A slightly different and more complicated approach but is useful in certain situations.
public class Main {
public static void main(String[] args) {
FOR obj = new FOR();
String str = obj.display(new ICallback() {
#Override
public void doSomething(String obj) {
// do whatever you want with this
System.out.println("This is being returned for each execution " + obj);
}
});
System.out.print(str);
}
public static interface ICallback
{
void doSomething(String obj);
}
public static class FOR {
int j = 5;
String hi = "hi";
String display(ICallback callback) {
for (int i = 0; i < j; i++) {
callback.doSomething(hi);
}
return hi;
}
}
}