Java中做输入的方式:通过控制台输入数据,需要使用Scanner对象来操作,那么java输入语句到底有哪些呢?下面跟本站小编一起来看看吧!
1.使用Scanner
使用时需要引入包import ner;首先定义Scanner对象
Scanner sc = new Scanner();
如果要输入整数,则 int n = Int();
String类型的.,则String temp = ();
比如:
import ner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner();
int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int month = -1;
while(true) {
try {
t("请输入月份:");
month = Int();
if(month >= 1 && month <= 12) {
break;
}
tln("** 请输入正确的月份 **");
} catch (Exception e) {
tln("** 格式错误!请输入数字 **");
();
}
}
tln(month + " 月份有:" + days[month - 1] + " 天");
}
}
2.使用BufferedReader
用前需要引入 import er;
BufferedReader br = new BufferedReader( new InputStreamReader() );
String input = Line();
比如:
==================================================================================================
import .*;
public class importtext {
public static void main(String[] args) {
String st;
int num;
float fnum;
try{
t("输入:");
BufferedReader br=new BufferedReader(new InputStreamReader());
st = Line();
t("输入一个数:");
num = eInt(Line());
t("输入一个浮点数:");
fnum = eFloat(Line());
t("输出:"+st+'n');
t("输出:"+num+'n');
t("输出:"+fnum+'n');
}catch(IOException e){}
}
}
==================================================================================================
package com.s2;
import .*;
public class Input
{
public static void main(String[] args)throws IOException
{
while(true)
{
BufferedReader buf;
String str;
buf =new BufferedReader(new InputStreamReader());
tln("Input a string:");
str=Line();
tln("String="+str);
}
}
}
==================================================================================================
应该注意的是:Java把从键盘输入的数据一律看作是字符串,因此若要从键盘输入并让系统认可是数值型数据,必须经过转换。
比如:
package com.s2;
import .*;
public class Input
{
public static void main(String[] args)throws IOException
{
while(true)
{
int num;
BufferedReader buf;
String str;
buf =new BufferedReader(new InputStreamReader());
tln("Input an integer:");
str=Line();
num=eInt(str);
tln("String="+str);
tln("Integer="+str);
}
}
}