如何在for循环中获得一对字符串?

时间:2018-12-23 06:54:15

标签: java

为什么使用nextLine()不能有效地获取输入? 如果我使用next()而不是nextLine(),则代码超级好,但是为什么呢?它背后的原因是什么。我应该在哪里以及全部使用next和nextLine();

import java.util.Scanner;

public class Sample{
    public static void main(String args[]) {
        String a,b;

        Scanner scan = new Scanner(System.in);
        q = scan.nextInt();
        for(int m=0;m<q;m++) {
            a = scan.nextLine();
            b = scan.nextLine();
            System.out.println(a + "" + b);
            }

    }
}

预期:

2
mnopm
nop
mnop nop
abcdee
bee
abcdee bee

实际:

2
mnop
mnop(output appears before taking the 2nd input)
abcee
bee
abcee bee

1 个答案:

答案 0 :(得分:1)

<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <script src = "https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"> </script> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body > <br><br><br><br> <ul style="display: inline" class="collapsible"> <li style="display: inline"> <div style="display: inline"class="collapsible-header"><i class="material-icons">filter_drama</i>First</div> <div style="display: none;position:absolute;"class="collapsible-body"><span>Lorem ipsum dolor sit amet.</span></div> </li> <li style="display: inline"> <div style="display: inline"class="collapsible-header"><i class="material-icons">place</i>Second</div> <div style="display: none;position:absolute;"class="collapsible-body"><span>Lorem ipsum dolor sit amet.</span></div> </li> <li style="display: inline"> <div style="display: inline"class="collapsible-header"><i class="material-icons">whatshot</i>Third</div> <div style="display: none;position:absolute;"class="collapsible-body"><span>Lorem ipsum dolor sit amet.</span></div> </li> </ul> <script> $(".collapsible").collapsible() </script> </body> </html>替换为q = scan.nextInt();可以解决问题

q = Integer.valueOf(scan.nextLine());方法不会在按回车键创建的输入中读取换行符。请参考此link以获取更多信息