有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

scanner类中的java输出未向字符串提供正确的输出

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);

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

        /* Print the sum of both integer variables on a new line. */
        int k=i+j;
        System.out.println(""+k);

        /* Print the sum of the double variables on a new line. */
        double o=p+d;
        System.out.println(""+o);

        /* Concatenate and print the String variables on a new line; 
           the 's' variable above should be printed first. */
        String s3=s.concat(n);
        System.out.println(s3);
        scan.close();
    }
}

我在给定代码的输入中遇到了字符串问题,尽管sccaner没有打印整行。我试着使用nextLine(),但仍然不起作用 因为我必须打印整个字符串

- Input (stdin)
   12
   4.0 
   is the best place to learn and practice coding! 
   Your Output (stdout) 
   16
   8.0
   HackerRank   
   Expected Output 
   16
   8.0 
   HackerRank is the best place to learn and practice coding!

共 (1) 个答案

  1. # 1 楼答案

    {a1}(<;==你应该读的链接)说:

    Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

    在上面的例子中,它返回“4.0”之后的剩余行,这是一个空字符串

    显然,输入标记由换行符分隔,因此在创建扫描程序后添加下面的第二行:

    // ...
    Scanner scan = new Scanner(System.in);
    scan.useDelimiter("\\n");
    // ...
    

    模式"\\n"表示一个反斜杠,后跟一个“n”,它被解释为换行符,请参见Pattern

    (解决方法/黑客:不要useDelimiter,只需忽略该行的其余部分,使用第二个nextLine(),而不是漂亮的^{