簡體   English   中英

如何從文本文件中獲取數字,而忽略其前面的單詞?

[英]How to grab a number from a text file, while ignoring the word in front of it?

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

我不完全了解您的問題,如果您需要更清晰的建議,請發表評論

這是您將在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

實際上,這非常簡單。 您需要的只是一個掃描儀,它的功能是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循環將是當前行的當前值。

字符串num = input.replaceAll(“ [^ 0-9]”,“”).trim();

為了多樣化,使用正則表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM