您的位置:程序门 -> java -> j2se / 基础类



excuse me -2 请问如何动态生成数组,java不会没有方法实现吧?


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


excuse me -2 请问如何动态生成数组,java不会没有方法实现吧?[已结贴,结贴人:a19861028]
发表于:2007-09-14 23:02:35 楼主
这个和excuse   me   一样,犯java.lang.nullpointerexception

import   java.io.*;
public   class   two_eight   {
public   static   void   main     (string[]   args)
{
int   list[]=null;
list=get();
for(int   i=0;i <list.length;i++){
system.out.print(list[i]);
}

}
static   int   search(int   a[],int   i,int   left,int   right)
{
while(left <right)
{
int   middle   =   (left+right)/2;
if(middle==a[middle])return   middle;
else   if(middle> a[middle])left=middle+1;
else     right=middle-1;
}
return   -1;
}

static   int[]   get()
{
    int[]       array=null;      
                    /*system.out.println( "please       enter       num   ");    
                    bufferedreader       stdin=new       bufferedreader(new       inputstreamreader(system.in));      
                    int   n   =   -1;
                 
try   {
n   =   integer.parseint(stdin.readline());
}   catch   (numberformatexception   e)   {
e.printstacktrace();
}   catch   (ioexception   e)   {

e.printstacktrace();
}     */


                    for(int       i=0;i <3;i++)      
                    {      
                   
                    bufferedreader   stdin=new       bufferedreader(new       inputstreamreader(system.in));      
                    try   {
array[i]       =   (int)integer.parseint(stdin.readline());
}   catch   (numberformatexception   e)   {

e.printstacktrace();
}   catch   (ioexception   e)   {

e.printstacktrace();
}      
                    }          
                    return   array;
                 
}
}
发表于:2007-09-14 23:19:491楼 得分:5
....动态数组用容器

或者看看这个动态扩展数组的方法..
public   static   object   arraygrows(object   oldarray)   {
class   cl   =   oldarray.getclass();
if(!cl.isarray())   return   null;
class   componenttype   =   cl.getcomponenttype();
int   length   =   array.getlength(oldarray);
int   newlength   =   length   *   11/10   +   10;
object   newarray   =   array.newinstance(componenttype,   newlength);
system.arraycopy(oldarray,   0,   newarray,   0,   length);
return   newarray;
}
发表于:2007-09-14 23:27:062楼 得分:0
如何动态生成数组?

为什么要用动态数组呢?
发表于:2007-09-15 21:40:573楼 得分:5
应该可以吧.
发表于:2007-09-15 22:25:224楼 得分:10
在for(int       i=0;i <3;i++)之前,请先给数组申请内存,即array   =   new   int[3]
你一开始int[]       array=null;   ,array还是null,
就调用array[i]       =   (int)integer.parseint(stdin.readline());
当然就出nullpointerexception了
请lz写程序细心一点,不要总犯小错误


快速检索

最新资讯
热门点击