[英]How can I read a String from a file split it into characters and put it in to a 2D array?
[英]How to read information from file and put it back into String array?
我有一個任務,我需要從文件中讀取信息。 文件中的信息格式為:倫敦莫斯科....我總共有 7 個城市和 7 行。 我需要讀取城市名稱並將它們放回字符串數組中。 當我測試這段代碼時,我收到一條消息java.lang.ArrayIndexOutOfBoundsException: 0
。
我將不勝感激有關如何解決問題的任何想法。
import java.util.Scanner;
import java.io.*;
public class Input {
static Scanner keyboard, input;
static PrintWriter output;
static String[] namesCities;
static String name = "";
static int index;
public static void main(String args[]) {
try
{
System.out.println("Please, enter the name of input file");
keyboard = new Scanner(System.in);
name = keyboard.nextLine();
File file = new File(name);
input = new Scanner(file);
namesCities = new String[index];
for (int index = 0; index < 7; index++)
{
namesCities[index] = input.next();
}
}
catch
{
catch (IOException a)
{
System.out.println("Could not find file " + name);
name = keyboard.nextLine();
}
}
}
在您現有的代碼中,您沒有正確初始化index
變量,因為它的值保持為零並且您的namesCities = new String[index];
導致大小為零的數組,導致ArrayIndexOutOfBoundsException
。 您需要將其初始化為7
例如namesCities = new String[7];
避免在類級別聲明變量,其范圍不應超過所需時間。 就像代碼中的Scanner
對象或文件名一樣,如果管理不當,它們似乎沒有任何長期存在的價值,它們可能會導致資源泄漏。 試試這個代碼,它在一行中使用Files.readAllLines
讀取您的文件,並作為List
對象返回,其中List
中的每個項目都包含您在文件中的行。 然后您可以使用toArray
將其轉換為數組。
public static void main(String[] args) throws Exception {
System.out.println("Please, enter the name of input file");
Scanner keyboard = new Scanner(System.in);
String name = keyboard.nextLine();
keyboard.close();
List<String> lines = Files.readAllLines(Paths.get(name));
String[] nameCities = lines.toArray(new String[lines.size()]);
System.out.println(Arrays.toString(nameCities));
}
如果您在理解此處的任何代碼時遇到困難,請告訴我。
所以我寫了一些小東西。 這假設您已經進行了所有正確的導入,並且沒有進行實際檢查以確保文件大小正確。 如果您絕對必須使用 for 循環,您可以將我的循環更改為告訴 counter < 7 (not counter <= 7)<---這將引發索引錯誤的 for 循環。
我更改了一些內容,但可以隨意更改它們,我將變量移到 main 中,因為您沒有理由將它們保留為實例變量。 我還將您的 .nextLine() 更改為 .next() 原因是因為 .nextLine() 將所有內容都告訴它遇到了一個新行字符,而 .next() 只告訴它遇到了一個空白字符。 如果這是您想要的行為,您可以將這兩種方式改回原來的方式。
public class Input{
public static void main(String[] args){
System.out.println("Please Enter the name of the input file");
keyboard = new Scanner(System.in);
name = keyboard.next();
File file = new File(name);
input = new Scanner(file);
String[] nameCities = new String[7];
int counter = 0;
while(input.hasNext()){
nameCities[counter] = input.next();
counter++;
}
keyboard.close()//don't forget to close your scanner
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.