2017-01-12 3 views
0

Я работаю над программой, которая читает файл и сохраняет имена и оценки в двух отдельных массивах, но я боюсь. Это то, что у меня есть до сих пор. Я создал массив имен, названных именами, но я смущен, как бы копировать имена в каждый индекс массива.Чтение файла и сохранение имен и номеров в двух массивах

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class ScannerReadFileSplit { 
    public static void main(String[] args) { 

File file = new File("NamesScore.txt"); 
String[] names = new String[100]; 
int[] scores = new int[100]; 
int i; 

try { 
     Scanner scanner = new Scanner(file); 
     while (scanner.hasNextLine()) { 
     String line = scanner.nextLine(); 
     String [] words = line.split("\t"); 
     for (String word: words) { 
      System.out.println(word); 
     } 
     } 
    } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
    } 
} 
} 

Мой текстовый файл:

John James  60 
Kim Parker  80 
Peter Dull  70 
Bruce Time  20 
Steve Dam  90 
+1

Какие имена? Вы ожидаете, что мы узнаем, как выглядит этот файл? – shmosel

ответ

1

Во-первых, вы хотите инициализировать i в 0 при объявлении его:

int i = 0; 

Затем, после расщепления линии вы можете тянуть данные из String[] и положите их в свои names и scores массивы:

String [] words = line.split("\t"); 

// The first element in 'words' is the name 
names[i] = words[0]; 

// The second element in 'words' is a score, but it is a String so we have 
// to convert it to an integer before storing it 
scores[i] = Integer.parseInt(words[1], 10); 

// Increment 'i' before moving on to the next line in our file 
i++; 

Не забудьте приступить к увеличению i, как показано на рисунке выше.

Существует некоторая проверка ошибок, что я затушевал. Вероятно, вы захотите проверить, что words имеет длину 2 после вашего звонка до split(). Также имейте в виду, что Integer.parseInt() может выкинуть NumberFormatException, если он не может проанализировать данные в столбце оценок как целое число.

1

насчет

int l = 0; 
    while (scanner.hasNextLine()) { 
    String line = scanner.nextLine(); 
    String [] words = line.split("\t"); 
    names[l] = words[0]; 
    scores[l] = Integer.parseInt(words[1]); 
    System.out.println(l + " - name: " + names[l] + ", score: " + scores[l]); 
    l++; 
    } 
1

Я попытался исправить свой код и при условии, встроенные комментарии, где я чувствовал, как вы пошли неправильно. На самом деле вы были близки к решению. Постарайтесь выяснить, что вы получаете в качестве вывода после строки кода, как

String[] words = line.split("\t"); 

Эта линия даст два строки (как это будет разделить строку в файл, который имеет только один вкладку отделенный имя и оценка) , И вы можете попробовать самостоятельно отлаживать. Как просто печать значения. например

System.out.println(words[0]); 

Это поможет вам продвинуться дальше.

Надеюсь, это поможет.

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class TwoArrays { 
    public static void main(String[] args) { 
     File file = new File("C:\\test\\textTest.txt"); 
     String[] names = new String[100]; 
     int[] scores = new int[100]; 
     int i = 0; 
     try { 
      Scanner scanner = new Scanner(file); 
      while (scanner.hasNextLine()) { 
       String line = scanner.nextLine(); 
       String[] words = line.split("\t"); 
       names[i] = words[0]; // storing value in the first array 
       scores[i] = Integer.parseInt(words[1]); // storing value in the 
                 // second array 
       i++; 
      } 
      /* 
      * This piece of code will give unnecessary values as you have 
      * selected an array of size greater than the values in the file for 
      * 
      * for(String name: names) { 
      *  System.out.println("Name:- "+name); 
      * } 
      * for(int score: scores) { 
      *  System.out.println("Score:- "+score); 
      * } 
      */ 
      // Better use the below way, here i am restricting the iteration till i 
      // i is actually the count of lines your file have. 
      for (int j = 0; j < i; j++) { 
       System.out.println("Name:- " + names[j] + "\t" + "Score:- " + scores[j]); 
      } 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
Смежные вопросы