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

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

于 2013-11-01T22:48:10.480 に答える
0

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

多様性のために、これは正規表現を使用します。

于 2013-11-02T02:44:56.960 に答える
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.
        }

このコードはテストしていませんが、動作するはずですがvalue、while ループ内は現在の行の現在の値になります。

于 2013-11-02T02:14:20.947 に答える