服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java-输入基本类


  java初学者,一定对从键盘输入数据感到困难,使用下面的类input,可以
方便的从键盘输入数据:
使用方法举例: string s=input.readstring(); 读入字符串
int i=input.readint(); 读入整数
下面是java输入输出基本类input类的源代码:
import java.io.*;
class input
{static inputstreamreader in;
static bufferedreader reader;
static
{in=new inputstreamreader(system.in);
reader=new bufferedreader(in);
}


static string readstring()
{string s="";
try
{ s=reader.readline();

}

catch(ioexception e)
{system.out.println(e);
system.exit(0);
}
return s;
}

static char readchar()
{char ch='a';
try
{
string s=readstring();
ch=s.charat(0);

}
catch(exception e)
{system.out.println("输入的数据类型不对,程序将退出");
system.exit(0);
}
return ch;
}


static int readint()
{string s=readstring();
int i=0;
try{
i=integer.parseint(s);
}
catch(exception e)
{system.out.println("输入的数据类型不对,程序将退出");
system.exit(0);
}
return i;
}
static double readdouble()
{string s=readstring();
double d=0.0;
try
{d=double.parsedouble(s);
}
catch(exception e)
{system.out.println("输入的数据类型不对,程序将退出");
system.exit(0);
}
return d;
}
static float readfloat()
{
string s=readstring();
float f=0.0f;
try
{
f=float.parsefloat(s);
}
catch(exception e)
{ system.out.println("输入的数据类型不对,程序将退出");
system.exit(0);
}
return f;
}
}

用法举例,从键盘输入十个整数:
class inoutdata
{public static void main(string args[])
{ int a[]=new int[10];
for(int i=0;i<10;i++)
{ system.out.println("请输入数");
a[i]=input.readint();
}
for(int i=0;i<10;i++)
system.out.println("a["+i+"]="+a[i]);
}
}

扫描关注微信公众号