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]);
}
}
闽公网安备 35060202000074号