试图从文件中读取每行代码

时间:2016-01-14 05:38:13

标签: java

我试图从.txt文件中读取以下信息

  

Griffey HHOHOKWOHKSPOOWSH
  广场OOHHHKPSOHOOHWWHO
  Pudge HHHHKOOHHHSWWHHOP

我需要能够分隔名称,然后是每个单独的字母(最好是来自charAt。每个字母代表Hit,Out,Walk,Pitch by Pitch或Strikeout。我必须计算每个玩家&# 39; s击球平均值,基本百分比,#Hits,#Walks,#Hit由Pitch。最后我必须找到每个类别中3的领导者。

到目前为止,我真的被困在能够将名字分开并拔出每封信件。

到目前为止,这是我的代码:

import java.util.*;

public class readStats
{
public static void main(String[] args) throws Exception 
{
//Pull stats.txt File
java.io.File file = new java.io.File("stats.txt");

//Create Scanner
Scanner input = new Scanner(file);
//Read data from file
    while (input.hasNextLine()) 
    {
    String name1 = input.next();
    String griffey1 = input.nextLine();
    char batArray = griffey1.charAt(0);
    //char griffey2 = input.next().charAt(1);
    System.out.print(name1);
    //System.out.println(griffey1);
    //System.out.println(batArray[1]);
    }
}

}

我的输出是:

GriffeyPiazzaPudge

更新

好的,我有每个"项目的变量"现在使用此代码:

import java.util.*;

public class readStats
{
public static void main(String[] args) throws Exception 
{
//Pull stats.txt File
java.io.File file = new java.io.File("stats.txt");

//Create Scanner
Scanner input = new Scanner(file);
//Read data from file
    while (input.hasNextLine()) 
    {
    String name1 = input.next();
    String stats1 = input.next();
    String name2 = input.next();
    String stats2 = input.next();
    String name3 = input.next();
    String stats3 = input.next();
    System.out.println(name1);
    System.out.println(stats1);
    System.out.println(name2);
    System.out.println(stats2);
    System.out.println(name3);
    System.out.println(stats3);
    }
}

}

输出:

格里菲

HHOHOKWOHKSPOOWSH

广场

OOHHHKPSOHOOHWWHO

屠夫

HHHHKOOHHHSWWHHOP

7 个答案:

答案 0 :(得分:1)

读取每一行然后使用

String words[ ] = String.split (" ");

words[0] = the name
words[1] = the code

然后可以使用

将单词[1]拆分为char数组

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray()

阅读行

Scanner input = new Scanner(file);
while (input.hasNextLine()) 
{
    String line = input.nextLine();
    .

答案 1 :(得分:0)

.main {
    position: relative;
    width: 100%;
    border: 1px solid black;
}

.dummy {
    padding-top: 100%; /* forces 1:1 aspect ratio */
}

.img-container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;

txt文件

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.*;

public class readStats
{
public static void main(String[] args) throws Exception 
{
java.io.File file = new java.io.File("D:\\user\\Mahfuz\\stats.txt");

BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
String spliter = ",";
try {
  while ((line = br.readLine()) != null) {
    String[] eachLise= line.split(spliter);
    String griffey1 =eachLise[1];
     for(int i=0; i<griffey1.length(); i++){
        char batArray = griffey1.charAt(i);
         System.out.println(batArray);
    }
}
}
    catch (FileNotFoundException e) {
  e.printStackTrace();
}

输出

Griffey,HHOHOKWOHKSPOOWSH
Piazza,OOHHHKPSOHOOHWWHO
Pudge,HHHHKOOHHHSWWHHOP

答案 2 :(得分:0)

您可以使用正则表达式获取名称:

  

注意:将stats.txt放在类文件的同一目录

RegEx
^(\\w+)[^\\s]

|-- ^(\\w+) => starts with word one or more
|-- [^\\s] => not contain space character 
import java.io.*;
import java.util.*;
import java.util.regex.*;

public class ReadStats {

    public static void main(String[] args) {
        try {
            //Pull stats.txt File
            File file = new File("stats.txt");

            //Create Scanner
            Scanner input = new Scanner(file);
            //Read data from file
            Pattern pattern = Pattern.compile("^(\\w+)[^\\s]");
            while (input.hasNextLine()) {
                String line = input.nextLine();
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    System.out.print(matcher.group());
                }
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }

}

答案 3 :(得分:0)

好的,我现在有了这个代码。这有助于我收到每封信,但我想知道是否有任何方法可以制作循环或更快/占用更少行的东西?

import java.util.*;

public class readStats
{
public static void main(String[] args) throws Exception 
{
//Pull stats.txt File
java.io.File file = new java.io.File("stats.txt");

//Create Scanner
Scanner input = new Scanner(file);
//Read data from file
    while (input.hasNextLine()) 
    {
    String name1 = input.next();
    String stats1 = input.next();
    String name2 = input.next();
    String stats2 = input.next();
    String name3 = input.next();
    String stats3 = input.next();
    char OneABname1 = stats1.charAt(0);
    char TwoABname1 = stats1.charAt(1);
    System.out.println(name1);
    System.out.println(stats1);
    System.out.println(name2);
    System.out.println(stats2);
    System.out.println(name3);
    System.out.println(stats3);
    System.out.println(OneABname1);
    System.out.println(TwoABname1);
    }
}

}

<强>输出

Griffey

HHOHOKWOHKSPOOWSH

Piazza

OOHHHKPSOHOOHWWHO

Pudge

HHHHKOOHHHSWWHHOP

H

H

我的最终输出看起来像这样写入另一个.txt文件:

个人统计数据 - 新行上的每个项目

名称

BA:

OB%:

H:

BB

K:

HBP:

空行

联盟领导人 - 新线上的每个项目

联盟领导人头球

BA:

OB%:

H:

BB

K:

HBP:

答案 4 :(得分:0)

以下代码解析每个玩家统计信息,将每个玩家的统计信息打印到控制台,然后显示每个类别中的领导者。正如一些人已经提到的,更好的长期解决方案可能是将每个玩家的统计数据封装到一个类中,并使用正式的数据结构,例如Map

public class readStats {
    public static int getStat(String letter, String stats) {
        int count = stats.length() - stats.replace(letter, "").length();

        return count;
    }

    public static void main(String[] args) {
        String hitsLeader = null;
        String outsLeader = null;
        String walksLeader = null;
        String hitsByPitchLeader = null;
        String strikeoutsLeader = null;
        int maxHits = 0;
        int maxOuts = 0;
        int maxWalks = 0;
        int maxHitsByPitch = 0;
        int maxStrikeouts = 0;

        java.io.File file = new java.io.File("stats.txt");
        Scanner input = new Scanner(file);

        while (input.hasNextLine()) {
            String line = input.nextLine();
            String[] parts  = line.split(" ");
            int hits        = getStat("H", parts[1]);
            int outs        = getStat("O", parts[1]);
            int walks       = getStat("W", parts[1]);
            int hitsByPitch = getStat("P", parts[1]);
            int strikeouts  = getStat("S", parts[1]);
            double ba = (double)hits / parts[1].length();
            double obp = (double)(hits + walks + hitsByPitch) / parts[1].length();

            System.out.println("Player " + parts[0] + " has the following stats:");
            System.out.println("hits: " + hits);
            System.out.println("outs: " + outs);
            System.out.println("walks: " + walks);
            System.out.println("hits by pitch: " + hitsByPitch);
            System.out.println("strikeouts: " + strikeouts);
            System.out.println("batting average: " + ba);
            System.out.println("on base percentage: " + obp);

            if (hits > maxHits) {
                maxHits = hits;
                hitsLeader = parts[0];
            }

            if (outs > maxOuts) {
                maxOuts = outs;
                outsLeader = parts[0];
            }

            if (walks > maxWalks) {
                maxWalks = walks;
                walksLeader = parts[0];
            }

            if (hitsByPitch > maxHitsByPitch) {
                maxHitsByPitch = hitsByPitch;
                hitsByPitchLeader = parts[0];
            }

            if (strikeouts > maxStrikeouts) {
                maxHits = hits;
                strikeoutsLeader = parts[0];
            }
        }

        // print out leaders from all categories
        System.out.println("Leader in hits is: " + hitsLeader);
        System.out.println("Leader in outs is: " + outsLeader);
        System.out.println("Leader in walks is: " + walksLeader);
        System.out.println("Leader in hits by pitch is: " + hitsByPitchLeader);
        System.out.println("Leader in strikeouts is: " + strikeoutsLeader);
    }
}

答案 5 :(得分:0)

您可以使用以下代码

public static void main(String[] args) throws FileNotFoundException {              
                    //Pull stats.txt File
        java.io.File file = new java.io.File("c:/stats.txt");
        //Create Scanner
        Scanner input = new Scanner(file);
        //Read data from file
            while (input.hasNextLine()) 
            {
            String name1 = input.next();
            String griffey1 = input.nextLine();


            char[] batArray = griffey1.trim().toCharArray();

            System.out.println(name1);
             System.out.println(griffey1);
            for(char c:batArray)
            {
                System.out.println(c);
            }              
            }
            }

答案 6 :(得分:0)

以下是解析每个玩家并构建每个统计数据的方法:


    import java.io.File;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Scanner;

    public class BaseballParser {

        class Player {
            String player;
            Map statCounts = new HashMap();

            public String toString() {
                StringBuilder sb = new StringBuilder();
                sb.append("Player: ").append(player).append("\n");
                for ( Character c : statCounts.keySet() ) {
                    sb.append(c).append(" : ").append(statCounts.get(c)).append("\n");
                }

                return sb.toString();
            }
        }

        public Map process(File file) throws Exception {
            if ( !file.exists() ) {
                throw new RuntimeException("Cannot locate " + file.getAbsolutePath() + " for processing.");
            }

            Scanner scanner = new Scanner(file);
            String nextLine;

            Map playerMap = new HashMap();

            while ( scanner.hasNext()  ){
                nextLine = scanner.nextLine();
                if ( nextLine.trim().length()  1 ) {
                System.out.println("Usage: BaseballParser [path to stats file]");
                System.exit(1);
            }
            BaseballParser parser = new BaseballParser();
            Map playerStats = parser.process(new File(s[0]));

            playerStats.values().stream().forEach(System.out::println);
        }


    }

输出:


Player: Piazza
P : 1
S : 1
W : 2
H : 6
K : 1
O : 6

Player: Pudge
P : 1
S : 1
W : 2
H : 9
K : 1
O : 3

Player: Griffey
P : 1
S : 2
W : 2
H : 5
K : 2
O : 5

希望这有帮助。