簡體   English   中英

輸入文本文件上的正則表達式浮點數

[英]Regular expression float number on a input text file

我需要做一份工資報告。 您必須鍵入具有文本信息的文件。 程序檢查文件是否存在。 然后,制作程序的輸出文件。 該程序在文本文件中打印工人的姓名,工作時間和比率。 我的程序只運行最后一組數字。

 import java.text.NumberFormat;
 import javax.swing.JTextArea;
 import java.awt.Font;
 import javax.swing.JOptionPane;
 import java.util.Scanner;
 import java.io.*;

 public class Homework {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {

    String answer, filename;


    filename = JOptionPane.showInputDialog("Enter the Input File Path:");

    File input = new File(filename);
    if (!input.exists()) {
        JOptionPane.showMessageDialog(null, "The input file:\n" + filename + "\ndoes not exist!");
        System.exit(0);
    }
    filename = JOptionPane.showInputDialog("Enter the Output File Path:");

    File output = new File(filename);
    if (output.exists()) {
        answer = JOptionPane.showInputDialog("The output file alaready exist!\nDo you want to overwrite it?");
        if (!answer.toLowerCase().equals("yes")) {
            System.exit(0);
        }
    }






    PrintWriter outFile = new PrintWriter(filename);
    Scanner in = new Scanner(input);

    double numberWords = 0, countNumber = 0;


   double value;

    String num, words, message;
    String amtStr, line = "";

    String alphaRegex = ".*[A-Za-z].*";
    String numRegex = ".*[0-9].*";



    while (in.hasNext()) {
        words = in.next();

        if (words.matches(alphaRegex)) {

            numberWords++;
            message = "The name is "+words+"\n"; //The Line is but leave +line+

     JOptionPane.showMessageDialog (null, message);



        } else if (words.matches(numRegex)) {
            countNumber++;
           num = in.next();


           message = "The number is "+num+"\n"; //The Line is but leave +line+

     JOptionPane.showMessageDialog (null, message);

             }



}
}

}

導致此問題的原因不是您的正則表達式。 它是while循環中的if語句。 當單詞匹配numRegex時,然后將.next()簽名為num,導致掃描程序跳過當前單詞並選擇下一個單詞,在您的情況下,該單詞也恰好是num。

以此替換while循環,它將起作用(我已經測試了代碼):

while (in.hasNext()) {
    words = in.next();

    if (words.matches(alphaRegex)) {
        numberWords++;
        message = "The name is "+words+"\n";
        JOptionPane.showMessageDialog (null, message);

    } else if (words.matches(numRegex)) {
        countNumber++;
        num = words; // instead of num = in.next()
        message = "The number is "+num+"\n";
        JOptionPane.showMessageDialog (null, message);
    }
}

我假設您正在尋找一個正則表達式來標識文本中的浮點數。 如果是這樣,這里是一個:

"(\\.\\d+)|(\\d+(\\.\\d+)?)"

這匹配任何后跟一個或多個數字的任何單獨的十進制數,或匹配一個后跟一個或多個數字的可選十進制的任何數字序列。 請注意,如果這是一個問題,則不能解決前導零。

該網站是用於構建和測試正則表達式的絕佳資源:

http://www.regexr.com/

暫無
暫無

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

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