Saving the value of an array in a method - java

I will just post the pseuducode, hope you will understand:
import java.util*.;
main method {
subemethod1();
submethod1() {
Screen input = new Scanner(System.in);
int buy = input.nextInt();
if( buy != 0) {
submethod2();
}
submethod2() {
Screen input = new Scanner(System.in);
int[][]grid = new int [5][6]
int row = input.nextInt();
int col = input.nextint();
grid[row][col] = 1;
Let's assume I typed 1 for row, and 1 for col this time. then grid[1][1] = 1. I want to save the value of grid[1][1] so that next time I enter row 2, col 2 I will have:
grid[1][1] = 1;
grid[2][2] = 1; and so on for whatever row-col combination I type.
lastly I want to return to submethod1, and I want submethod1 to understand that grid[1][1] = 1 and that grid[2][2] also has the value 1; and so on....

Below I am assuming that you are asking about saving value of grid in an instance of program and not between various instances of program calls. if you want to save value of grid between varrious program calls than you will have to store value of grid in some file etc.
instead of creating the array grid inside submethod2(), create it as a class variable and submethod1(), submethod2() as member functions.
create an object in main method and call submethod1() on the object
something like
class ABC
{
int[][] grid = new int[5][6];
submethod1()
{
...
}
submethod2()
{
...
}
public static void main(String args[])
{
ABC abc = new ABC();
abc.submethod1();
}
}

This is a scoping problem. Essentially you're creating a new int[][] variable called grid every time you call submethod2(). Either store it as a class variable, or pass it in and then return it from submethod2() and manually update it yourself (I wouldn't recommend this approach)
Without more context, it's hard to recommend how to decompose your problem into objects, but one solution could be something like the following:
import java.util*.;
public class MainClass {
private int[][] grid;
public static void main(String[] args) {
submethod1();
}
private void submethod1() {
grid = new int[5][6];
Screen input = new Scanner(System.in);
int buy = input.nextInt();
if( buy != 0) {
submethod2();
}
}
private void submethod2() {
Screen input = new Scanner(System.in);
int row = input.nextInt();
int col = input.nextint();
grid[row][col] = 1;
}
}

Best way to deal with such problem is use Object Oriented approach. Remember that's why we use Java.
Create a class GridItem which will have three properties row, column, value. When you store some value create object of GridItem and store it in Global List. You can then iterate over it in any function and access which values were stored.
class GridItem
{
int row;
int column;
int value;
public GridItem(int row, int column, int value)
{
this.row = row;
this.column = column;
this.value = value;
}
//Provide getters only
}
ArrayList<GridItem>items = new ArrayList<GridItem>();
items.add(new GridItem(1, 1, 1));// 1 row 1 col 1 value
items.add(new GridItem(2, 2, 2));// 2 row 2 col 2 value
items.get(0).getRow()// get first
There are several other solutions. e.g Maintain a global array and then expand it. Create list of grids etc but they all are complicated and do more than necessary.

Related

Number is not added at back of existing array

Learning about Arrays. I am not able to figure out why a new number is not added to the back of my existing array. I read in two textfiles in file_1.txt are the numbers '1 2 3' and in file_2.txt is the number '91'. Basically without the method of Void addBack() the program does what I expect, however by adding the method it seems not make a new Array. Even when I go over the elements[i] = elements[i-1] it won't print it as a whole. I am expecting to print for the first part
The numbers are: 1 2 3 and the second part The numbers are: 1 2 3 91.
public class ExampleLecture {
IntRow readIntRow(Scanner input) {
IntRow result = new IntRow();
while (input.hasNext()) {
result.add(input.nextInt());
}
return result;
}
IntRow setBack(Scanner input) {
IntRow result = new IntRow();
while(input.hasNext()) {
result.addBack(input.nextInt());
System.out.println("here");
}
return result;
}
void print(IntRow row) {
for (int i = 0; i < row.numberOfElements; i++) {
System.out.printf("%d ", row.elements[i]);
}
System.out.printf("\n");
}
void start() {
Scanner in = UIAuxiliaryMethods.askUserForInput().getScanner();
Scanner in2 =UIAuxiliaryMethods.askUserForInput().getScanner();
IntRow row = readIntRow(in);
IntRow row2 = setBack(in2);
System.out.printf("the numbers are: ");
print (row);
System.out.printf("the new numbers are: ");
print (row2);
}
public static void main(String[] args) {
new ExampleLecture().start();
}
}
package examplelecture;
class IntRow {
static final int MAX_NUMBER_OF_ELEMENTS = 250;
int[] elements;
int numberOfElements;
IntRow() {
elements = new int[MAX_NUMBER_OF_ELEMENTS];
numberOfElements = 0;
}
void add(int number) {
elements[numberOfElements] = number;
numberOfElements += 1;
}
void addBack(int number) {
for (int i = numberOfElements; i>0; i--) {
elements[i] = elements[i-1];
elements[i] = number;
}
}
}
You have 2 successive assignments which write to the same position:
elements[i] = elements[i-1];
elements[i] = number;
The value is alway overwritten with number, so the first statement has no effect.
Also in your addBack method your for cycle:
for (int i = numberOfElements; i>0; i--) {
What happens if numberOfElements is 0?
You call it addBack but it looks like a better name for the method is addFirst. Usually index 0 is considered the front, not the back.
First off, both the readIntRow() and setBack() methods create new IntRow objects row and row2. If you want the result to be appended to the first IntRow object created i.e. to row , you should call:
IntRow row = readIntRow(in);
IntRow row2 = row.setBack(in2);
and setBack() needs to be modified to:
IntRow setBack(Scanner input) {
while(input.hasNext()) {
this.add(input.nextInt());
System.out.println("here");
}
return this;
}
Note that in setBack(), if you are trying to append numbers to the end of the IntRow object, you should call add() instead of addBack() as above. If you are trying to add to the front, you should call addBack() [and it might be better to call it addFront() instead].
Also, in the implementation of addBack(), if you are trying to add to the front of the IntRow object, the element[i] = number operation should take place only once, after the loop. Otherwise all the values in indices <= numberOfElements would be overwritten with number.
void addBack(int number) {
for (int i = numberOfElements; i>0; i--) {
elements[i] = elements[i-1];
}
elements[0] = number;
}
Admittedly it is not entirely clear what you are trying to accomplish. But you may have several problems. The first is as follows:
IntRow setBack(Scanner input) {
IntRow result = new IntRow();
while (input.hasNext()) {
result.addBack(input.nextInt());
System.out.println("here");
}
return result;
}
IntRow has nothing in it since it is new. So all you are doing is iterating over the new file which has just 91 in it. Remember, result has no items. So it won't even iterate once in addBack.
So just do the following:
Change your addBack method to just add the numbers. Why use a loop to cascade down the elements since you are doing this within the same instance of IntRow? Just add it on to the end using the numberofElements as the next index.
void addBack(int number) {
elements[numberOfElements++] = number;
}
If you want to copy the contents of one IntRow object to another you would need another method in the IntRow class. Something like:
public void copy(IntRow r) {
for (int i = 0; i < r.numerOfElements; i++) {
elements[i] = r.elements[i];
}
numerOfElements = r.numberOfElements;
}
And keeping with good design it might be better to return numberOfElements in a method such as public int size();

Finding for a specific row in a 2D Array and printing it out in Java

Sorry, I'm new to Java. I created a 2D array and populated it with String data. Now the task is to find a specific row in that array, that is filled with certain String and print it out. I mean to print only the row that was found. The problem is I don't know what row would it be. I managed to find that row and print it, but it prints the column along with the found row. Is it possible to print only the row but not the column?
Sorry for my English.
public class Math extends StudentCharts {
public Math(){
math = new String [3][3];
math[0][0]="math"; math[0][1]="person1"; math[0][2]="49";
math[1][0]=math[0][0]; math[1][1]="person2"; math[1][2]="12";
math[2][0]=math[0][0]; math[2][1]="person3"; math[2][2]="31";
}
public void prnt (String namechk){
int x = 0;
int y = 0;
for (x=0; x<3; x++) {
if (namechk.equals(math[x][1])) {
for (y=0; y<3; y++) {
System.out.println(math[x][y]+" ");
}
}
else { System.out.println("error");
}
The main class:
public static void main(String[] args) {
Math chr1 = new Math();
Scanner user = new Scanner(System.in);
System.out.println("Enter full name, please");
String namecheck = user.nextLine();
chr1.prnt(namecheck);

Accessing Objects Made in Array from Different Class

i am having trouble trying to figure out how to access objects that were made in an array in another class from Main. Psuedo for what im trying to do.
In Main CLass Prompt user for number of Tables In the Restaurant
take number n, create array of n Table objects in Restaurant Class
Access each tableobject created and be able to add values to it via constructor all from main
Hopefully the code can Explain Better.
My Main Class
Restaurant RestaurantObject = new Restaurant();
Table TableObject = new Table();
System.out.println("Max Tables In Restaurant? (Interger)");//Set Max Tables
Scanner smax_tables = new Scanner(System.in);
int max_tables = smax_tables.nextInt();
RestaurantObject.create_table_array(TableObject, max_tables);
My Restaurant Class
private Table[] TableList; //and other random variables
//other methods
public void create_table_array(Table table,int number) {
Table[] TableList = new Table[number];
int i = 0;
for(i = 0; i < number; i++) {
TableList[i] = table;
}
public Restaurant() {
}
My Table CLass
int max_amount;
public int getMax() {
return max_amount
}
Table(int number) {
this.max_amount = number;
}
And my desired action
run program and enter 5 for max tables
5 tables created in restaurant
RestaurantObject.Table1(10) //set max to 10 in table object
System.out.printf("max amount for table1 is %d",Restaurant.Table1.getMax()
Now that im re-looking at it. Would i have to prompt the user for the table to edit, get and return that table object in the array? Any help would be great,thanks
If i get your question right, the you want to access the array created here :
public void create_table_array(Table table,int number) {
Table[] tableList = new Table[number];
int i = 0;
for(i = 0; i < number; i++)
tableList[i] = table;
}
What you can do is change the method from void to Table[] and return the created array. Like this:
public Table[] create_table_array(Table table,int number) {
Table[] tableList = new Table[number];
int i = 0;
for(i = 0; i < number; i++)
tableList[i] = table;
return tableList;
}
Now in your main program, you can call the method like this:
Table[] tables = RestaurantObject.create_table_array(TableObject, max_tables);
Now you can access all tables by their indices. For example
for(int i = 0; i < tables.length; i++)
//do something to tables[i]
Also, you should stick with JAVA naming conventions and use camelCase for variable names. For example: TableList==>tableList etc...

Using a data structure to solve this in O(n)

we have sequence of 4 characters (A,B,C and D)that map to numbers form 1 to n.
we define components to be:
Component(k) :
A {cell[k]}
if Color(left_k) = Color(k)
then
A <-- A U Component(left_k)
if Color(right_k) = Color(k)
then
A <-- A U Component(left_k)
return A
there is 3 types of operations(the numbers in list indicate the input):
by giving index it should remove the component in that index(the numbers mapping to characters are fixed)
example : AABBBDA is the string. if index is 3 it should return AADA
by giving index it should rotate the string based on the component on that index(the numbers mapping to characters are fixed)
example : AABBBDA is the string. if index is 3 it should return DABBBAA
it should print the string.
inputs are like:
1 2 --> first operation with index=2
2 3 --> second operation with index=3
3 --> third operation
It's an assignment, happy to get help.
this is what i've tried so far:
public static void main(String[] args)
{
int numberOfOps;
String[] print = new String[30];
List list = new List();
Scanner input = new Scanner(System.in);
int count = input.nextInt();
String colors = new String();
colors = input.next();
for(int i = 0; i < count; i++)
{
list.add(colors.charAt(i));
}
numberOfOps = input.nextInt();
list.printElement();
for (int i = 0; i < numberOfOps; i++)
{
int op = input.nextInt();
if(op == 1)
{
int index = input.nextInt();
char c = list.item[index];
int temp = index;
int prevIndex = index;
int nexIndex = index;
if(index != 0)
{
while (list.item[--index] == c)
{
prevIndex--;
}
while (list.item[++temp] == c)
{
nexIndex++;
}
list.setNext(prevIndex-1, nexIndex+1);
}
else
{
while (list.item[++temp] == c)
{
nexIndex++;
}
list.setNext(prevIndex, nexIndex+1);
}
}
if(op == 2)
{
int index = input.nextInt();
}
if(op == 3)
{
print[i] = list.printElement();
}
}
}
here is my List class:
public class List {
// reference to linked list of items
public static final int MAX_LIST = 20;
public static final int NULL = -1;
public char item[] = new char[MAX_LIST]; // data
public int avail;
public int next[] = new int[MAX_LIST]; // pointer to next item
private int numItems; // number of items in list
public List()
{
int index;
for (index = 0; index < MAX_LIST-1; index++)
next[index] = index + 1;
next[MAX_LIST-1] = NULL;
numItems = 0;
avail = 0;
} // end default constructor
public void add(char e)
{
item[avail] = e;
avail = next[avail];
numItems++;
}
public String printElement()
{
String temp = null;
int index = 0;
while(index<avail)
{
temp += item[index];
System.out.println(item[index]);
index = next[index];
}
return temp;
}
public int size()
{
return numItems;
}
public void setNext(int i, int value)
{
next[i] = value;
}
}
if you test it you'll get, it has lots of problems, such as, I have no idea to do the rotate operation, and it has problem with connecting two components when the middle component has been removed.
This is a difficult question to answer, because the requirements are not properly stated.
For example the first bunch of pseudo-code does not make it clear whether A is a set, a multi-set or a list. The notation (use of curly brackets, and U (union?)) seems to say set ... but the output seems to be a list. Or maybe it is supposed to be a schema for a data structure??
And even the inputs are not clearly described.
But putting that on one side, there is still room for some (hopefully) helpful advice.
Make sure that >>you<< understand the requirements. (I imagine that the real requirements for the assignment are better stated than this, and the details have been "lost in translation".)
I would actually use an array list (or a StringBuilder) rather than a linked list for this. (But a properly implemented linked list ... implementing the List API ... would work.)
But whatever data structure you chose, there is no point in implementing it from scratch ... unless you are specifically required to do that. There are perfectly good list classes in the Java standard libraries. You should reuse them ... rather than attempting to reinvent the wheel (and doing a bad job).
If you are required to implement your own data structure type, then your current attempt is a mess. It looks like a hybrid between an array list and a linked list ... and doesn't succeed in being either. (For example, a decent array list implementation does not need a MAX_LIST, and doesn't have next pointers / indexes. And a linked list does not have any arrays inside it.)

Accessing 2-dimensional array from an object class.

In Java I have a 2-dimensional array of objects but I can't access any of those array of objects in the object's class methods. What should I do?
Here's my class:
class GoPiece
{
final int boardSize = 19;
final int empty = 0;
final int black = 1;
final int white = 2;
int pieceType = empty;
int leftRight;
int downUp;
int turnPlayed;
boolean legal;
// GoPiece's Constructor with 3 parameters.
GoPiece(int blackOrWhite, int horizontalCoordinate, int verticalCoordinate)
{
pieceType = blackOrWhite;
leftRight = horizontalCoordinate;
downUp = verticalCoordinate;
if ((true));
}
// GoPiece's Constructor with 2 parameters.
GoPiece(int horizontalCoordinate, int verticalCoordinate)
{
pieceType = empty;
leftRight = horizontalCoordinate;
downUp = verticalCoordinate;
}
// GoPiece's Constructor with no parameters.
GoPiece()
{
leftRight = 0;
downUp = 0;
}
// Initialize an empty Go board full of GoPieces.
GoPiece[][] InitializeBoard()
{
GoPiece[][] intersection = new GoPiece[boardSize][boardSize];
for(int horizontal = 0; horizontal < boardSize; horizontal++)
{
for(int vertical = 0; vertical < boardSize; vertical++)
{
intersection[horizontal][vertical] = new GoPiece(horizontal,vertical);
}
}
return intersection;
}
// Make a piece a certain type: empty, black, or white.
public void SetType(int newType)
{
pieceType = newType;
}
public int GetType()
{
return pieceType;
}
public void CheckKill()
{
int foobar = this.GetType();
}
}
I can then use InitializeBoard() in another part of my program to create a two dimensional array of GoPieces... this works, but How do I access all of those pieces other than the one I'm referencing in the class GoPiece's member functions? I tried passing the whole array into one of GoPieces functions, but that didn't seem to work.
Go is an Ancient Chinese Board game. The CheckKill() method above is where I tried to access different parts of the array, but failed. Here I have some working dummy code.
Thank you.
You need to create a separate class to represent the board itself (including the current placement of pieces). The logic for creating a board, testing for a kill, etc., belong to the board, not to an individual piece.
Do you mean you want to call a method with the array like InitializeBoard.GetType(); Where InitializeBoard is a 2 Dimensional Array?
You can't do that. You Must Specify which GoPiece to get out of InitializeBoard. Example: InitializeBoard[0][0].GetType(); If you must call all methods, you can use a for loop to call each individually.

Categories

Resources