我没有得到正确的输出?

ehxuflar  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(317)
import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String[] in = new String[n];
        for (int i = 0; i < n; i++) {
            in[i] = sc.nextLine();
        }
        for (int i = 0; i < n; i++) {
            System.out.println(in[i]);
        }
    }
}

输入:

2
Ankit

输出:

Ankit
8ljdwjyq

8ljdwjyq1#

这是因为scanner.nextint方法不会读取通过按“enter”创建的输入中的换行符,因此对scanner.nextline的调用在读取该换行符后返回。解决这个问题有两种选择,
1.通过scanner.nextline读取输入,并将输入转换为所需的正确格式

Scanner sc = new Scanner(System.in);
    int n = Integer.parseInt(sc.nextLine());

    String[] in = new String[n];

    for (int i = 0; i < n; i++)
    {
        in[i] = sc.nextLine();
    }

    for (int i = 0; i < n; i++)
    {
        System.out.println(in[i]);
    }

2.在每个scanner.nextint之后添加scanner.nextline调用

Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    sc.nextLine();

    String[] in = new String[n];

    for (int i = 0; i < n; i++)
    {
        in[i] = sc.nextLine();
    }

    for (int i = 0; i < n; i++)
    {
        System.out.println(in[i]);
    }
azpvetkf

azpvetkf2#

scanner类跳过nextint之后的下一行,这样您就可以通过如下编辑代码来修复它-

import java.util.Scanner; 
public class test {
public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    sc.nextLine();  
    String[] in=new String[n];
    for(int i=0;i<n;i++){
        in[i]=sc.nextLine();
    }
    for(int i=0;i<n;i++){
        System.out.println(in[i]);
    }

    }
}

相关问题