2017-06-20 2 views
0
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(); 
    } 
} 

Je reçois le problème dans la chaîne en entrée dans le code donné si sccaner pas l'impression de l'ensemble line.I essayé d'utiliser nextLine(), mais encore il ne fonctionne pas comme je dois imprimer toute la chaîne.sortie en classe du scanner ne donne pas une sortie correcte à la chaîne

- 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

double possible de [Scanner saute nextLine() après l'utilisation suivante() , nextInt() ou d'autres méthodes nextFoo()] (https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – Tom

Répondre

0

Les documentation of nextLine (< == lien vous devriez lire) dit:

Advances ce scanner passé la ligne en cours et retourne l'entrée qui a été ignorée. Cette méthode renvoie le reste de la ligne en cours, à l'exclusion de tout séparateur de ligne à la fin. La position est définie au début de la ligne suivante.

Dans le cas ci-dessus, il renvoie le reste de la ligne après "4.0" qui est la chaîne vide.

Apparemment, les jetons d'entrée sont délimitées par des sauts de ligne ajouter de sorte que le second soufflet en ligne après la création du scanner:

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

Le motif "\\n" signifie une barre oblique inverse suivie d'un « n » qui est interprété comme un caractère de saut de ligne , voir Pattern.

(solution de contournement/pirater: au lieu de useDelimiter, simplement ignorer le reste de la ligne et d'utiliser une seconde nextLine() - pas nifty)