creating an array in a seperate constructor class - java

Very new to this. I'm trying to call a constructor method out of a separate class file that will make an array. Rather than post what I was working on for an assignment I've made a generic version that is much more simple.
What I am expecting is that the main will call MakeArray which will create an array of 3 integers: [0,1,2] then the main will add these terms and the only output would be the total, 2.
From my Main:
MakeArray trial = new MakeArray()
System.out.println(trial[0] + trial[1] + trial[2]);
From my class file:
final int CONSTANT = 3;
public MakeArray()
{
int[] demo = new int[CONSTANT];
for(int i=0; i<CONSTANT; i++)
{
demo[i]=i;
}
return demo[];
}
Thanks!

Creating an array like this won't work because arrays aren't normal objects but special ones.
So you can't just make an object that works the same as an array, instead make a static method (one that can be called without having an instance of a class) and make it return an array, like this:
static final int CONSTANT = 3;
public static int[] MakeArray()
{
int[] demo = new int[CONSTANT];
for(int i=0; i<CONSTANT; i++)
{
demo[i]=i;
}
return demo;
}
In that case you also have to make the constant variable static like I have done.
Then you can call this much like a constructor, you just need to add the name of the class it is placed in before it when you want to call it:
int[] trial = MakeArray.MakeArray();
This of course only works if you put this method in a class called "MakeArray" otherwise you have to put something else in front of the dot.

You don't appear to want a new instance of a MakeArray I suggest you make it an utility method.
From my Main:
int[] trial = MakeArray.newArray(3);
System.out.println(trial[0] + ", " + trial[1] + ", "+trial[2]);
with a utlity class defined as
enum MakeArray { ;
static int[] newArray(int n) {
int[] demo = new int[n];
for (int i = 0; i < n; i++)
demo[i]=i;
return demo;
}
}

You cannot access the MakeArray object as an array. You could however create a method returns said array:
class MakeArray {
public static int[] makeArray() {
int[] demo = new int[CONSTANT];
for(int i=0; i<CONSTANT; i++) {
demo[i]=i;
}
return demo;
}
}
Then you can use it like that:
int[] trial = MakeArray.makeArray();
System.out.println(trial[0] + trial[1] + trial[2]);

One way to do it is to add an instance variable in your class and its corresponding getter method:
final int CONSTANT = 3;
int[] demo;
public MakeArray()
{
demo = new int[CONSTANT];
for(int i=0; i<CONSTANT; i++)
{
demo[i]=i;
}
}
public getArray(){
return demo;
}
Now you can call from main:
MakeArray arr = new MakeArray();
int[] trial = arr.getArray();
System.out.println(trial[0] + trial[1] + trial[2]);

As far I understand your question, you may be want something like this.
class file:
final int CONSTANT = 3;
public class MakeArray
{
public int[] demo;
public MakeArray()
{
demo = new int[CONSTANT];
for(int i=0; i<CONSTANT; i++)
{
demo[i]=i;
}
}
}
main class:
MakeArray trial = new MakeArray()
System.out.println(trial.demo[0] + trial.demo[1] + trial.demo[2]);

Related

How to call the constructor of the members of an array in Java?

I have a class:
public class a {
public int memberA;
private int memberB;
public a (int i) {
memberA = i;
memberB = ...;
}
}
and another one:
public class b {
public a[] = new a[10]; // <-- How do I call the constructor of 'a' with a value?
...
}
I tried many things, but nothing works! My app crashes if I don't call the constructor!
You can just use a for loop to instantiate each element of the array.
public class b {
public a[] arr = new a[10];
{
for(int i = 0; i < arr.length; i++) arr[i] = new a(/*some value*/);
}
}
As an aside, always follow Java naming conventions e.g. the name of the classes should be A and B instead of a and b. Better if you use self-descriptive names.

Queue does not take parameters in java

I have a problem in my code
I'm not being able to add Queue
When I tried to add this code
Queue<Integer> myqu = new LinkedList<>();
for (int i = 0; i <= mySecondArray.length + 1; i++){
myqu.add(mySecondArray[i]);
}
To this code
import java.util.LinkedList;
import java.util.Queue;
import java.util.*;
class test{
static class Queue{
static Stack<Integer> s1 = new Stack<Integer>();
Queue<Integer> myqu = new LinkedList<>();
static int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
static int[] mySecondArray = new int[10];
static void enQueue(){
for (int i = 0; i < intArray.length; i++){
s1.push(intArray[i]);
}
System.out.printf("\nBefore multiply operation\n");
System.out.printf("%s \n",s1);
System.out.printf("\nAfter multiply operation\n");
Integer edit = s1.pop();
System.out.printf("[");
for (int i = 1; i <= s1.size() + 1; i++){
mySecondArray[i] = i * 2;
edit = Integer.valueOf(i) * 2;
System.out.printf("%s",edit);
System.out.printf(", ");
}
System.out.printf("]");
for (int i = 0; i <= mySecondArray.length + 1; i++){
myqu.add(mySecondArray[i]);
}
}
};
public static void main(String[] args)
{
Queue q = new Queue();
q.enQueue();
}
}
It says " error: type Queue does not take parameters
Queue myqu = new LinkedList();"
Could you correct the code, Please
You are geeting this issue because your class name and interface Queue name is same.
Change you class name and this issue will resolve like:
static class SampleQueue{
..your code
}
And change your main method for new name:
public static void main(String[] args)
{
SampleQueue q = new SampleQueue();
q.enQueue();
}
If you're trying to use java.util.Queue, why are you creating your own inner static class called Queue? Rename your Queue class, and it's also declared static, so you can't instantiate it with new
Also you myqu is not declared static, so you need to fix that as well, I renamed it myQueue in the code below as per naming conventions
public class test {
static class QueueUtil {
static Stack<Integer> s1 = new Stack<Integer>();
static Queue<Integer> myQueue = new LinkedList<>();
static int[] intArray = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
static int[] mySecondArray = new int[10];
static void enQueue() {
for (int value : intArray) {
s1.push(value);
}
System.out.print("\nBefore multiply operation\n");
System.out.printf("%s \n", s1);
System.out.print("\nAfter multiply operation\n");
Integer edit = s1.pop();
System.out.print("[");
for (int i = 1; i <= s1.size() + 1; i++) {
mySecondArray[i] = i * 2;
edit = i * 2;
System.out.printf("%s", edit);
System.out.print(", ");
}
System.out.print("]");
for (int i = 0; i <= mySecondArray.length + 1; i++) {
myQueue.add(mySecondArray[i]);
}
}
}
public static void main(String[] args) {
QueueUtil.enQueue();
}
}
This code should fix your issue that you asked about, but I think you're not going to get the results you're expecting...
I recommend reading up on how, when and why to use static, there are a lot of great posts on here.

How do I initialize elements of an array, 1 through 10, and then use that constructor in a method that will print the elements?

I have an assignment for object-oriented programming class. I've been trying to take the values of an array that were initialized in a constructor, and use the values from that constructor to print them in a different method called printArrayValues. I cannot seem to 'call' or return the values in the method.. I've been troubleshooting for hours and I'm getting frustrated.
The assignment's steps are as follows:
The constructor for the ExerciseOne class initializes and instantiates myArray as an array of ten integers, and initializes the elements of the array with the values 1 through 10, using a for-loop.
You must assign the values in terms of the for-loop index variable, for example, i.
The class has a method called printArrayValues that uses a for-loop and System.out.print() statement to print out the values of the elements of the array, as shown in the sample output.
This method has no parameters, and no return value.
I've tried creating a new variable in the constructor, and then calling it in the method, but it's not working.
public class ExerciseOne {
public int[] myArray;
public static void main(String[] args) {
ExerciseOne aExerciseOne = new ExerciseOne();
aExerciseOne.printArrayValues();
}
ExerciseOne() {
for (int i = 0; i < myArray.length; i++) {
this.myArray = new int[i];
}
}
public void printArrayValues() {
System.out.print("myArray = {");
for (int a = 0; a < myArray.length; a++) {
System.out.print((myArray[a] + 1));
if (a < 9) {
System.out.print(",");
}
else {
System.out.print("};");
}
}
}
//
//public void displayArrayProduct() {
// for (int : myArray) {
//
// }
//
//}
}
I got frustrated and just created the loop, to initialize it, in the method. This is incorrect for the assignment, but I wanted to move on. Honestly I'm very lost at this point and I'm sorry if that makes it more difficult to help me.
You can try this code.
public class ExerciseOne {
public int[] myArray = new int[10];
public static void main(String[] args) {
ExerciseOne aExerciseOne = new ExerciseOne();
aExerciseOne.printArrayValues();
}
ExerciseOne() {
for (int i = 0; i < myArray.length; i++) {
this.myArray[i] = i+1;
}
}
public void printArrayValues() {
System.out.print("myArray = {");
for (int a = 0; a < myArray.length; a++) {
System.out.print((myArray[a]));
if (a < 9) {
System.out.print(",");
}
else {
System.out.print("};");
}
}
}
}
Output: myArray = {1,2,3,4,5,6,7,8,9,10};
You are initializing the same array twice. Your program will work the same if you use any of below :
myArray = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9 , 10};
or
myArray = new int[10]; for (int i = 0; i < myArray.length; i++) { this.myArray[i]=i+1; }
as your array is not 2d array so you cant assign another array on elements of array.
this.myArray = new int[i]; // not correct
I've written and tested the below and it returns the output you need. Please note that it's been written in C# for a console application. If it helps then please remember to vote for me.
Create your ExerciseOne class like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
public class ExerciseOne
{
int[] eo;
public ExerciseOne()
{
eo = new int[10];
for (int i = 0; i <= 9; i++)
{
eo[i] = i + 1;
}
printArrayValues();
}
public void printArrayValues()
{
foreach (var item in eo)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}
Then call the class like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Program
{
static void Main(string[] args)
{
ExerciseOne one = new ExerciseOne();
}
}
}

JUnit: test builder with private field

I'm a beginner and I have a problem with JUnit test in the constructor of a class.
The class that I want to test is called IntSortedArray and is as follows:
public class IntSortedArray {
private int[] elements;
private int size;
public IntSortedArray() {
this.elements = new int[16];
this.size = 0;
}
public IntSortedArray(int initialCapacity) throws IllegalArgumentException {
if(initialCapacity < 0) {
throw new IllegalArgumentException("Error - You can't create an array of negative length.");
}
else {
elements = new int[initialCapacity];
size = 0;
}
}
public IntSortedArray(int[] a) {
elements = new int[a.length + 16];
for(int i = 0; i < a.length; i++)
elements[i] = a[i];
size = a.length;
insertionSort(elements);
}
//other code...
}
With Eclipse I created a class for JUnit:
public class IntSortedArrayUnitTest {
private IntSortedArray isa;
#Test
public void testConstructorArray16Elements() {
isa = new IntSortedArray();
int expected = 0;
for(int i: isa.elements) **<-- ERROR**
expected += 1;
assertEquals(expected, 16);
}
}
I started to write a test class with the intention to test all the methods of the class IntSortedArray, including constructors.
The first method testConstructorArray16Elements() wants to test the first builder.
So I thought I would check if the creation of the array elements is done properly, so the for loop counts how long elements and make sure it along 16 (as required).
But Eclipse generates (rightly) a mistake because elements is private.
How can I fix this error? I don't want to put the public field and if possible I would like to avoid creating a method public int[] getElements().
What do you recommend?
Another question: I can do two assert the same method? One to test the length of the array and the other to test that size is 0.
I hope not to have made big mistakes, this is the first time I use JUnit.
PS: how can I test the second constructor?
Thank you very much!
It looks like your class fields are declare as private but you trying to access then from outside the class. You need to provide the accessors methods in you class to make them visible:
private int[] elements;
private int size;
public static final int MAX = 16;
public int[] getElements() { ... }
public int getSize() { return size; }
Then you will be able to write below code:
isa = new IntSortedArray();
int expected = 0;
for(int i: isa.getElements()) {
expected += 1;
}
assertEquals(expected, IntSortedArray.MAX );
It looks like your constructor has created an array for 16 integers, but does not initialize it with any value. To do that you should have below code:
public IntSortedArray() {
this.elements = new int[MAX];
this.size = 0;
for (int i=0 ; i < MAX ;i++) {
elements[i] = i;
size++;
}
}
You'll have to write a getter method for your array, or implement an Iterator

How to use an ArrayList from one class in another?

I'm fairly new to Java and this may sound a bit strange.
Okay basically I'm taking in 9 values and storing them as Integers in an ArrayListScores.
I have verified that they are storing in there and all looks okay with that.
I'm developing a simple androids app.
So we take it as if I take in the 9 values in class 1 as such from text views parseInt them. This works fine that is not my issue.
Class 1
ArrayList<Integer> Scores = new ArrayList<Integer>();
Scores.add(Integer.parseInt(et1.getText().toString()));
Scores.add(Integer.parseInt(et2.getText().toString()));
Scores.add(Integer.parseInt(et3.getText().toString()));
Scores.add(Integer.parseInt(et4.getText().toString()));
Scores.add(Integer.parseInt(et5.getText().toString()));
Scores.add(Integer.parseInt(et6.getText().toString()));
Scores.add(Integer.parseInt(et7.getText().toString()));
Scores.add(Integer.parseInt(et8.getText().toString()));
Scores.add(Integer.parseInt(et9.getText().toString()));
My Problem is that I have another class which I want to do some basic calculations, just add up all the scores as such.
Class 2
public class AddNumbers {
private static AddNumbers instance;
private AddNumbers(){
}
public static AddNumbers getInstance() {
if(instance == null) {
instance = new AddNumbers();
}
return instance;
}
public int getFinalScore() {
ArrayList<Integer> Scores = new ArrayList<Integer>();
int final_score = 0;
for(int s: Scores){
final_score += s;
}
return final_score;
}
}
I was to do the basic adding up of all the scores in class 2 and send the result back to class 1 but I don't know how.
Do you really need another class for this? Why not just put this in a method in Class 1?
It would look like:
public int getFinalScore(){
You want to put in your ArrayList here. This should look like:
public int getFinalScore(ArrayList<Integer> Scores) {
Then put your for loop, and return final_score:
int final_score = 0;
for (int s: Scores) {
final_score += s;
}
return final_score;
So your final method would look like this:
public int getFinalScore(ArrayList<Integer> Scores) {
int final_score = 0;
for (int s: Scores) {
final_score += s;
}
return final_score;
}
You would call it just via getFinalScore(Scores).
Pass Scores from Class 1 as a parameter into the getFinalScore method in Class 2
public int getFinalScore(List<Score> scores) {
int final_score = 0;
for(int s: scores){
final_score += s;
}
return final_score;
}
Then use the return value as your sum in Class 1.
What I would do is make a variable/instance of the ArrayList from class 1. so first you need to make Scores public so your other class can access it:
public static ArrayList<Integer> Scores = new ArrayList<Integer>(); //add public and static
Scores.add(Integer.parseInt(et1.getText().toString()));
Scores.add(Integer.parseInt(et2.getText().toString()));
Scores.add(Integer.parseInt(et3.getText().toString()));
Scores.add(Integer.parseInt(et4.getText().toString()));
Scores.add(Integer.parseInt(et5.getText().toString()));
Scores.add(Integer.parseInt(et6.getText().toString()));
Scores.add(Integer.parseInt(et7.getText().toString()));
Scores.add(Integer.parseInt(et8.getText().toString()));
Scores.add(Integer.parseInt(et9.getText().toString()));
Then, you need to refer back to it like so:
public int getFinalScore() {
ArrayList<Integer> scores = Class1.Scores; //make a new variable referring to the Scores (Case Matters!)
int final_score = 0;
for(int s: scores){ //use the new variable
final_score += s;
}
return final_score;
}
Alternatively, you can make the new variable scores (CASE matters) public and static if you want to use it in yet another class again (if you want to, this isn't necessary). However, you still need to make the ArrayList public! The public scores would look like this:
public class AddNumbers {
private static AddNumbers instance;
public static ArrayList<Integer> scores = Class1.Scores //made the variable public and static (optional)
private AddNumbers(){
}
public static AddNumbers getInstance() {
if(instance == null) {
instance = new AddNumbers();
}
return instance;
}
//same as before
public int getFinalScore() {
ArrayList<Integer> scores = Class1.Scores; //make a new variable referring to the Scores (Case Matters!)
int final_score = 0;
for(int s: scores){ //use the new variable
final_score += s;
}
return final_score;
}
}
Alternatively again, you can make a new parameter and set it to Scores (Again, you still need to make Scores public):
public int getFinalScore(ArrayList<Integer> scores) {
scores = Class1.Scores //set local variable to public variable
int final_score = 0;
for(int s: scores){
final_score += s;
}
return final_score;
}

Categories

Resources