为什么我需要使用Scanner.nextLine();两次保存?

时间:2019-06-26 21:53:32

标签: java

这来自hackerank.com上的30天代码挑战。我已经找到了意外的解决方案,但是我不明白为什么。如果我不使用z = scan.nextLine();什么都不会保存到该变量。

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        int i = 4;
        double d = 4.0;
        String s = "HackerRank ";

        Scanner scan = new Scanner(System.in);

        /* Declare second integer, double, and String variables. */
        int x;
        double y;
        String z;
        /* Read and save an integer, double, and String to your 
        variables.*/
        // Note: If you have trouble reading the entire String, please go 
        back and review the Tutorial closely.
        x = scan.nextInt();
        y = scan.nextDouble();
        z = scan.nextLine();
        z = scan.nextLine();

        /* Print the sum of both integer variables on a new line. */
        System.out.println(i + x);
        /* Print the sum of the double variables on a new line. */
        System.out.println(d + y);
        /* Concatenate and print the String variables on a new line; 
        the 's' variable above should be printed first. */
        System.out.println(s + z);
        scan.close();
    }
}

输入:

12
4.0
is the best place to learn and practice coding!

我的输出:

16
8.0
HackerRank 

预期输出:

16
8.0
HackerRank is the best place to learn and practice coding!

0 个答案:

没有答案