如何从文本文件中获取数字,而忽略前面的单词?

时间:2013-11-01 22:20:58

标签: java printwriter

所以我有一个.txt文件,只有这个作为内容:

pizza 4
bowling 2
sleepover 1

我要做的是,例如在第一行,忽略“披萨”部分,但将4保存为整数。

这是我到目前为止的一小段代码。

public static void addToNumber() {

  PrintWriter writer;
  Int pizzaVotes, bowlingVotes, sleepOverVotes;

   try {
     writer = new PrintWriter(new FileWriter("TotalValue.txt"));
     }
   catch (IOException error) {
     return;
     }


   // something like if (stringFound)
   //      ignore it, skip to after the space, then put the number
   //      into a variable of type int
   //      for the first line the int could be called pizzaVotes

        //   pizzaVotes++;

        //  then replace the number 4 in the txt file with pizzaVote's value
        //  which is now 5.
        //  writer.print(pizzaVotes); but this just overwrites the whole file.

        // All this  will also be done for the other two lines, with bowlingVotes
        // and sleepoverVotes.

      writer.close();

   } // end of method

我是初学者。正如您所看到的,我的实际功能代码很短,我不知道如何继续。如果有人愿意指出我正确的方向,即使你只是给我一个网站的链接,这将是非常有帮助的......

编辑:我愚蠢地认为PrintWriter可以读取文件

3 个答案:

答案 0 :(得分:0)

我不完全理解你的问题,所以如果你想要一些更明确的建议请评论

以下是您将在Java中使用的常见模式:

Scanner sc=new Scanner(new File(.....));

while(sc.hasNextLine(){
    String[] line=sc.nextLine().split("\\s");//split the string up by writespace
    //....parse tokens
 }
 // now do something

在您的情况下,您似乎想要执行以下操作:

Scanner sc=new Scanner(new File(.....));
FrequencyCloud<String> votesPerActivity=new FrequencyCloud<String>()
while(sc.hasNextLine(){
    String[] line=sc.nextLine().split("\\s");//split the string up by writespace
    //if you know the second token is a number, 1st is a category you can do 
    String activity=line[0];
    int votes=Integer.parseInt(line[1]);
    while(votes>0){
        votesPerActivity.incremendCloud(activity);//no function in the FrequencyCloud for mass insert, yet
        votes--;
    }
}


///...do whatever you wanted to do, 
//votesPerActivity.getCount(activity) gets the # of votes for the activity
/// for(String activity:votesPerActivity.keySet()) may be a useful line too

FrequencyCloud:http://jdmaguire.ca/Code/JDMUtil/FrequencyCloud.java

答案 1 :(得分:0)

实际上这很简单。你需要的只是一个扫描仪,它的功能是nextInt()

        // The name of the file which we will read from
        String filename = "TotalValue.txt";

        // Prepare to read from the file, using a Scanner object
        File file = new File(filename);
        Scanner in = new Scanner(file);

        int value = 0;

        while(in.hasNextLine()){
             in.next();
             value = in.nextInt();
             //Do something with the value here, maybe store it into an ArrayList.
        }

我没有测试过这段代码,但它应该可以工作,但是while循环中的value将是当前行的当前值。

答案 2 :(得分:0)

String num = input.replaceAll(“[^ 0-9]”,“”)。trim();

为了多样性,这使用正则表达式。