码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA输入随笔

时间:2018-09-29 22:46:08      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:spl   system   pil   red   asn   java   readline   简单的   输入   

做题时经常遇到输入的问题,很麻烦

写一点点自己对于输入的随笔,以备后查

这里都以整数为例,其他类型的话换成相应方法就行了

1、知道一共多少行,每一行只有一个整数

这是比较简单的输入,可以用Scanner或者BufferedReader读,需要的话再进行强制转换

Scanner sc = new Scanner(System.in);
for(int i=0;i<n;i++){
     int x = sc.nextInt();
}

  

BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
for(int i=0;i<n;i++){
    int x = Integer.parseInt(sc.readLine().trim());
}

  

2、不知道一共有多少行,每一行只有一个整数

Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()){
   int x = sc.nextInt();
}

 

BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
String s;
while((s=sc.readLine())!=null){
   int x = Integer.parseInt(s.trim());
}

 

3、输入只有一行,有多个整数,不知道整数有多少个,它们之间用空格隔开,最后要把这些整数放入一个数组

BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
String[] s = sc.readLine().trim().split("\\s+");
int[] a= new int[s.length];
for(int i=0;i<s.length;i++){
   a[i]=Integer.parseInt(s[i]);
}

  

4、输入只有一行,有多个整数,提前知道整数有多少个(比如5个),它们之间用空格隔开,最后要把这些整数放入一个数组

Scanner sc = new Scanner(System.in);
int[] a= new int[5]; int i=0; while (sc.hasNextInt()) { a[i++]=sc.nextInt(); }

  

5、输入有多行,整数之间由各种符号隔开(包括换行符),我们需要取得所有整数构成数组。我们提前知道一共需要多少整数(比如6个)

 

Scanner sc = new Scanner(System.in);
sc.useDelimiter(Pattern.compile("\\D+"));
int x,count=0;
int[] a= new int[6];
while(count<6){
     x = sc.nextInt();
     a[count++]=x;
}

  

JAVA输入随笔

标签:spl   system   pil   red   asn   java   readline   简单的   输入   

原文地址:https://www.cnblogs.com/StackNeverOverFlow/p/9726825.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!