Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AbdullahMagat/0179e84a540279f48a85ad75cbc307c9 to your computer and use it in GitHub Desktop.
Save AbdullahMagat/0179e84a540279f48a85ad75cbc307c9 to your computer and use it in GitHub Desktop.
Hackerrank Java End-of-file Solution
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i=0;
while(scan.hasNextLine()){
String str=scan.nextLine();
if (str.contains("end-of-file")){
i++;
System.out.println(i+" "+str);
break;
}else{
i++;
System.out.println(i+" " +str);
}
}
// I don't know why hackerrank didn't accept my below solution. when I run it in eclipse it worked as well as it is required. anyway it is the 2. solution.
// Scanner scan = new Scanner(System.in);
// int i = 0;
// while(true){
// String str=scan.nextLine();
// if (str.contains("end-of-file")){
// i++;
// System.out.println(i+" "+str);
// break;
// }else{
// i++;
// System.out.println(i+" " +str);
// }
// }
}
}
@kadirgocebe
Copy link

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) {
    **String str;**
    Scanner input = new Scanner(System.in);
    int i=0;
    while(input.hasNextLine()){
     str=input.nextLine();
        if (str.contains("end-of-file")){
            i++;
            System.out.println(i+" "+str);
            break;
        }else{
            i++;
            System.out.println(i+" " +str);       
        }}
   
}

}

Here is the solution same as you. I guess the str variable should introduct after main not when you get it from user

@Preetojha08
Copy link

public class Solution {

public static void main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    
    Scanner scan = new Scanner(System.in);

    int i=1;
    while(scan.hasNextLine()){
    String s=scan.nextLine();
    System.out.println(i+" " +s);
        i++; 
    }
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment