2016-12-31 79 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