焼きます:
私はこのような番号付きリスト内のユーザーと出力内容からファイル名を受け取ることになっているコードを持っている:https://imgur.com/a/CGd86xU
今、私はハードコーディングせずに私の出力に1. 2. 3.などを追加できるように見えることはできません、または私はコードファイルがあると、ファイルが同じディレクトリに存在していないかどうかを検出するために試みることができますかで、そのようなファイルが存在しないユーザーに伝えます。
私は、出力コードが正しくなどのファイルの内容を番号またはファイルユーザ入力が存在するかどう区別する例で示したが、マイナスたことをこれまでのコード。
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Q4 {
public static void main(String[] args) throws IOException {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter filename");
String fileName = scanner.nextLine();
File f = new File(fileName);
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = null;
System.out.println(""); //Intended to be empty as to allow the next line. So far that's the only way to get this part it to work.
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
注:私はコード含むファイルに、むしろ新たなんだそうええ...
agillgilla:
私はあなたが正しく求めているかを理解する場合は、ユーザーが指定したファイルの行ごとに行番号を印刷したいです。
もしそうなら、あなただけ追加することができますcounter
あなたが行毎にファイルを読み込む際に、変数を:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Q4 {
public static void main(String[] args) throws IOException {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter filename");
String fileName = scanner.nextLine();
File f = new File(fileName);
if (!f.exists()) {
System.out.println(fileName + " doesn't exist!");
return;
}
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = null;
System.out.println(""); //Intended to be empty as to allow the next line. So far that's the only way to get this part it to work.
int counter = 1;
while ((readLine = b.readLine()) != null) {
System.out.println(counter + ": " + readLine);
counter++;
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
私はまたかどうかを確認するためのチェックを追加File
使用して存在するFile.exists()
方法を。