java程序如何在控制台限制输入的字数。如输入4位数字
2个回答
2016-09-30
展开全部
可以利用正则表达式,输入之后在判断:
package foundations.iolearn;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ReadingFromStdin {
public static void main(String[] args)
{
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = "";
while((s = br.readLine()) != null) {
if (!s.matches("^\\s*(\\+|-)?([0-9]|[1-9][0-9]*)\\s*$")) {
throw new Exception("含有非法字符");
}
int i = Integer.parseInt(s.trim());
System.out.println("read: " + i);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
package foundations.iolearn;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ReadingFromStdin {
public static void main(String[] args)
{
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = "";
while((s = br.readLine()) != null) {
if (!s.matches("^\\s*(\\+|-)?([0-9]|[1-9][0-9]*)\\s*$")) {
throw new Exception("含有非法字符");
}
int i = Integer.parseInt(s.trim());
System.out.println("read: " + i);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询