Consider the following code segment in the class test.java: import java.io.IOExc
ID: 3692895 • Letter: C
Question
Consider the following code segment in the class test.java: import java.io.IOException; import java.io.File: import java.util.Scanner; public class Test { public static void main(String[] args) { String stringRead; try { Scanner file = new Scanner(new File("data.txt")); stringRead = file.nextLine; } catch (lOException ioc) { ioc.printStackTracc(); } System.out.println("Siring read: " + stringRead);//Line 21 } } At compile time, we get the following error: Test.java:2l: error: variable stringRead might not have been initialized System.out.println("String read: " + stringRead); I error Explain what the problem is and how to fix it.Explanation / Answer
You declared them, but you didn't initialize them. Initializing them is setting them equal to empty string:
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
public class Test
{
public static void main(String[] args) {
String stringRead = ""; // solution is by initialzing the stringRead to empty string
try
{
Scanner file = new Scanner(new File("1.txt"));
stringRead = file.nextLine();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
System.out.println("String read: " + stringRead); // error
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.