简体   繁体   中英

How to store 2-dimensional String array (java)

I'm trying to do a 2-dimensional String array method which takes 3 parameters (String array and two ints), the String array is already defined in the main method as (String [] stringArray = {"1", "2" , "3", "4", "5"};) and the two integers are entered by the user for the rows and columns. I want the code to run multiple times and the user to enter the values of rows and columns for each time it returns a 2-dimensional array with ("x") in the position of rows and columns which the user entered and ("0") otherwise. My question is how to store this 2-dimensional array info for the next attempt by the user.

//////////////////////////////////

Test:(This test is what I want, not what the code do!)

First attempt: -The user enters: 1 for row and 1 for line.

Output:
1 x 0 0
2 0 0 0
3 0 0 0
4 0 0 0
5 0 0 0

Second attempt: -The user enters: 2 for row and 3 for line.

Output:
1 x 0 0
2 0 0 0
3 0 x 0
4 0 0 0
5 0 0 0

//////////////////////////////////

My code:

import java.util.Scanner;

public class Assignment03First{
public static void main(String [] args){

    Scanner in = new Scanner(System.in);
    Assignment03First test = new Assignment03First();

    String [] stringArray = {"1", "2" , "3", "4", "5"};

    test.intro();
    int input = 0;
    String result [][];
    do{
    System.out.println("If you would like to make a booking press 1, otherwise press 0");
    input = in.nextInt(); 

    if(input == 1){
        test.helper1(stringArray);
    }else{
        System.out.println("Take care. Can't wait to hear from you again!");
    }
    }while(input == 1);
}

public void intro(){

    System.out.println("Available seats:");
    System.out.println("  SEAT ROWS");
    System.out.println("   A  B  C");
    for(int y = 1; y <= 5; y++){
        System.out.println("-----------");
        System.out.print("|" + y);
        for(int z = 0; z < 3; z++){
            System.out.print("|" + 0 + "|");    
        }
        System.out.println();
    }
    System.out.println("-----------");
}

public int helper1(String [] a){
    Assignment03First test = new Assignment03First();
    Scanner in = new Scanner(System.in);

        int unkown = 0;

        System.out.println("Hello! Welcome to our online ticket booking application");
        System.out.println("Which seat row would you like to seat?");
        String r = in.next();
        if(r.equals("A")){
            unkown = 0;
        }else if(r.equals("B")){
            unkown = 1;
        }else{
            unkown = 2;
        }
        System.out.println("Which seat line would you like to seat?");
        int l = (in.nextInt() - 1);

        test.seatInfo(a, unkown, l);

    return l;
}

public String [][] seatInfo(String [] a, int rows, int lines){
    Assignment03First test = new Assignment03First();

    int r = 5;
    int c = 4;
    String[][] array = new String[r][c];

    for(int i= 0; i < r; i++){
        for(int j = 0; j < c - 1; j++){
            if(i == lines && j == rows){
                array [i][j] = "x";
            }else{ 
                array [i][j] = "0";
            }
        }
        test.helper2(array, r, c, a);
    }
    return array;
}

public String [][] helper2(String [][] a, int r, int c , String [] b){

    Assignment03First test = new Assignment03First();

    System.out.println("Available seats:");
    System.out.println("  SEAT ROWS");
    System.out.println("   A  B  C");

    for(int i= 0; i < r; i++){
        System.out.println("-----------");
        System.out.print("|" + b[i]);
        for(int j = 0; j < c - 1; j++){
        System.out.print("|" + a[i][j] + "|");
        }
        System.out.println();
        System.out.println("-----------");
    }
    return a;
}
}

I believe what will be easier will use a dictionary or hashmap for this. You would be able to call or change the values in the dictionary by just calling the key and not dealing with array indexes.

You can store it in a class field. You can create class SeatService with field String[][] array and in a main method create object of SeatService class. Then you can call method seatInfo on this object and this method do modification on array .

Example of implementation:

Test class with main method:

public class Test {

    public static void main(String[] args) {
        SeatService seatService = new SeatService(4, 5);
        String[][] test1 = seatService.seatInfo(new String[] { "1", "2", "3", "4", "5" }, 2, 1);
        print(test1);
        String[][] test2 = seatService.seatInfo(new String[] { "1", "2", "3", "4", "5" }, 0, 0);
        print(test2);
    }

    public static void print(String[][] array) {
        System.out.print("Output: ");
        for (int i = 0; i < array.length; i++) {
            System.out.print(i + 1 + " ");
            for (int j = 0; j < array[i].length; j++) {
                System.out.print(array[i][j] + " ");
            }
        }
        System.out.print("\n");
    }
}

SeatService class:

public class SeatService {
    int r;
    int c;
    String[][] array;

    public SeatService(int r, int c) {
        this.r = r;
        this.c = c;
        array = new String[r][c];
        cleanArray();
    }

    public String[][] seatInfo(String[] a, int rows, int lines) {
        if (rows < r && lines < c && rows >= 0 && lines >= 0)
            array[rows][lines] = "x";
        return array;
    }

    private void cleanArray() {
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                array[i][j] = "0";
            }
        }
    }
}

Few things you should analyze:

  1. String[] a in your code is unused
  2. Your operations on array overrides previous modifications
  3. Indexes, first element in array has index 0, analyze example and your code eg j < c - 1

My first suggestion is that you try and use different notation for array indexing. In your example arrays you stated the user would enter row and then line. Rows are usually up and down. I suggest using row,column or i,j or n,m which are more common ways to describe position in 2d arrays.

Additionally, using an array of strings for this example is creating unnecessary overhead. A 2d array of boolean would suffice.

To answer your question it depends on how you want to store what seats are taken. If you want your class to store its current state

public class SomeSeatClass {

    private String[][] currentState;

    public SomeSeatClass(int rows, int cols) {
        currentState = new String[rows][cols];
        // sets the size of the 2d array and then initialize it so that no seats are
        // taken.
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < rows; j++) {
                currentState[i][j] = "0";
            }
        }
    }

    public void setSeat(int rows, int lines) {

        currentState[rows][lines] = "x";
    }

    public String[][] getCurrentState() {
        return this.currentState;
    }

}

However if you just want the function to process the new position and return the updated array then i would recommend making the function static like so

public static String [][] seatInfo(String [][] a, int rows, int lines){
        String[][] returnString = a.clone();
        returnString[rows][lines] = "x";
        return returnString;
    }

then in your main code

    int numberOfRows =5;
    int numberOfColumns = 3;
    String[][] seating = new String[numberOfRows][numberOfColumns];
    //initialize array to "0"s
     for (int i = 0; i < numberOfRows; i++) {
            for (int j = 0; j < numberOfColumns; j++) {
                seating[i][j] = "0";
            }
        }
     //get the row and col from user
     int userRow = 1;
     int userCol = 1;
     //seating now holds the most current state 
    seating =  SomeSeatClass.seatInfo(seating, userRow, userCol);

I think the issue you are running into is that you are looping through your array and resetting everything to "0" with each function call. You just need to set everything to zero at the beginning and then just update what seat is taken.

Notes: be careful of thinking of arrays as starting at 1,1. They start at 0,0 and it would be easiest to use them that way but hide those details from user. be careful when using strings as method parameters because they are immutable. No changes to strings will be reflected outside the function. However, you used a array of strings which changes it a little. be careful when thinking how to hold your data. String[][] is actually a 3d array. In your function you pass a String[] which doesnt really help us figure out what to do with our String[][] seatingArray

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM