如何使用给定java文件中的字符串?

时间:2015-06-03 01:44:14

标签: java arrays string split

我开始学习java并且我坚持使用这个,让我说我有这个公共类Info在哪里有数据,那里有玩家的ID,名字和姓氏,联赛和最后一个数字1 =击球手和2 =投手,然后在其他2个属性就像击球手和投手表现,其中第一个是球员ID,其余只是数字来做计算和东西但是&# 39;没问题。

private String[] Data = {"30 Juan Perez Yankees American 1", 
                          "43 Pedro Perez Braves National 2",
                          "31 Carlos Maldonado Orioles National 1",
                          "44 Jose Canseco Phillips National 1",
                          "45 Jesus Kilmer Orioles National 2",
                          "32 Carlos Montana Braves National 2"};

private String[] Hitters = {"30 50 10 3",
                            "31 20 5 10",
                            "44 60 10 10"};


private String[] Pitchers = {"43 23.3 4 28", 
                             "45 50 2 10",
                             "32 20 6 4"};

这是来自练习测试,其中有一些其他类和需要完成的东西,我已经完成了那部分,但现在我必须在每个字符串数组中使用这些值,但我不知道如何要做到这一点,那里有很多东西,我不知道哪条路要走,或者哪条路是最好的方法,我知道我必须将它们拆分并将它们各自的值转换为解决价值问题,但拆分部分是我被困的地方。很抱歉打扰了所有人,并提前感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

...在数据中有玩家的ID,名字和姓氏,联赛,最后一个数字1 =击球手和2 =投手,然后在其他2个属性中就像击球手和投手表现在哪里第一个是玩家ID,剩下的只是用于计算和数据的数字,但这不是问题。

对于Data(例如Data [0]):

String [] info = Data[0].split(" "); // split on space
int playerID = Integer.parseInt(info[0]);
String firstName = info[1];
String lastName = info[2];
// and so on..

有关分割字符串的更多信息,请查看this

答案 1 :(得分:0)

尝试使用创建临时字符串数组的方法,然后硬编码以获取数据,如下所示

public static void main(String[] args) {
    String[] Data = {"30 Juan Perez Yankees American 1",
        "43 Pedro Perez Braves National 2",
        "31 Carlos Maldonado Orioles National 1",
        "44 Jose Canseco Phillips National 1",
        "45 Jesus Kilmer Orioles National 2",
        "32 Carlos Montana Braves National 2"};

    String[] Hitters = {"30 50 10 3",
        "31 20 5 10",
        "44 60 10 10"};

    String[] Pitchers = {"43 23.3 4 28",
        "45 50 2 10",
        "32 20 6 4"};

   /*
    Below is the details on splitting data. I also assume though its clear, that in Data array for first data
    for eg. "30 Juan Perez Yankees American 1"
    these are seperate columns
    30
    Juan Perez
    Yankees
    American
    1
    */
    String[] tempData;
    for(String data: Data){
        tempData=data.split(" ");
        //Now suppose you want to use the first data
        System.out.println("Your age is: "+tempData[0]);
        //Suppose you want the complete name
        String fullName = tempData[1]+" "+tempData[2];
        System.out.println("Name of the Player: "+fullName);
        /*if you just needed to display the name you can also do 
        System.out.println("Name of the Player: "+ tempData[1]+" "+tempData[2]);
        */

        /*Same you do for the rest*/


    }




}