Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

What is the output of this code sequence? try { Scanner file = new Scanner(new F

ID: 3548311 • Letter: W

Question

What is the output of this code sequence?                 

                    try                 

                    {                 

                    Scanner file = new Scanner(new File("data.txt));                 

                    String s = "";                 

                    while(file.hasNext())                 

                    {                 

                    s=file.nextLine());                 

                    }                 

                    if(s.equals("A"))                 

                    System.out.println("Nice finish");                 

                    file.close();                 

                    }                 

                    catch(IOException ioe)                 

                    {                 

                    ioe.printStackTrace();                 

                    }






                    File data.txt contains:                 

                    A                 

                    B                 

                    C                 

                    A                 

                    B                 

                    A

Explanation / Answer

The output will be "Nice finish"


Now why is the question. Here is the explanation


s=file.nextLine()); finds the next line of the file and reads it into a string s.

Now the shile loop makes this string reach the last line of the file.


Now since the last line of the given file is "A", the strings match and the output is "Nice finish"


Cheers!

Please rate my efforts :)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote