简体   繁体   English

Java中没有大小的数组

[英]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? 感谢您提供任何帮助,有关我的编码的任何评论都很棒,因此我可以解决该问题以供将来学习:)另外,count变量似乎可以计数64个字符,而不是txt文件中的27个字符?

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) 编辑:仅供参考,还有一个类包含一些我目前正在使用的方法(在代码末尾提到的MapFunctions

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. 如果您事先不知道大小,请改用ArrayList

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. 将值添加到ArrayList ,可以创建一个数组(其大小基于ArrayList中元素的数量)并将数据复制到该ArrayList

Array should have number of rows declared, If you are not sure of that user ArrayList. 如果不确定该用户Ar​​rayList,则Array应该声明了行数。

You can read example here 您可以在此处阅读示例

You can't create arrays without size or variable size arrays in Java. 在Java中,没有大小或可变大小的数组就无法创建数组。 If you are not sure about the size the best approach is to use ArrayList instead of Array. 如果不确定大小,最好的方法是使用ArrayList而不是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 但是,如果您只想使用数组,那么您可以做的就是在数组大小已满时将数组大小增加一些

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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