简体   繁体   中英

Array without size in Java

I'm trying to define an array without any specific size but cannot seem to figure it out.

Any help is appreciated and any comments regarding my coding is awesome so I could fix that for future learning :) Also, the count variable seems to count 64 characters instead of the 27 in the txt file?

Thanks.

EDIT: FYI there is another class that contains some methods I'm currently working on (which is MapFunctions mentioned at the end of the code)

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Scanner;

public class MapMain {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        String T;
        System.out.print("What is the file dest?");
        T=input.nextLine();
        //String [][] map = new String[!][!];
        InputStream is = null;
        int i;
        char c;

        try{
          // new input stream created
             is = new FileInputStream(T);
             System.out.println("Characters printed:");
             int count;
             count = 0;
             // reads till the end of the stream
             while((i=is.read())!=-1){
                count=count+1;
                c=(char)i;

                // prints character
                System.out.print(c);
                for (int i = 0; i<array1.length;i++){
                    for (int j = 0; j<array1[i].length;j++){
                        array1[i][j]=c;
                    }
                }
             }
             System.out.print("\n"+count+"\n");
        }catch(Exception e){
             // if any I/O error occurs
             e.printStackTrace();
        }finally{
        }
        MapFunctions ankosh = new MapFunctions();
    }
}

An array must have a fixed size. If you don't know the size in advance, use an ArrayList instead.

After you finish adding the values to the ArrayList , you can create an array (whose size is based on the number of elements in the ArrayList ) and copy the data to it.

Array should have number of rows declared, If you are not sure of that user ArrayList.

You can read example here

You can't create arrays without size or variable size arrays in Java. If you are not sure about the size the best approach is to use ArrayList instead of Array. But if you want to use only arrays then you what you can do is increase the array size by some factor when the array size if full

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