【问题标题】:Read names/phone numbers from text file and store them into an array in java从文本文件中读取姓名/电话号码并将它们存储到java中的数组中
【发布时间】:2018-12-07 07:22:05
【问题描述】:

问题要我通过读取文本文件的前四个名称并将其存储到数组中来完成代码。

这里是要填写的代码。

import java.io.*;
import java.util.Scanner;


public class PersonDemo
{
  public static void main(String[] args)
  {
    File file = new File("phonedata.txt");
    Scanner infile = new Scanner(System.in);
    Person[] pArray = new Person[4];
    for(int i=0;i<4;i++)
    {
      String n = infile.nextLine();
      String p = infile.nextLine();

我应该在这里插入什么?

     }  
     infile.close();

   }
}    

正在使用的目标文件是:

public class Person
{
  private String name = "";
  private String phone ="";

public Person(String n, String p)
{
    name = n;
    phone = p;
}

public  Person()
{
    name ="";
    phone="";
}
public void setName(String n)
{
    name =n;
}
public void setPhone(String p)
{
    phone = p;
}
public String getName()
{
    return name;
}
public String getPhone()
{
    return phone;
}
public String toString()
{
    return "Name: "+name + "  Phone: " + phone;
}

}

正在使用的文本文件是:

奥利维亚

555-1111

提姆

555-2222

特蕾莎

555-3333

森林

555-4444

弗兰克

555-5555

西蒙

555-6666

现在我应该如何使用目标文件将文本存储到数组中我对代码应该是什么样子感到困惑?

【问题讨论】:

  • 你使用的是什么版本的java?
  • 我有点困惑。你为什么使用new Scanner(System.in);?您将读取应用程序的标准输入,而不是您想要读取的文件。尝试查看 FileReader 和 BufferedReader。我也有点困惑你为什么使用 Scanner 来达到这个目的(Javadoc 写道:一个简单的文本扫描器,可以使用正则表达式解析原始类型和字符串。)。
  • 这是我老师给的示例代码,我们应该填写它。
  • 你的老师可能想骗你,可能会告诉他这行不通,因为扫描仪使用了错误的输入。我想名字和电话号码之间的白线是复制粘贴造成的?如果这些白线应该在那里,那么代码也不会工作(因为你先读了一个名字,然后你读了一个空行)。
  • @tristanhoward :有什么答案对你有用吗?如果是,请考虑接受/支持他们。 What should I do when someone answers my question?

标签: java arrays object java.util.scanner


【解决方案1】:

欢迎来到 Stack Overflow @tristan

String p = infile.nextline();之后,做pArray[i] = n + " " + p

这应该使您的循环看起来像:

for(int i=0;i<4;i++)
{
  String n = infile.nextLine();
  String p = infile.nextLine();
  Person person = new Person(n, p); 
  pArray[i] = person;
}

这应该可以满足您的要求。

【讨论】:

  • 这不会编译,因为 pArraytype Person 而不是 String
  • 如何打印结果?
  • @NicholasK 绝对正确。我心不在焉,犯了错误
  • @tristanhoward 我已经更新了答案。现在如果你想打印它,你可以做for(Person p:person){p.toString();}
  • 它说 for each 不适用它需要一个数组。
【解决方案2】:

你可以使用这个逻辑:

for (int i = 0; i < 4; i++) {
   String name = infile.nextLine();
   infile.nextLine();               // skip a line because there is a blank line in between
   String phoneNum = infile.nextLine();
   infile.nextLine();               // here again skipping a blank line
   Person per = new Person(name, phoneNum); 
   pArray[i] = per;
} 

解释:

  1. 这里我们将姓名电话号码存储在字符串变量name中 和phoneNum
  2. 现在我们使用这些变量创建一个 Person 的 object,使用 参数化构造函数。
  3. 接下来,我们将这个对象赋给数组的对应索引。

您的扫描仪也应定义如下,以通过您的扫描仪对象infile读取文件

Scanner infile = new Scanner(file);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2013-11-19
    • 2019-07-26
    • 1970-01-01
    相关资源
    最近更新 更多