1. public static void read (String inFile, String [] lines){ try { Scanner read
ID: 3827733 • Letter: 1
Question
1.
public static void read (String inFile, String [] lines){
try {
Scanner read = new Scanner (new File ("inFile"));
lines = new String[read.nextInt()];
for (int i = 0; i < lines.length; i++) {
lines[i] = read.nextLine();
} } catch (IOException e){
System.out.println("can't read: " + inFile);
System.exit(-1); } }
public static void main (String [] args){
String [] lines = null; read ("in.txt", lines);
System.out.println(Arrays.toString(lines)); }
inFile:
3 Hey!
How’s it going?
Fun Stuff…
The answer is: can't read: in.txt
I want to know,why ?
I think it should be [Hey!, How’s it going?, Fun Stuff]
Explanation / Answer
Please make sure that you have a file named "in.txt" because thats the file name being passed. Fixed various issue in your code.
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class ReadMessage {
public static String[] read(String inFile) {
try {
Scanner read = new Scanner(new FileReader(inFile));
int n = read.nextInt();
String[] lines2 = new String[n];
for (int i = 0; i < lines2.length; i++) {
lines2[i] = read.nextLine();
}
read.close();
return lines2;
} catch (IOException e) {
System.out.println("can't read: " + inFile);
System.exit(-1);
}
return null;
}
public static void main(String[] args) {
String[] lines = read("in.txt");
System.out.println(Arrays.toString(lines));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.