Java编程中获取键盘输入实现方法及注意事项
1. 键盘输入一个数组
package com.wen201807.sort;
import java.util.Scanner;
public class Main {
        public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            int len = sc.nextInt();
            int[] array = new int[len];
            for(int i = 0; i < len; i++) {
                array[i] = sc.nextInt();
            }
                        display(array);
        }
    }
        public static void display(int[] array) {
        for(int i = 0; i < array.length - 1; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println(array[array.length - 1]);
    }
}
2. 键盘输入含有逗号的坐标
package Java;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            int len = sc.nextInt();
            //sc.nextLine();
            int[] x = new int[len];
            int[] y = new int[len];
            for(int i = 0; i < len; i++) {
                String str = sc.next().trim();    //trim()函数去掉字符串首尾的空格
                //sc.nextLine();
                String[] strs = str.split(",");    //将坐标分开装入数组
                x[i] = Integer.parseInt(strs[0]);
                y[i] = Integer.parseInt(strs[1]);
            }
            
            for(int i = 0; i < len; i++) {
                System.out.print(x[i] + " ");
                System.out.println();
            }
            for(int i = 0; i < len; i++) {
                System.out.print(y[i] + " ");
                System.out.println();
            }
        }
    }
    
}
注意:
(1) Scanner类中next()与nextLine()都可以实现字符串String的获取。
next() 方法遇见第一个有效字符(非空格,非换行符)时,开始扫描,当遇见第一个分隔符或结束符(空格或换行符)时,结束扫描,获取扫描到的内容,即获得第一个扫描到的不含空格、换行符的单个字符串。
使用nextLine()时,则可以扫描到一行内容并作为一个字符串而被获取到。它的结束符只能是Enter键,即nextLine()方法返回的是Enter键之前没有被读取的所有字符,它是可以得到带空格的字符串的。
(2)当上述程序这样写的时候会报如下的错误:
错误如图:
原因:
这里nextline()读到空的换行符作为输入怎么读到换行符呢?在nextLine()中读取了第一行,但nextInt()只读取了输入的整型数字却没有读取换行符,下一个nextLine()会读取换行符,因此出现了错误,类型不匹配。
处理方法:
方法一:在for循环内最后加上sc.nextLine();用来读取nextInt()没有读取的换行符
方法二:把String str = sc.nextLine();改为String str = sc.next();
(3)为什么要加sc.nextLine()这一条语句
对于为什么要加sc.nextLine()这一条语句,因为出现了下面的问题:
1.没有sc.nextLine()的话,程序在debug模式下运行,发现直接先跳过第一次的str = sc.nextLine();这条语句,以str = 空形式传递了值,因此,后面相当于做了一次空操作,输出了一个空行,问题在哪呢?
2.通过查阅资料,当next()、nextInt()、nextDouble()等等这些之后,你如果不再加一条sc.nextLine()的话,下面如果用到了类似str = sc.nextLine(); 这条语句的话,会首先读取上面next()、nextInt()、nextDouble()等等这些语句的回车作为一条默认的(为什么是这样的机制呢?还需要继续探索),因此,解决的办法看下面第3点:3.就是在输入 next()、nextInt()、nextDouble()等等这些 之后,再用一个sc.nextLine()这个来截取上面的一个回车操作,后面的nextLine()在第一次才能起作用。
参考博客:https://blog.csdn.net/claram/article/details/52057562
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!