MENU

java中使用nextLine(); 没有输入就自动跳过的问题?

May 20, 2018 • Read: 3197 • Java阅读设置

我昨天在做题(最长上升子序列)的过程中遇到一个问题,第一个数 N 表示后面有多少组测试数据,但是当我输入 N 之后,for 循环里的 nextLine(); 并没有让我输入,就跳过并且输出了

问题分析

in.nextLine()不能放在in.nextInt()后面,否则 in.nextLine()会读入\n,但\n并不会成为返回的字符

举个例子:

import java.util.*;
public class static void main(String[] args){
    Scanner in = new Scanner(System.in);
    int N = in.nextInt();
    for(int i = 0;i < N;i++){
    String str = in.nextLine(); 
    }
}

假如输入 N 为 1,摁下回车,程序并不会让你继续输入 str,而是直接结束了

解决方案

最好的解决办法,在 nextInt() 和 nextLine() 之间放一个 in.nextLine() 来接收这个 “n”

import java.util.*;
public class static void main(String[] args){
    Scanner in = new Scanner(System.in);
    int N = in.nextInt();
    in.nextLine();
    for(int i = 0;i < N;i++){
    String str = in.nextLine(); 
    }
}
Last Modified: February 8, 2020
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment