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 :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.