2016-12-31 52 views
-1

我正在解决这个hackerrank 30天的代码挑战。代码如下:30天的代码hackerrank day1

import java.util.*; 

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

     /* Declare second integer, double, and String variables. */ 
     try (Scanner scan = new Scanner(System.in)) { 
      /* Declare second integer, double, and String variables. */ 
      int i2; 
      double d2; 
      String s2; 

      /* Read and save an integer, double, and String to your variables.*/ 
      i2 = scan.nextInt(); 
      d2 = scan.nextDouble(); 

      scan.nextLine(); // This line 
      s2 = scan.nextLine(); 

      /* Print the sum of both integer variables on a new line. */ 
      System.out.println(i + i2); 

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

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

在这段代码中我添加一个额外的行scan.nextLine();因为没有它的编译器甚至不会注意到下一行是s2 = scan.nextLine();。为什么编译器不注意s2=scan.nextLine();而不写scan.nextLine();

回答

3

这与编译器以及Scanner的行为方式无关。

如果你读了Java文档,你会看到Sanner.nextLine()不

此扫描器执行当前行,并返回输入的是 被跳过。此方法返回当前行的其余部分,排除末尾的任何行分隔符,即 。该位置设置为下一行开头的 。现在

你可能想知道什么是左,你叫

i2 = scan.nextInt(); 
d2 = scan.nextDouble(); 

后,在这种情况下,它是回车符。调用scan.nextLine()会读取这些字符并将位置设置为下一行的开头。

+0

谢谢。我也错过了回车符的概念。 – ashishdhiman2007