【问题标题】:How to store an array of String as an enumeration type如何将字符串数组存储为枚举类型
【发布时间】:2016-03-06 18:59:26
【问题描述】:

我做了两个类,一个叫Card,一个叫Pack。 Card 类具有以下属性:

private String Name;
private int Magic;
private int Cunning;
private int Courage;
private int Wisdom;
private int Temper;

在 Pack 类中,我创建了一个文件读取器方法,用于读取我 PC 上的文件并将其每一行存储为字符串数组。例如,这是文本的一部分(不是代码):

 Pansy_Parkinson
 42
 21
 18
 19
 9
 Dean_Thomas
 40
 10
 35
 22
 4

My String array[] 将每一行存储为不同的索引。 我想做的,就是把这个String数组转换成Card类型的数组。 它应该在每个索引中存储一张具有 6 个属性的卡片..

所以我想我需要一个方法来转换它,并且我将通过这种方式根据之前的文本获得新的 2D Card 数组:

Card [][] ArrayOfCards = new Card [1][5];

请问您知道我该怎么做吗?

.................................................. ............ ..................................................... ........

非常感谢大家的宝贵帮助! 我尝试了所有代码,它们看起来很棒!但我不知道为什么它在我的主要或方法本身中显示错误..

这是我的 FileReader 类!

import java.io.File;
import java.util.Arrays;
import java.io.*; //To deal with exceptions
import java.util.*;
import java.util.Scanner;
import java.util.ArrayList;

public class ReadFile {

        private Scanner x;
        private String Path;

        public ReadFile (String ThePath){
            Path = ThePath;
        }

        public String[] openFile() throws IOException /*To throw any errors up the line*/
        {
            FileReader FR = new FileReader(Path);
            BufferedReader TextReader = new BufferedReader(FR);

            int NoOfLines = readLines();
            String[] TextData = new String[NoOfLines];

            for (int i = 0; i < NoOfLines; i++)
                TextData[i] = TextReader.readLine(); //Accesses the lines of text and stores them in the array

            TextReader.close();
            return TextData;
        }

        int readLines() throws IOException //Return the number of lines in the text
        {
            FileReader FR2 = new FileReader(Path);
            BufferedReader BF = new BufferedReader(FR2);

            String ALine;
            int NoOfLines = 0;

            while ((ALine = BF.readLine()) != null)//Read each line of text & stop when a null value's reached
            NoOfLines++;

            BF.close();
            return NoOfLines;
        }

}

我刚刚在 main 上读过它,如下所示:

 public static void main(String[] args) {
        // TODO code application logic here

        String FileName = "C:/Users/Anwar/Desktop/Potter.txt"; //Path of the file on my PC
        try {
            ReadFile File = new ReadFile(FileName); 
            String[] ArrayLines = File.openFile();
            for(int i = 0; i < ArrayLines.length; i++) 
                System.out.println(ArrayLines[i]);
            }
        catch (IOException e) /*Defiend object of type IOException*/ {
            System.out.println(e.getMessage());
        }}

任何人都可以帮助我吗?

【问题讨论】:

  • Card[] ArrayOfCards 应该足够了。为什么它必须是二维的?或者List&lt;Card&gt; 可能会更好
  • 我个人会在Card 类上创建一个静态Parse 方法,该方法采用string 并返回Card,或者如果string 的格式不正确则抛出异常.然后你只需要将代表Card 的字符串输入其中。另外我建议使用列表而不是数组。而且我认为你的 Pansy Parkinson 的脾气太低了。
  • 为什么不使用序列化方法?
  • 我同意@ASh。此外,您的问题中有一个 Java 和一个 c# 标记。您使用哪种语言?
  • @DarrenGourley 我猜是 Java。 someType[][] 是多维数组的定义方式,在 C# 中是 someType[,]

标签: java arrays type-conversion readfile


【解决方案1】:

因为您的问题有一个 c# 标签,所以我决定给出一个 c# 示例,您应该能够相当容易地将其转换为 java。

基本上我创建了一个Card 类,它有一个构造函数,它接受关于卡片的6 个统计信息。我保留了private 字段,因为它们在您的问题中是这样的。 我创建了一个for 循环,它遍历数组中的每个项目,一次有效地获取6 个项目并将它们传递给Card 构造函数。然后我们将此card 添加到我们的ListCards

我还添加了一个快速的 ToInt() 扩展来整理 Card 实例化。

会有更好的方法来做到这一点,但这解决了您向我们提出的问题。此示例中也没有错误处理。

    class Program
    {
        static void Main(string[] args)
        {
            var rawData = new string[]{
                 "Pansy_Parkinson",
                 "42",
                 "21",
                 "18",
                 "19",
                 "9",
                 "Dean_Thomas",
                 "40",
                 "10",
                 "35",
                 "22",
                 "4"
            };

            var Cards = new List<Card>();

            for(int i = 0; i < rawData.Length; i+=6)
            {
                var card = new Card(rawData[0 + i], rawData[1 + i].ToInt(), rawData[2 + i].ToInt(), rawData[3 + i].ToInt(), rawData[4 + i].ToInt(), rawData[5 + i].ToInt());
                Cards.Add(card);
            }
        }
    }

    public static class StringExtensions
    {
        public static int ToInt(this string item)
        {
            return Convert.ToInt32(item);
        }
    }

    public class Card
    {
        private string Name;
        private int Magic;
        private int Cunning;
        private int Courage;
        private int Wisdom;
        private int Temper;

        public Card(string name, int magic, int cunning, int courage, int wisdom, int temper)
        {
            Name = name;
            Magic = magic;
            Cunning = cunning;
            Courage = courage;
            Wisdom = wisdom;
            Temper = temper;
        }
    }

【讨论】:

    【解决方案2】:

    也许可以这样尝试:

    使用参数 String array[][] 为 Card 创建构造函数,这将是从文本文件创建的数组,第二个参数将是 int 数,它将说明在哪里搜索构造函数的数据

    构造函数应该像这样工作:

    Card(String[][] array, int numberForConstructor){
    
    this.name = array[numberForConstructor][0];
    this.magic = array[numberForConstructor][1];
    this.cunning = array[numberForConstructor][2];
    this.courage = array[numberForConstructor][3];
    this.temper = array[numberForConstructor][4];
    }
    

    然后你可以使用这个构造函数将新的 Card 对象放入 Array、List 或任何你想要的东西

    【讨论】:

      【解决方案3】:

      你应该为你的类 Card 创建 getter/setter,然后你就可以使用这个函数了。我不知道您使用哪种语言(c# 或 java),因此您必须调整下面的解决方案。

      public class Pack
      {
          public List<Card> cards = new List<Card>();
      
          public Pack(string filename)
          {
              // Your parsing function
              while ((line = readLine() != null)
              {
                  Card c = new Card();
                  c.setName(line);
                  c.setMagic(Convert.ToInt32(readLine());
                  c.setCunning(Convert.ToInt32(readLine());
                  c.setCourage(Convert.ToInt32(readLine());
                  c.setWisdom(Convert.ToInt32(readLine());
                  c.setTemper(Convert.ToInt32(readLine());
                  cards.add(c);
              }
          }
      }
      

      然后你要创建一个新包只需执行以下操作

      Pack p = new Pack("cards.txt");
      p.cards[0].getName();
      

      【讨论】:

        【解决方案4】:

        您的输入数组每行有一个卡片参数。所以我认为你只是在寻找这样的东西:

        public static Card[] convert(String[] arr){
            if(arr.length % 6 != 0){
                System.out.println("error in data");
                return null;
            }
            Card[] res = new Card[arr.length / 6];
        
            for(int i = 0; i < res.length; i++){
                String Name = arr[(i * 6) + 0];
                int Magic = Integer.parseInt(arr[(i * 6) + 1]);
                int Cunning  = Integer.parseInt(arr[(i * 6) + 2]);
                int Courage = Integer.parseInt(arr[(i * 6) + 3]);
                int Wisdom = Integer.parseInt(arr[(i * 6) + 4]);
                int Temper = Integer.parseInt(arr[(i * 6) + 5]);
                res[i] = new Card(Name, Magic, Cunning, Courage, Wisdom, Temper);
            }
        
            return res;
        }
        

        【讨论】:

          【解决方案5】:

          这可行:

          public Card ConvertArrayToCard(string[] array)
          {
                 Card card = new Card;
                 card.Name = array[0];
                 card.Magic= array[1];
                 card.Cunning= array[2];
                 card.Courage= array[3];
                 card.Wisdom= array[4];
                 card.Temper= array[5];
           }
          

          【讨论】:

            【解决方案6】:

            很多答案..这是另一个。

            你的班级;

            public class Pack
            {
               public string Name { get; set; }
               public int Magic { get; set; }
               public int Cunning { get; set; }
               public int Courage { get; set; }
               public int Wisdom { get; set; }
               public int Temper { get; set; }
            }
            

            然后是逻辑。这里面有一些内置的防御性编码机制。我会让你弄清楚的。

                        var lines = File.ReadAllLines(@"C:\temp2.txt");
                        List<Pack> mypack =  new List<Pack>();
                        Pack member = null;
                        int count = 0;
                        foreach (var line in lines)
                        {
                            int val;
                            count = (!int.TryParse(line, out val)) ? 0 : count + 1;
                            switch (count)
                            {
                                case 0:
                                    member = new Pack() { Name = line.Trim() };
                                    break;
                                case 1:
                                    member.Magic = val;
                                    break;
                                case 2:
                                    member.Cunning = val;
                                    break;
                                case 3:
                                    member.Courage = val;
                                    break;
                                case 4:
                                    member.Wisdom = val;
                                    break;
                                case 5:
                                    member.Temper = val;
                                    mypack.Add(member);
                                    break;
                            }
                        }
                        return mypack;
            

            【讨论】:

              猜你喜欢
              • 2013-11-02
              • 2015-06-19
              • 2014-07-23
              • 1970-01-01
              • 1970-01-01
              • 2018-02-14
              • 2021-07-21
              相关资源
              最近更新 更多