读取文件并将名称和数字存储在两个数组中 [英] Reading a file and storing names and numbers in two arrays

查看:117
本文介绍了读取文件并将名称和数字存储在两个数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个读取文件的程序,并将名称和分数存储在两个单独的数组中,但是我正在挣扎。这是我迄今为止。
我为名称创建了一个名称数组,但我很困惑,我将如何将名称复制到数组的每个索引。

  import java.io.File; 
import java.io.FileNotFoundException;
import java.util.Scanner;
$ b $ 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;

尝试{
扫描仪扫描仪=新的扫描仪(文件);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
String [] words = line.split(\t);
for(String word:words){
System.out.println(word);

$ b} catch(FileNotFoundException e){
e.printStackTrace();





我的文本文件是:


$ b $ / p>

  John James 60 
Kim Parker 80
Peter Dull 70
Bruce Time 20
史蒂夫·达姆90


解决方案

b
$ b

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


I'm working on a program that reads a file and stores the names and scores in two separate arrays, but I'm struggling. This is what I have so far. I created an array for names called names, but I'm confused how I would copy the names into each index of the array.

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();
  }
 }
}

My text file is:

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

解决方案

what about

  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++; 
   }

这篇关于读取文件并将名称和数字存储在两个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆