在我的程序中,它讀取一個名爲datafile.txt的文件... datafile.txt裏面是一個隨機的3行字。我的程序所做的是讀取用戶輸入的文件,然後他們可以輸入Line#和Word#,並且它會告訴他們在該位置的單詞..例如..從java中的datafile.txt讀取某些語句
什麼是文件閱讀?
datafile.txt
請輸入的行號和字數目(第一行是1)。
這個詞是:
我的問題是,我的程序讀取在TXT文檔爲0,1,2 3線和字從0開始。所以,閱讀第一行中的第一個單詞必須輸入0,0而不是1,1。我想要做的是讓它工作,以便他們可以輸入1,1而不是0,0。不知道我的問題是什麼,現在,這裏是我的代碼....
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class readingFile {
/**
* @param args
* @throws IOException
* @throws validException
*/
public static void main(String[] args) throws IOException, checkException
{
System.out.println("Enter file name: ");
Scanner keyboard = new Scanner(System.in);
BufferedReader inputStream = null;
ArrayList<String> file = new ArrayList<String>();
String fileName = keyboard.next();
System.out.println ("The file " + fileName +
" has the following lines below: ");
System.out.println();
try
{
inputStream = new BufferedReader(new FileReader(fileName));
ArrayList<String> lines = new ArrayList<String>();
while(true)
{
String line = inputStream.readLine();
if(line ==null)
{
break;
}
Scanner itemnize = new Scanner(line);
while(itemnize.hasNext())
{
lines.add(itemnize.next());
}
lines.addAll(lines);
System.out.println(lines+"\n");
}
System.out.println("Please enter the line number and word number");
int index1 = keyboard.nextInt();
int index = keyboard.nextInt();
System.out.println("The word is: "+ lines.get(index));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
}
inputStream.close();
}
private static void checkValid(ArrayList<String> items, int index) throws checkException
{
throw new checkException("Not Found");
}
}
難道你只是在索引和索引1中減去一個之前訪問數據? –
按照慣例,Java集合的索引從0開始。但是,您只需從用戶輸入的值中減去1即可。我會寫一個答案,但請先嚐試自己修復你的代碼,並添加發生的事情和你對這個問題的期望。 –
我確實寫過會發生什麼事以及我想要做什麼 –