0

所以我有一个 .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 可以读取文件

4

3 回答 3

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

频率云:http: //jdmaguire.ca/Code/JDMUtil/FrequencyCloud.java

于 2013-11-01T22:48:10.480 回答
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.
        }

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

于 2013-11-02T02:14:20.947 回答
0

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

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

于 2013-11-02T02:44:56.960 回答