two-dimensional array between classes | java - java

i have one problem with inheritance. I have 2 classes, (CreateAnArray,TheGame) and now - i have two-dimensional array which is created in 'CreateAnArray' class and i want to use it in 'TheGame' class, but every time i try to do it, it shows me 'null'.
public class TheGame extends CreateAnArray{
public void insert(String k){
for(int i=0;i<arrayOX.length;i++){
for(int j=0;j<arrayOX.length;j++){
if(arrayOX[i][j] == k && (arrayOX[i][j] != "x" && arrayOX[i][j] != "y"))
arrayOX[i][j]=k;
System.out.println(arrayOX[i][j]);
}
}
}
And the second class:
public class CreateAnArray {
public String[][] arrayOX = new String[3][3];
public void create(){
int k=1;
for(int i=0;i<arrayOX.length;i++){
for(int j=0;j<arrayOX.length;j++){
arrayOX[i][j]=Integer.toString(k++);
}
}
}
public void show(){
for(int i=0;i<arrayOX.length;i++){
for(int j=0;j<arrayOX.length;j++){
System.out.print(arrayOX[i][j]);
}
System.out.println();
}
}
I've tried a returning method, creating objects but nothing helps, what should I do?

Don't do this. Have your first class operate normally. When it needs arrayOX, have a function return that array to the first class. Don't extend the class here.
public String[] create(){
String[] arrayOX = new String[3][3];
int k=1;
for(int i=0;i<arrayOX.length;i++){
for(int j=0;j<arrayOX.length;j++){
arrayOX[i][j]=Integer.toString(k++);
}
}
return arrayOX;
}
Then, call this function to get arrayOX in the other class.

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.

creating method in new class; cannot find symbol error in main class

I know this has probably been an error asked about a million times but I'm really struggling to understand why I'm getting this with my one specific assignment.
I am to create a method class that will go through a String[] of words called 'list' and sort them alphabetically. I thought this would be an easy..
Here is what I have, I have no problem with the actual sorting, I just can't get Java to understand that I'm trying to call the method. I was given a specific class name, main class code, and method header, so I cannot change it or else I can't use the code runner.
class Lesson_15_Activity{
public static void sortAndPrint(String [] list){ //cant change
for (int pos = 0; pos < list.length-1; pos++){
for (int k = 0; k <= pos; k++){ //
if (list[k].compareTo(list[pos]) < 0){
list[pos] = list[k];
}
}
}
for (int a = 0; a < list.length-1; a++){
System.out.println(list[a]);
}
}
}
//the main method
class Main {
public static void main(String[] args) {
String [] list = { "against" , "forms" , "belief" , "government" , "democratic" , "movement" , "understanding"};
sortAndPrint(list);
//^this is where i get the error
}
}
I've tried adding code like this like in my earlier lessons but couldn't get it to work.
private String[] words;
public setWords(){
words = list;
}
You can go straight forward like this
import java.util.Arrays;
public class Lesson15Activity {
public static void main(String[] args) {
String[] list = {"against", "forms", "belief", "government", "democratic", "movement", "understanding"};
sortAndPrint(list);
//^this is where i get the error
}
public static void sortAndPrint(String[] list) { //cant change
Arrays.stream(list).sorted().forEach(e -> System.out.println(e));
}
}
You define two classes: Lesson_15_Activity and Main, and you're trying to use the method sortAndPrint since the class Main, when it is defined in Lesson_15_Activity.
One simple solution is join both classes:
class Lesson_15_Activity{
public static void sortAndPrint(String [] list){ //cant change
for (int pos = 0; pos < list.length-1; pos++){
for (int k = 0; k <= pos; k++){ //
if (list[k].compareTo(list[pos]) < 0){
list[pos] = list[k];
}
}
}
for (int a = 0; a < list.length-1; a++){
System.out.println(list[a]);
}
}
public static void main(String[] args) {
String [] list = { "against" , "forms" , "belief" , "government" , "democratic" , "movement" , "understanding"};
sortAndPrint(list);
//^this is where i get the error
}
}

How do I access an ArrayList from a previous method in the same class?

In this project, I'm trying to access information from an ArrayList which contains only the dates which are Strings.
Here is part of the class I tried. If not having the whole class makes it hard to understand I can edit...
public ArrayList<String> getTicketDates(){
ArrayList<String> theDateArray= new ArrayList<>();
int i;
for (i=0; i <tickets.size(); i++){
if(tickets .get(i).getPurchased()== false){
theDateArray.add(tickets.get(i).getDate());
}
}
for(int f=0; f<theDateArray.size();f++){
System.out.println(theDateArray.get(f)+ " ");
}
return theDateArray;
}
public int getTickets(String date){
int tix= theDateArray.indexOf(date);
int occurrences= Collections.frequency(theDateArray, tix);
if (tix>=0){
System.out.println(occurrences);
}
return occurrences;
}
The 2nd class, I'm trying to count the amount of times one particular date occurs in the previous ArrayList, but it says that theDateArray cannot be resolved to a variable.
One method I've tried is just calling the entire method getTicketDates(), but what it does is it prints out the ArrayList triple, and the occurrences still don't work.
Your theDateArray variable scope is local to the getTicketDates() method, so you are not able to access it in the other method, so declare it as an instance variable as shown below:
public class YourTicketsClass {
//declare ArrayList as an instance variable
ArrayList<String> theDateArray= new ArrayList<>();
public ArrayList<String> getTicketDates(){
int i;
for (i=0; i <tickets.size(); i++){
if(tickets .get(i).getPurchased()== false){
theDateArray.add(tickets.get(i).getDate());
}
}
for(int f=0; f<theDateArray.size();f++){
System.out.println(theDateArray.get(f)+ " ");
}
return theDateArray;
}
public int getTickets(String date){
int tix= theDateArray.indexOf(date);
int occurrences= Collections.frequency(theDateArray, tix);
if (tix>=0){
System.out.println(occurrences);
}
return occurrences;
}
}
Define the array list outside of the method, then populate the list inside the method. Like this:
public class YourdataClass {
private List<String> theDateArray = new ArrayList<String>();
public ArrayList<String> getTicketDates(){
int i;
for (i=0; i <tickets.size(); i++){
if(tickets .get(i).getPurchased()== false){
theDateArray.add(tickets.get(i).getDate());
}
}
for(int f=0; f<theDateArray.size();f++){
System.out.println(theDateArray.get(f)+ " ");
}
return theDateArray;
}
public int getTickets(String date){
int tix= theDateArray.indexOf(date);
int occurrences= Collections.frequency(theDateArray, tix);
if (tix>=0){
System.out.println(occurrences);
}
return occurrences;
}
}/* end class */
Here are some references. http://www.javawithus.com/tutorial/scope-and-lifetime-of-variables
https://en.wikibooks.org/wiki/Java_Programming/Scope

ArrayList is empty in other Methods in Java

The ArrayList is initialised inside a Class and its values are set in a method (which are only existent in this method)
How could I prevent the arraylist from being empty or why is this even happening?
(Edit: I added this minor project to github (https://github.com/goodstuff20/NENAM))
List<Node> nodes = new ArrayList<Node>();
public Creature(Node[] nodes){
for(int i = 0; i < nodes.length; i++) {
this.nodes.add(nodes[i]);
}
System.out.println(this.nodes.size()); //4
}
public void tick(){
System.out.println(nodes.size()); //0
}
You have defined 2 contructors in class Creature. In the second ctor you make a call to the first using the new-operator:
public Creature(Node[] nodes){
//....
for(int i = 0; i < nodes.length; i++){
nodess.add(nodes[i]);
}
//....
}
public Creature(int[][] nodePos, int[][] musclePos){
//...
Node[] nodes = new Node[nodePos.length];
//...
new Creature(nodes);
}
Maybe your intention is to change the currently created object by calling the other ctor, but instead you create a new object with no relation to the first.
To call another ctor inside a ctor on the same object you have to use this, but that must be done in the first line.
For example:
public Creature(int[][] nodePos, int[][] musclePos){
this(...);
}
For your purposes it is better to use an init-method:
public Creature(Node[] nodes){
init(nodes);
}
public Creature(int[][] nodePos, int[][] musclePos){
//...
Node[] nodes = new Node[nodePos.length]; //when defineing an int length = normal and not -1
//...
init(nodes);
}
private void init(Node[] nodes) {
//...
for(int i = 0; i < nodes.length; i++){
nodess.add(nodes[i]);
}
//...
}

Am I not understanding ArrayList or am I missing something?

I'm trying to create a very, very simple program.
I want my class called Text to simply print out a string, specifically, one letter.
Then in my second class called Window, I want to create an ArrayList of that class, iterate through the list and call the method of my Text class to print out the string. But it does not print anything.
What am I doing wrong?
public class Text {
private String a;
public void printA() {
a = "a";
System.out.print(a);
}
}
and the other class..
import java.util.ArrayList;
public class Window {
private ArrayList<Text> string = new ArrayList<Text>(5);
public Window() {
addText();
}
public void iterate() {
for (int i = 0; i < string.size() - 1; i++) {
string.get(i).printA();
}
}
public void addText() {
for (int i = 0; i <string.size() - 1; i++) {
string.add(new Text());
}
}
public static void main(String[] args) {
Window wind = new Window();
wind.iterate();
}
}
for(int i = 0; i <string.size()-1;i++){
string.add(new Text());
}
initialy the arraylist is empty, so string.size() == 0
the forlus wil not be executed, change to
public void addText(){
string.add(new Text())
}
or even better
public void addText(Text t){
string.add(t)
}
that way you can add Text-object created with different constructors
If you modify iterate to:
public void iterate(){
System.out.println(string.size()-1);
for(int i = 0; i < string.size()-1;i++){
string.get(i).printA();
}
}
You will get -1
Let me explain why:
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. private ArrayList<Text>string = new ArrayList<Text>(5); merely sets the capacity of the underlying array that is the data structure that implement the ArrayList object. size() returns the number of objects inside of the ArrayList not the capcity
public void addText(){
for(int i = 0; i <string.size()-1;i++){
string.add(new Text());
}
}
The for loop's expression doesn't evaluate to true, and therefore you never add a single object to the loop which is why iterate would print -1 if you added the print statement there
The
new ArrayList<Text>(5);
Doesn't mean you have 5 elements array. It means that this is just initial capacity of internal array for storing elements. Due to this your init code:
public void addText(){
for(int i = 0; i <string.size()-1;i++){
string.add(new Text());
}
}
faces no elements in the list with string.size() = 0.
Use this instead (If you like to add 5 elements):
public void addText(){
for(int i = 0; i < 5;i++){
string.add(new Text());
}
}
There is no problem to add more elements (even if the initial capacity was only '5'). From docu "As elements are added to an ArrayList, its capacity grows automatically."
problem it this method.
public void addText(){
for(int i = 0; i <string.size()-1;i++){
string.add(new Text());
}
}
this doesn't add anything at all. because string.size() is 0.
may be you should change it to
public void addText(int size){
for(int i = 0; i <size-1;i++){
string.add(new Text());
}
}
Ps: new Arraylist<Text>(5) actually creates an empty list with initial capacity = 5 (not size). See it here
Well for stater your method in Text needs parameter so it KNOWS to take in 'a' and if you're variable in your parameter is going to be 'a' as well you need use "this." so that the compiler knows that the two are different.
public class Text {
private String a;
public void printA(String a) {
this.a = "a";
System.out.print(a);
}
}
What you are doing wrong is that you are creating the ArrayList with a capacity of 5, but it does not yet have 5 objects in it. Thus, the addText method does nothing. Here's a version that works:
public void addText(){
for(int i = 0; i < 4; i++){
string.add(new Text());
}
}
Note that string.size() - 1 has been changed to 4, becuase string.size() is 0, and you want to add 4 elements to the list. Also, your iterate method could use a little refactoring:
public void iterate(){
for(Text text : string){
string.get(i).printA();
}
}
Instead of a simple loop, an enhanced for is used instead. This is no more than a typing shortcut, but it improves efficiency for LinkedLists.

Categories

Resources