簡體   English   中英

從輸入文件中讀取多項式(Java 中)

[英]Reading Polynomials from Input File (in Java)

我需要從文件中讀取多項式。 我面臨的問題是系數是否超過一位或是否有負號,我不知道如何讓程序識別多個數字是單個 integer。 手動執行時,這將使我的代碼變得非常復雜,因為我需要讓程序“了解”它的周圍環境,例如何時啟動和停止。 那么,有沒有可以用來解析這個的內置庫? (在我研究的時候,我發現了 Pattern 和 Matcher 類,但不確定它是否可以在這種情況下使用)。

例如,我知道如何為這個 2x^2 + 4x + 8 編碼,但不知道如何為 -22x^2 - 652x + 898 編碼。

任何幫助表示贊賞。

我認為您使用模式和匹配器 Class 是正確的。 我發現了這篇文章: Splitting a string using Regex in Java

我不完全確定你想用這個做什么,或者文件看起來像什么,但是從上面的帖子中樞軸你可以做類似的事情:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Polynomial
{
    public static void main (String[] args)
    {
        final String poly = "-2123x^-232-22x^2-652x+898";
        // Does not handle a missing + or - on the first term
        Pattern p = Pattern.compile("([-+]\\d+)x?[\\^]?([-]?\\d+)?");
        Matcher m = p.matcher(poly);
        while (m.find())
        {
            System.out.println("Entire match:" + m.group(0));
            // Showing option of casting to Integer
            System.out.println("Coefficient:" + Integer.parseInt(m.group(1)));
            // Possibly null since the last few parts don't have exponent or x
            if (null != m.group(2))
            {
                System.out.println("Exponent:" + m.group(2));
            }

        }
        
    }
}

暫無
暫無

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

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